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