// Package rooms lets AI agents (or people) fight a brawl live, round by round. // // A room holds one match on the brawl rules, cut into a few long rounds (5 // by default). Each round both players read the live state (StateJSON), // try plans for free (PlanPreview), then send their plan in two steps: // // 1. Seal: send a fingerprint of the plan (see PlanHash), so the other side // can't copy it. // 2. Reveal: send the plan itself, the secret salt and a short thought. // // When both plans are revealed, the chain plays the round. A player who // misses a deadline is played by the fallback bot they picked when joining, // so nobody can stall a room. Help() describes every call as JSON; Render // draws the live board for gnoweb. package rooms import ( "chain" "chain/runtime" "crypto/sha256" "encoding/hex" "strconv" "strings" rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v2" "gno.land/p/nt/avl/v0" "gno.land/p/nt/ufmt/v0" "gno.land/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/mybots/v2" ) const ( MinRounds = 3 MaxRounds = 8 MinSeconds = 60 // shortest room match MaxSeconds = 300 // longest room match MinPhase = 15 // blocks, about a minute MaxPhase = 1000 DefaultPhase = 40 BlockSeconds = 4 // rough time per block on testnet, for secondsLeft MaxThought = 140 MaxName = 20 MaxPlan = 500 MaxPreviews = 8 keysPrefix = "keys:" ) // Phases of a room. const ( Waiting = iota // created, waiting for a second player Sealing // both players send a sealed plan Revealing // both players reveal their plans Done // the match is over ) var phaseNames = [4]string{"waiting", "sealing", "revealing", "done"} // A Player is one side of a room. type Player struct { Addr address Name string Class int Fallback int // bot that plays when this player misses a round Seal string // fingerprint of the plan for this round Plan string // revealed plan for this round Thought string Revealed bool Missed int // rounds the fallback bot played Inputs string // every input so far, one character per tick Thoughts string // every round's thought, joined by "\n" } // A Room is one live match. type Room struct { ID int Seed uint32 Rounds int RoundTicks int MatchTicks int PhaseBlocks int Round int Phase int Deadline int64 // block height when the current phase may be forced on P [2]*Player Snap string // the live match, packed (see brawl.Snapshot); "" when not live BotSnap [2]string // each fallback bot's memory Gold [2]int // final score, once done Last string // what happened last round, as JSON (see LastResult) Spar bool // a solo sparring room: side B is always a bot Created int64 } var ( rooms avl.Tree // zero-padded id -> *Room nextID = 1 ) func key(id int) string { s := strconv.Itoa(id) return strings.Repeat("0", 10-len(s)) + s } func mustRoom(id int) *Room { v := rooms.Get(key(id)) if v == nil { panic("no room #" + strconv.Itoa(id)) } return v.(*Room) } func height() int64 { return runtime.ChainHeight() } func cleanText(s string, max int, what string) string { s = strings.TrimSpace(s) if len(s) > max { panic(what + ": " + strconv.Itoa(max) + " characters at most") } for _, c := range s { if c < ' ' || c == '|' || c == '<' || c == '>' || c == '"' || c == '\\' { panic(what + ": plain text only") } } return s } // MyBot as a fallback is the bot you saved in the mybots realm. const MyBot = 3 func checkPlayer(class, fallback int, addr address) { if class < rules.Hunter || class > rules.Reader { panic("class: 0 hunter, 1 brawler, 2 coward, 3 trickster, 4 reader") } if fallback < rules.Easy || fallback > MyBot { panic("fallback: 0 easy, 1 normal, 2 hard bot, 3 your saved bot") } if fallback == MyBot && mybots.Profile(addr.String()) == "" { panic("fallback 3 needs a bot saved in mybots") } } // fallbackBot packs a player's fallback bot as it starts the match. A saved // bot is copied in when the match starts; if it was removed since, the // Normal bot plays instead. func fallbackBot(p *Player, seed uint32) string { if p.Fallback == MyBot { if prof := mybots.Profile(p.Addr.String()); prof != "" { return rules.NewProfileBot(rules.MustProfile(prof), seed).Snapshot() } return rules.NewBot(rules.Normal, seed).Snapshot() } return rules.NewBot(p.Fallback, seed).Snapshot() } // Create opens a room and returns its id. // - fallback: the bot that plays any round you miss (0 easy, 1 normal, // 2 hard, 3 the bot you saved in mybots) // - rounds: 3 to 8 (5 is a good default) // - seconds: the whole match, 60 to 300 (120 is a good default) // - phaseBlocks: how long each phase waits for a slow player, 15 to 1000 // blocks (40 is about 2.5 minutes; 1000 is about an hour, for slow agents) func Create(cur realm, name string, class, fallback, rounds, seconds, phaseBlocks int) int { checkPlayer(class, fallback, cur.Previous().Address()) if rounds < MinRounds || rounds > MaxRounds { panic("rounds: 3 to 8") } if seconds < MinSeconds || seconds > MaxSeconds { panic("seconds: 60 to 300") } if phaseBlocks < MinPhase || phaseBlocks > MaxPhase { panic("phaseBlocks: 15 to 1000") } ticks := seconds * rules.TPS r := &Room{ID: nextID, Rounds: rounds, RoundTicks: (ticks + rounds - 1) / rounds, MatchTicks: ticks, PhaseBlocks: phaseBlocks, Created: height()} r.P[0] = &Player{Addr: cur.Previous().Address(), Name: cleanText(name, MaxName, "name"), Class: class, Fallback: fallback} nextID++ rooms.Set(key(r.ID), r) chain.Emit("RoomCreated", "room", strconv.Itoa(r.ID), "player", r.P[0].Addr.String()) return r.ID } // Join takes the second place in a waiting room and starts the match. The // arena and coins come from the block the match starts in. func Join(cur realm, id int, name string, class, fallback int) { r := mustRoom(id) if r.Phase != Waiting { panic("room #" + strconv.Itoa(id) + " is already full") } addr := cur.Previous().Address() if addr == r.P[0].Addr { panic("you can't join your own room") } checkPlayer(class, fallback, addr) r.P[1] = &Player{Addr: addr, Name: cleanText(name, MaxName, "name"), Class: class, Fallback: fallback} h := height() r.Seed = uint32(h*7919+int64(id)*104729) % (1 << 31) r.Snap = rules.NewLength(r.Seed, r.P[0].Class, class, r.MatchTicks).Snapshot() r.BotSnap[0] = fallbackBot(r.P[0], r.Seed+1) r.BotSnap[1] = fallbackBot(r.P[1], r.Seed+2) r.Phase = Sealing r.Deadline = h + int64(r.PhaseBlocks) chain.Emit("RoomStarted", "room", strconv.Itoa(id), "seed", strconv.Itoa(int(r.Seed)), "arena", rules.ArenaName(r.Seed)) } // Spar opens a solo sparring room: you (side A) against a bot that plays a // learned style every round (profile: 22 characters, from LearnStyle or the // mybots realm). The match starts at once, and each round plays as soon as // you reveal. rounds, seconds and phaseBlocks work as in Create. func Spar(cur realm, name string, class, fallback int, profile string, rounds, seconds, phaseBlocks int) int { prof, err := rules.ParseProfile(profile) if err != nil { panic("profile: " + err.Error() + " (get one from LearnStyle)") } id := Create(cur, name, class, fallback, rounds, seconds, phaseBlocks) r := mustRoom(id) r.Spar = true r.P[1] = &Player{Name: "Sparring bot", Class: prof.Class, Fallback: -1} h := height() r.Seed = uint32(h*7919+int64(id)*104729) % (1 << 31) r.Snap = rules.NewLength(r.Seed, class, prof.Class, r.MatchTicks).Snapshot() r.BotSnap[0] = fallbackBot(r.P[0], r.Seed+1) r.BotSnap[1] = rules.NewProfileBot(prof, r.Seed+2).Snapshot() r.Phase = Sealing r.Deadline = h + int64(r.PhaseBlocks) chain.Emit("RoomStarted", "room", strconv.Itoa(id), "seed", strconv.Itoa(int(r.Seed)), "arena", rules.ArenaName(r.Seed), "spar", profile) return id } func side(r *Room, addr address) int { for s := 0; s < 2; s++ { if r.P[s] != nil && r.P[s].Addr == addr { return s } } panic("you are not playing in room #" + strconv.Itoa(r.ID)) } // PlanHash is the fingerprint to seal: hex sha256 of plan + "|" + salt. Read // it for free (vm/qeval) before sealing, or compute it yourself. func PlanHash(plan, salt string) string { sum := sha256.Sum256([]byte(plan + "|" + salt)) return hex.EncodeToString(sum[:]) } // Seal sends the fingerprint of your plan for this round. You can seal while // the room is sealing, and also late, while it is revealing, if you haven't // sealed yet. Sending the same fingerprint again is safe and does nothing. func Seal(cur realm, id int, hash string) { r := mustRoom(id) if r.Phase != Sealing && r.Phase != Revealing { panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ": nothing to seal") } if len(hash) != 64 { panic("hash: 64 hex characters (see PlanHash)") } p := r.P[side(r, cur.Previous().Address())] if p.Seal == hash { return // a retry of a seal that already landed } if p.Seal != "" { panic("you already sealed a different plan this round") } p.Seal = hash if r.Phase == Sealing && r.P[0].Seal != "" && (r.P[1].Seal != "" || r.Spar) { r.Phase = Revealing r.Deadline = height() + int64(r.PhaseBlocks) } } // Reveal sends your plan for this round, the salt you sealed it with, and a // thought of up to 140 characters that everyone watching will see. A plan // is plain text (see Help: plan words) or "keys:" followed by one input // character per tick. Revealing the same plan again is safe. func Reveal(cur realm, id int, plan, salt, thought string) { r := mustRoom(id) if r.Phase != Revealing { panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ", not revealing (seal first; see allowedActions)") } p := r.P[side(r, cur.Previous().Address())] if p.Seal == "" { panic("seal a plan before revealing it") } if PlanHash(plan, salt) != p.Seal { panic("this plan and salt don't match your seal") } if p.Revealed { return // a retry of a reveal that already landed } checkPlan(plan, r.RoundTicks) p.Plan = plan p.Thought = cleanText(thought, MaxThought, "thought") p.Revealed = true if r.P[0].Revealed && (r.P[1].Revealed || r.Spar) { play(r) } } // Advance moves a room on once its phase deadline has passed. Anyone may // call it. // - Sealing: if someone sealed, the room moves to revealing with a fresh // deadline, and whoever hasn't sealed can still seal and reveal in it. // If nobody sealed, both bots play the round. // - Revealing: the round is played; whoever hasn't revealed is played by // their fallback bot. func Advance(cur realm, id int) { r := mustRoom(id) if r.Phase != Sealing && r.Phase != Revealing { panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase]) } if height() < r.Deadline { panic("too early: " + strconv.Itoa(int(r.Deadline-height())) + " blocks left (see blocksLeft)") } if r.Phase == Sealing && (r.P[0].Seal != "" || r.P[1].Seal != "") { r.Phase = Revealing r.Deadline = height() + int64(r.PhaseBlocks) return } play(r) } // play runs one round. A player without a revealed plan is played by their bot. func play(r *Room) { g := rules.Restore(r.Snap) before := [2]int{g.F[0].Gold, g.F[1].Gold} var bots [2]rules.Actor var runs [2]*runner var chunk [2][]byte for s := 0; s < 2; s++ { if r.P[s].Revealed { runs[s] = newRunner(r.P[s].Plan) } else { if !(r.Spar && s == 1) { r.P[s].Missed++ } bots[s] = rules.RestoreActor(r.BotSnap[s]) } } for i := 0; i < r.RoundTicks && !g.Over(); i++ { var m, a [2]int for s := 0; s < 2; s++ { if runs[s] != nil { m[s], a[s] = runs[s].next(g, s) } else { m[s], a[s] = bots[s].Act(g, s) } chunk[s] = append(chunk[s], rules.Encode(m[s], a[s])) } g.Step(m[0], a[0], m[1], a[1]) } last := ufmt.Sprintf(`{"round":%d,"from":%d,"to":%d,"players":[`, r.Round, g.T-len(chunk[0]), g.T) for s := 0; s < 2; s++ { p := r.P[s] p.Inputs += string(chunk[s]) if bots[s] != nil { r.BotSnap[s] = bots[s].Snapshot() } if r.Round > 0 { p.Thoughts += "\n" } p.Thoughts += p.Thought if s == 1 { last += "," } last += ufmt.Sprintf(`{"name":%s,"bot":%t,"plan":%s,"thought":%s,"goldBefore":%d,"goldAfter":%d,"x":%d,"y":%d,"inputs":%s}`, strconv.Quote(p.Name), bots[s] != nil, strconv.Quote(p.Plan), strconv.Quote(p.Thought), before[s], g.F[s].Gold, g.F[s].X, g.F[s].Y, strconv.Quote(string(chunk[s]))) } r.Last = last + "]}" chain.Emit("Round", "room", strconv.Itoa(r.ID), "round", strconv.Itoa(r.Round), "tick", strconv.Itoa(g.T), "inputsA", string(chunk[0]), "inputsB", string(chunk[1]), "thoughtA", r.P[0].Thought, "thoughtB", r.P[1].Thought, "goldA", strconv.Itoa(g.F[0].Gold), "goldB", strconv.Itoa(g.F[1].Gold), ) for s := 0; s < 2; s++ { p := r.P[s] p.Seal, p.Plan, p.Thought, p.Revealed = "", "", "", false } r.Round++ if g.Over() { r.Phase = Done r.Gold = [2]int{g.F[0].Gold, g.F[1].Gold} r.Snap, r.BotSnap = "", [2]string{} // free the live state; the inputs replay it chain.Emit("RoomDone", "room", strconv.Itoa(r.ID), "goldA", strconv.Itoa(g.F[0].Gold), "goldB", strconv.Itoa(g.F[1].Gold)) return } r.Snap = g.Snapshot() r.Phase = Sealing r.Deadline = height() + int64(r.PhaseBlocks) }