Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

rooms.gno

13.06 Kb · 394 lines
  1// Package rooms lets AI agents (or people) fight a brawl live, round by round.
  2//
  3// A room holds one match on the brawl rules, cut into a few long rounds (5
  4// by default). Each round both players read the live state (StateJSON),
  5// try plans for free (PlanPreview), then send their plan in two steps:
  6//
  7//  1. Seal: send a fingerprint of the plan (see PlanHash), so the other side
  8//     can't copy it.
  9//  2. Reveal: send the plan itself, the secret salt and a short thought.
 10//
 11// When both plans are revealed, the chain plays the round. A player who
 12// misses a deadline is played by the fallback bot they picked when joining,
 13// so nobody can stall a room. Help() describes every call as JSON; Render
 14// draws the live board for gnoweb.
 15package rooms
 16
 17import (
 18	"chain"
 19	"chain/runtime"
 20	"crypto/sha256"
 21	"encoding/hex"
 22	"strconv"
 23	"strings"
 24
 25	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v2"
 26	"gno.land/p/nt/avl/v0"
 27	"gno.land/p/nt/ufmt/v0"
 28	"gno.land/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/mybots/v2"
 29)
 30
 31const (
 32	MinRounds     = 3
 33	MaxRounds     = 8
 34	MinSeconds    = 60  // shortest room match
 35	MaxSeconds    = 300 // longest room match
 36	MinPhase      = 15  // blocks, about a minute
 37	MaxPhase      = 1000
 38	DefaultPhase  = 40
 39	BlockSeconds  = 4 // rough time per block on testnet, for secondsLeft
 40	MaxThought    = 140
 41	MaxName       = 20
 42	MaxPlan       = 500
 43	MaxPreviews   = 8
 44	keysPrefix    = "keys:"
 45)
 46
 47// Phases of a room.
 48const (
 49	Waiting   = iota // created, waiting for a second player
 50	Sealing          // both players send a sealed plan
 51	Revealing        // both players reveal their plans
 52	Done             // the match is over
 53)
 54
 55var phaseNames = [4]string{"waiting", "sealing", "revealing", "done"}
 56
 57// A Player is one side of a room.
 58type Player struct {
 59	Addr     address
 60	Name     string
 61	Class    int
 62	Fallback int    // bot that plays when this player misses a round
 63	Seal     string // fingerprint of the plan for this round
 64	Plan     string // revealed plan for this round
 65	Thought  string
 66	Revealed bool
 67	Missed   int    // rounds the fallback bot played
 68	Inputs   string // every input so far, one character per tick
 69	Thoughts string // every round's thought, joined by "\n"
 70}
 71
 72// A Room is one live match.
 73type Room struct {
 74	ID          int
 75	Seed        uint32
 76	Rounds      int
 77	RoundTicks  int
 78	MatchTicks  int
 79	PhaseBlocks int
 80	Round       int
 81	Phase       int
 82	Deadline    int64 // block height when the current phase may be forced on
 83	P           [2]*Player
 84	Snap        string    // the live match, packed (see brawl.Snapshot); "" when not live
 85	BotSnap     [2]string // each fallback bot's memory
 86	Gold        [2]int    // final score, once done
 87	Last        string    // what happened last round, as JSON (see LastResult)
 88	Spar        bool      // a solo sparring room: side B is always a bot
 89	Created     int64
 90}
 91
 92var (
 93	rooms  avl.Tree // zero-padded id -> *Room
 94	nextID = 1
 95)
 96
 97func key(id int) string {
 98	s := strconv.Itoa(id)
 99	return strings.Repeat("0", 10-len(s)) + s
100}
101
102func mustRoom(id int) *Room {
103	v := rooms.Get(key(id))
104	if v == nil {
105		panic("no room #" + strconv.Itoa(id))
106	}
107	return v.(*Room)
108}
109
110func height() int64 { return runtime.ChainHeight() }
111
112func cleanText(s string, max int, what string) string {
113	s = strings.TrimSpace(s)
114	if len(s) > max {
115		panic(what + ": " + strconv.Itoa(max) + " characters at most")
116	}
117	for _, c := range s {
118		if c < ' ' || c == '|' || c == '<' || c == '>' || c == '"' || c == '\\' {
119			panic(what + ": plain text only")
120		}
121	}
122	return s
123}
124
125// MyBot as a fallback is the bot you saved in the mybots realm.
126const MyBot = 3
127
128func checkPlayer(class, fallback int, addr address) {
129	if class < rules.Hunter || class > rules.Reader {
130		panic("class: 0 hunter, 1 brawler, 2 coward, 3 trickster, 4 reader")
131	}
132	if fallback < rules.Easy || fallback > MyBot {
133		panic("fallback: 0 easy, 1 normal, 2 hard bot, 3 your saved bot")
134	}
135	if fallback == MyBot && mybots.Profile(addr.String()) == "" {
136		panic("fallback 3 needs a bot saved in mybots")
137	}
138}
139
140// fallbackBot packs a player's fallback bot as it starts the match. A saved
141// bot is copied in when the match starts; if it was removed since, the
142// Normal bot plays instead.
143func fallbackBot(p *Player, seed uint32) string {
144	if p.Fallback == MyBot {
145		if prof := mybots.Profile(p.Addr.String()); prof != "" {
146			return rules.NewProfileBot(rules.MustProfile(prof), seed).Snapshot()
147		}
148		return rules.NewBot(rules.Normal, seed).Snapshot()
149	}
150	return rules.NewBot(p.Fallback, seed).Snapshot()
151}
152
153// Create opens a room and returns its id.
154//   - fallback: the bot that plays any round you miss (0 easy, 1 normal,
155//     2 hard, 3 the bot you saved in mybots)
156//   - rounds: 3 to 8 (5 is a good default)
157//   - seconds: the whole match, 60 to 300 (120 is a good default)
158//   - phaseBlocks: how long each phase waits for a slow player, 15 to 1000
159//     blocks (40 is about 2.5 minutes; 1000 is about an hour, for slow agents)
160func Create(cur realm, name string, class, fallback, rounds, seconds, phaseBlocks int) int {
161	checkPlayer(class, fallback, cur.Previous().Address())
162	if rounds < MinRounds || rounds > MaxRounds {
163		panic("rounds: 3 to 8")
164	}
165	if seconds < MinSeconds || seconds > MaxSeconds {
166		panic("seconds: 60 to 300")
167	}
168	if phaseBlocks < MinPhase || phaseBlocks > MaxPhase {
169		panic("phaseBlocks: 15 to 1000")
170	}
171	ticks := seconds * rules.TPS
172	r := &Room{ID: nextID, Rounds: rounds, RoundTicks: (ticks + rounds - 1) / rounds, MatchTicks: ticks,
173		PhaseBlocks: phaseBlocks, Created: height()}
174	r.P[0] = &Player{Addr: cur.Previous().Address(), Name: cleanText(name, MaxName, "name"), Class: class, Fallback: fallback}
175	nextID++
176	rooms.Set(key(r.ID), r)
177	chain.Emit("RoomCreated", "room", strconv.Itoa(r.ID), "player", r.P[0].Addr.String())
178	return r.ID
179}
180
181// Join takes the second place in a waiting room and starts the match. The
182// arena and coins come from the block the match starts in.
183func Join(cur realm, id int, name string, class, fallback int) {
184	r := mustRoom(id)
185	if r.Phase != Waiting {
186		panic("room #" + strconv.Itoa(id) + " is already full")
187	}
188	addr := cur.Previous().Address()
189	if addr == r.P[0].Addr {
190		panic("you can't join your own room")
191	}
192	checkPlayer(class, fallback, addr)
193	r.P[1] = &Player{Addr: addr, Name: cleanText(name, MaxName, "name"), Class: class, Fallback: fallback}
194	h := height()
195	r.Seed = uint32(h*7919+int64(id)*104729) % (1 << 31)
196	r.Snap = rules.NewLength(r.Seed, r.P[0].Class, class, r.MatchTicks).Snapshot()
197	r.BotSnap[0] = fallbackBot(r.P[0], r.Seed+1)
198	r.BotSnap[1] = fallbackBot(r.P[1], r.Seed+2)
199	r.Phase = Sealing
200	r.Deadline = h + int64(r.PhaseBlocks)
201	chain.Emit("RoomStarted", "room", strconv.Itoa(id), "seed", strconv.Itoa(int(r.Seed)), "arena", rules.ArenaName(r.Seed))
202}
203
204// Spar opens a solo sparring room: you (side A) against a bot that plays a
205// learned style every round (profile: 22 characters, from LearnStyle or the
206// mybots realm). The match starts at once, and each round plays as soon as
207// you reveal. rounds, seconds and phaseBlocks work as in Create.
208func Spar(cur realm, name string, class, fallback int, profile string, rounds, seconds, phaseBlocks int) int {
209	prof, err := rules.ParseProfile(profile)
210	if err != nil {
211		panic("profile: " + err.Error() + " (get one from LearnStyle)")
212	}
213	id := Create(cur, name, class, fallback, rounds, seconds, phaseBlocks)
214	r := mustRoom(id)
215	r.Spar = true
216	r.P[1] = &Player{Name: "Sparring bot", Class: prof.Class, Fallback: -1}
217	h := height()
218	r.Seed = uint32(h*7919+int64(id)*104729) % (1 << 31)
219	r.Snap = rules.NewLength(r.Seed, class, prof.Class, r.MatchTicks).Snapshot()
220	r.BotSnap[0] = fallbackBot(r.P[0], r.Seed+1)
221	r.BotSnap[1] = rules.NewProfileBot(prof, r.Seed+2).Snapshot()
222	r.Phase = Sealing
223	r.Deadline = h + int64(r.PhaseBlocks)
224	chain.Emit("RoomStarted", "room", strconv.Itoa(id), "seed", strconv.Itoa(int(r.Seed)), "arena", rules.ArenaName(r.Seed), "spar", profile)
225	return id
226}
227
228func side(r *Room, addr address) int {
229	for s := 0; s < 2; s++ {
230		if r.P[s] != nil && r.P[s].Addr == addr {
231			return s
232		}
233	}
234	panic("you are not playing in room #" + strconv.Itoa(r.ID))
235}
236
237// PlanHash is the fingerprint to seal: hex sha256 of plan + "|" + salt. Read
238// it for free (vm/qeval) before sealing, or compute it yourself.
239func PlanHash(plan, salt string) string {
240	sum := sha256.Sum256([]byte(plan + "|" + salt))
241	return hex.EncodeToString(sum[:])
242}
243
244// Seal sends the fingerprint of your plan for this round. You can seal while
245// the room is sealing, and also late, while it is revealing, if you haven't
246// sealed yet. Sending the same fingerprint again is safe and does nothing.
247func Seal(cur realm, id int, hash string) {
248	r := mustRoom(id)
249	if r.Phase != Sealing && r.Phase != Revealing {
250		panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ": nothing to seal")
251	}
252	if len(hash) != 64 {
253		panic("hash: 64 hex characters (see PlanHash)")
254	}
255	p := r.P[side(r, cur.Previous().Address())]
256	if p.Seal == hash {
257		return // a retry of a seal that already landed
258	}
259	if p.Seal != "" {
260		panic("you already sealed a different plan this round")
261	}
262	p.Seal = hash
263	if r.Phase == Sealing && r.P[0].Seal != "" && (r.P[1].Seal != "" || r.Spar) {
264		r.Phase = Revealing
265		r.Deadline = height() + int64(r.PhaseBlocks)
266	}
267}
268
269// Reveal sends your plan for this round, the salt you sealed it with, and a
270// thought of up to 140 characters that everyone watching will see. A plan
271// is plain text (see Help: plan words) or "keys:" followed by one input
272// character per tick. Revealing the same plan again is safe.
273func Reveal(cur realm, id int, plan, salt, thought string) {
274	r := mustRoom(id)
275	if r.Phase != Revealing {
276		panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ", not revealing (seal first; see allowedActions)")
277	}
278	p := r.P[side(r, cur.Previous().Address())]
279	if p.Seal == "" {
280		panic("seal a plan before revealing it")
281	}
282	if PlanHash(plan, salt) != p.Seal {
283		panic("this plan and salt don't match your seal")
284	}
285	if p.Revealed {
286		return // a retry of a reveal that already landed
287	}
288	checkPlan(plan, r.RoundTicks)
289	p.Plan = plan
290	p.Thought = cleanText(thought, MaxThought, "thought")
291	p.Revealed = true
292	if r.P[0].Revealed && (r.P[1].Revealed || r.Spar) {
293		play(r)
294	}
295}
296
297// Advance moves a room on once its phase deadline has passed. Anyone may
298// call it.
299//   - Sealing: if someone sealed, the room moves to revealing with a fresh
300//     deadline, and whoever hasn't sealed can still seal and reveal in it.
301//     If nobody sealed, both bots play the round.
302//   - Revealing: the round is played; whoever hasn't revealed is played by
303//     their fallback bot.
304func Advance(cur realm, id int) {
305	r := mustRoom(id)
306	if r.Phase != Sealing && r.Phase != Revealing {
307		panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase])
308	}
309	if height() < r.Deadline {
310		panic("too early: " + strconv.Itoa(int(r.Deadline-height())) + " blocks left (see blocksLeft)")
311	}
312	if r.Phase == Sealing && (r.P[0].Seal != "" || r.P[1].Seal != "") {
313		r.Phase = Revealing
314		r.Deadline = height() + int64(r.PhaseBlocks)
315		return
316	}
317	play(r)
318}
319
320// play runs one round. A player without a revealed plan is played by their bot.
321func play(r *Room) {
322	g := rules.Restore(r.Snap)
323	before := [2]int{g.F[0].Gold, g.F[1].Gold}
324	var bots [2]rules.Actor
325	var runs [2]*runner
326	var chunk [2][]byte
327	for s := 0; s < 2; s++ {
328		if r.P[s].Revealed {
329			runs[s] = newRunner(r.P[s].Plan)
330		} else {
331			if !(r.Spar && s == 1) {
332				r.P[s].Missed++
333			}
334			bots[s] = rules.RestoreActor(r.BotSnap[s])
335		}
336	}
337	for i := 0; i < r.RoundTicks && !g.Over(); i++ {
338		var m, a [2]int
339		for s := 0; s < 2; s++ {
340			if runs[s] != nil {
341				m[s], a[s] = runs[s].next(g, s)
342			} else {
343				m[s], a[s] = bots[s].Act(g, s)
344			}
345			chunk[s] = append(chunk[s], rules.Encode(m[s], a[s]))
346		}
347		g.Step(m[0], a[0], m[1], a[1])
348	}
349	last := ufmt.Sprintf(`{"round":%d,"from":%d,"to":%d,"players":[`, r.Round, g.T-len(chunk[0]), g.T)
350	for s := 0; s < 2; s++ {
351		p := r.P[s]
352		p.Inputs += string(chunk[s])
353		if bots[s] != nil {
354			r.BotSnap[s] = bots[s].Snapshot()
355		}
356		if r.Round > 0 {
357			p.Thoughts += "\n"
358		}
359		p.Thoughts += p.Thought
360		if s == 1 {
361			last += ","
362		}
363		last += ufmt.Sprintf(`{"name":%s,"bot":%t,"plan":%s,"thought":%s,"goldBefore":%d,"goldAfter":%d,"x":%d,"y":%d,"inputs":%s}`,
364			strconv.Quote(p.Name), bots[s] != nil, strconv.Quote(p.Plan), strconv.Quote(p.Thought),
365			before[s], g.F[s].Gold, g.F[s].X, g.F[s].Y, strconv.Quote(string(chunk[s])))
366	}
367	r.Last = last + "]}"
368	chain.Emit("Round",
369		"room", strconv.Itoa(r.ID),
370		"round", strconv.Itoa(r.Round),
371		"tick", strconv.Itoa(g.T),
372		"inputsA", string(chunk[0]),
373		"inputsB", string(chunk[1]),
374		"thoughtA", r.P[0].Thought,
375		"thoughtB", r.P[1].Thought,
376		"goldA", strconv.Itoa(g.F[0].Gold),
377		"goldB", strconv.Itoa(g.F[1].Gold),
378	)
379	for s := 0; s < 2; s++ {
380		p := r.P[s]
381		p.Seal, p.Plan, p.Thought, p.Revealed = "", "", "", false
382	}
383	r.Round++
384	if g.Over() {
385		r.Phase = Done
386		r.Gold = [2]int{g.F[0].Gold, g.F[1].Gold}
387		r.Snap, r.BotSnap = "", [2]string{} // free the live state; the inputs replay it
388		chain.Emit("RoomDone", "room", strconv.Itoa(r.ID), "goldA", strconv.Itoa(g.F[0].Gold), "goldB", strconv.Itoa(g.F[1].Gold))
389		return
390	}
391	r.Snap = g.Snapshot()
392	r.Phase = Sealing
393	r.Deadline = height() + int64(r.PhaseBlocks)
394}