rooms.gno
13.48 Kb · 421 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. The match is cut into rounds of
4// a few seconds. Each round, both players look at the live state, decide
5// their moves for the next round and send them 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 that round and saves the new
12// state. A player who misses the deadline is played by the fallback bot they
13// picked when joining, so nobody can stall a room. Thoughts and each round's
14// inputs go out as events, so anyone can watch the fight, reasoning included,
15// and replay it exactly.
16package rooms
17
18import (
19 "chain"
20 "chain/runtime"
21 "crypto/sha256"
22 "encoding/hex"
23 "strconv"
24 "strings"
25
26 rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl"
27 "gno.land/p/nt/avl/v0"
28 "gno.land/p/nt/ufmt/v0"
29 "gno.land/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/mybots"
30)
31
32const (
33 MinRoundTicks = 50 // 5 s
34 MaxRoundTicks = 150 // 15 s
35 MinSeconds = 60 // shortest room match
36 MaxSeconds = 300 // longest room match
37 // PhaseBlocks is how long each phase (seal, then reveal) waits for a
38 // slow player before anyone may move the room on.
39 PhaseBlocks = 30
40 MaxThought = 140
41 MaxName = 20
42)
43
44// Phases of a room.
45const (
46 Waiting = iota // created, waiting for a second player
47 Sealing // both players send a sealed plan
48 Revealing // both players reveal their plans
49 Done // the match is over
50)
51
52var phaseNames = [4]string{"waiting", "sealing", "revealing", "done"}
53
54// A Player is one side of a room.
55type Player struct {
56 Addr address
57 Name string
58 Class int
59 Fallback int // bot level that plays when this player misses a round
60 Seal string // fingerprint of the plan for this round
61 Plan string // revealed plan for this round
62 Thought string
63 Revealed bool
64 Missed int // rounds the fallback bot played
65 Inputs string // every input so far, one character per tick
66}
67
68// A Room is one live match.
69type Room struct {
70 ID int
71 Seed uint32
72 RoundTicks int
73 MatchTicks int
74 Round int
75 Phase int
76 Deadline int64 // block height when the current phase may be forced on
77 P [2]*Player
78 Snap string // the live match, packed (see brawl.Snapshot); "" until it starts
79 BotSnap [2]string // each fallback bot's memory
80 Gold [2]int // final score, once done
81 Created int64
82}
83
84var (
85 rooms avl.Tree // zero-padded id -> *Room
86 nextID = 1
87)
88
89func key(id int) string {
90 s := strconv.Itoa(id)
91 return strings.Repeat("0", 10-len(s)) + s
92}
93
94func mustRoom(id int) *Room {
95 v := rooms.Get(key(id))
96 if v == nil {
97 panic("no room #" + strconv.Itoa(id))
98 }
99 return v.(*Room)
100}
101
102func height() int64 { return runtime.ChainHeight() }
103
104func cleanText(s string, max int, what string) string {
105 s = strings.TrimSpace(s)
106 if len(s) > max {
107 panic(what + ": " + strconv.Itoa(max) + " characters at most")
108 }
109 for _, c := range s {
110 if c < ' ' || c == '|' || c == '<' || c == '>' || c == '"' || c == '\\' {
111 panic(what + ": plain text only")
112 }
113 }
114 return s
115}
116
117// MyBot as a fallback is the bot you saved in the mybots realm.
118const MyBot = 3
119
120func checkPlayer(class, fallback int, addr address) {
121 if class < rules.Hunter || class > rules.Reader {
122 panic("class: 0 hunter, 1 brawler, 2 coward, 3 trickster, 4 reader")
123 }
124 if fallback < rules.Easy || fallback > MyBot {
125 panic("fallback: 0 easy, 1 normal, 2 hard bot, 3 your saved bot")
126 }
127 if fallback == MyBot && mybots.Profile(addr.String()) == "" {
128 panic("fallback 3 needs a bot saved in mybots")
129 }
130}
131
132// fallbackBot packs a player's fallback bot as it starts the match. A saved
133// bot is copied in when the match starts; if it was removed since, the
134// Normal bot plays instead.
135func fallbackBot(p *Player, seed uint32) string {
136 if p.Fallback == MyBot {
137 if prof := mybots.Profile(p.Addr.String()); prof != "" {
138 return rules.NewProfileBot(rules.MustProfile(prof), seed).Snapshot()
139 }
140 return rules.NewBot(rules.Normal, seed).Snapshot()
141 }
142 return rules.NewBot(p.Fallback, seed).Snapshot()
143}
144
145// Create opens a room. roundTicks is the round length in ticks (10 a second,
146// 50 to 150, so 5 to 15 seconds; 100 is a good default). seconds is the whole
147// match (60 to 300; 180 is a good default). fallback is the bot (0 easy,
148// 1 normal, 2 hard, 3 the bot you saved in mybots) that plays for you in any
149// round you miss. Returns the
150// room id.
151func Create(cur realm, name string, class, fallback, roundTicks, seconds int) int {
152 checkPlayer(class, fallback, cur.Previous().Address())
153 if roundTicks < MinRoundTicks || roundTicks > MaxRoundTicks {
154 panic("roundTicks: 50 to 150 (5 to 15 seconds)")
155 }
156 if seconds < MinSeconds || seconds > MaxSeconds {
157 panic("seconds: 60 to 300")
158 }
159 r := &Room{ID: nextID, RoundTicks: roundTicks, MatchTicks: seconds * rules.TPS, Created: height()}
160 r.P[0] = &Player{Addr: cur.Previous().Address(), Name: cleanText(name, MaxName, "name"), Class: class, Fallback: fallback}
161 nextID++
162 rooms.Set(key(r.ID), r)
163 chain.Emit("RoomCreated", "room", strconv.Itoa(r.ID), "player", r.P[0].Addr.String())
164 return r.ID
165}
166
167// Join takes the second place in a waiting room and starts the match. The
168// arena and coins come from the block the match starts in.
169func Join(cur realm, id int, name string, class, fallback int) {
170 r := mustRoom(id)
171 if r.Phase != Waiting {
172 panic("room #" + strconv.Itoa(id) + " is already full")
173 }
174 addr := cur.Previous().Address()
175 checkPlayer(class, fallback, addr)
176 r.P[1] = &Player{Addr: addr, Name: cleanText(name, MaxName, "name"), Class: class, Fallback: fallback}
177 h := height()
178 r.Seed = uint32(h*7919+int64(id)*104729) % (1 << 31)
179 r.Snap = rules.NewLength(r.Seed, r.P[0].Class, class, r.MatchTicks).Snapshot()
180 r.BotSnap[0] = fallbackBot(r.P[0], r.Seed+1)
181 r.BotSnap[1] = fallbackBot(r.P[1], r.Seed+2)
182 r.Phase = Sealing
183 r.Deadline = h + PhaseBlocks
184 chain.Emit("RoomStarted", "room", strconv.Itoa(id), "seed", strconv.Itoa(int(r.Seed)), "arena", rules.ArenaName(r.Seed))
185}
186
187func side(r *Room, addr address) int {
188 for s := 0; s < 2; s++ {
189 if r.P[s] != nil && r.P[s].Addr == addr {
190 return s
191 }
192 }
193 panic("you are not playing in room #" + strconv.Itoa(r.ID))
194}
195
196// PlanHash is the fingerprint to seal: hex sha256 of plan + "|" + salt. Read
197// it for free (vm/qeval) before sealing, or compute it yourself.
198func PlanHash(plan, salt string) string {
199 sum := sha256.Sum256([]byte(plan + "|" + salt))
200 return hex.EncodeToString(sum[:])
201}
202
203// Seal sends the fingerprint of your plan for this round.
204func Seal(cur realm, id int, hash string) {
205 r := mustRoom(id)
206 if r.Phase != Sealing {
207 panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ", not sealing")
208 }
209 if len(hash) != 64 {
210 panic("hash: 64 hex characters (see PlanHash)")
211 }
212 p := r.P[side(r, cur.Previous().Address())]
213 if p.Seal != "" {
214 panic("you already sealed this round")
215 }
216 p.Seal = hash
217 if r.P[0].Seal != "" && r.P[1].Seal != "" {
218 r.Phase = Revealing
219 r.Deadline = height() + PhaseBlocks
220 }
221}
222
223// Reveal sends your plan for this round: one input character per tick (see
224// the brawl package; shorter means standing still for the rest), the salt
225// you sealed it with, and a thought of up to 140 characters that everyone
226// watching will see.
227func Reveal(cur realm, id int, plan, salt, thought string) {
228 r := mustRoom(id)
229 if r.Phase != Revealing {
230 panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ", not revealing")
231 }
232 p := r.P[side(r, cur.Previous().Address())]
233 if p.Revealed {
234 panic("you already revealed this round")
235 }
236 if len(plan) > r.RoundTicks || !rules.Valid(plan) {
237 panic("plan: at most " + strconv.Itoa(r.RoundTicks) + " input characters")
238 }
239 if PlanHash(plan, salt) != p.Seal {
240 panic("this plan and salt don't match your seal")
241 }
242 p.Plan = plan
243 p.Thought = cleanText(thought, MaxThought, "thought")
244 p.Revealed = true
245 if r.P[0].Revealed && r.P[1].Revealed {
246 play(r)
247 }
248}
249
250// Advance moves a room on once its phase deadline has passed: whoever hasn't
251// sealed or revealed is played by their fallback bot this round. Anyone may
252// call it.
253func Advance(cur realm, id int) {
254 r := mustRoom(id)
255 if r.Phase != Sealing && r.Phase != Revealing {
256 panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase])
257 }
258 if height() < r.Deadline {
259 panic("too early: the deadline is block " + strconv.Itoa(int(r.Deadline)))
260 }
261 if r.Phase == Sealing && (r.P[0].Seal != "" || r.P[1].Seal != "") {
262 // whoever sealed still gets to reveal; the other side is the bot's
263 r.Phase = Revealing
264 r.Deadline = height() + PhaseBlocks
265 return
266 }
267 play(r)
268}
269
270// play runs one round. A player without a revealed plan is played by their bot.
271func play(r *Room) {
272 g := rules.Restore(r.Snap)
273 var bots [2]rules.Actor
274 var chunk [2][]byte
275 for s := 0; s < 2; s++ {
276 if !r.P[s].Revealed {
277 r.P[s].Missed++
278 }
279 }
280 for i := 0; i < r.RoundTicks && !g.Over(); i++ {
281 var m, a [2]int
282 for s := 0; s < 2; s++ {
283 p := r.P[s]
284 if !p.Revealed {
285 if bots[s] == nil {
286 bots[s] = rules.RestoreActor(r.BotSnap[s])
287 }
288 m[s], a[s] = bots[s].Act(g, s)
289 } else if i < len(p.Plan) {
290 m[s], a[s], _ = rules.Decode(p.Plan[i])
291 } else {
292 m[s], a[s] = rules.Still, rules.None
293 }
294 chunk[s] = append(chunk[s], rules.Encode(m[s], a[s]))
295 }
296 g.Step(m[0], a[0], m[1], a[1])
297 }
298 for s := 0; s < 2; s++ {
299 r.P[s].Inputs += string(chunk[s])
300 if bots[s] != nil {
301 r.BotSnap[s] = bots[s].Snapshot()
302 }
303 }
304 chain.Emit("Round",
305 "room", strconv.Itoa(r.ID),
306 "round", strconv.Itoa(r.Round),
307 "tick", strconv.Itoa(g.T),
308 "inputsA", string(chunk[0]),
309 "inputsB", string(chunk[1]),
310 "thoughtA", r.P[0].Thought,
311 "thoughtB", r.P[1].Thought,
312 "goldA", strconv.Itoa(g.F[0].Gold),
313 "goldB", strconv.Itoa(g.F[1].Gold),
314 )
315 for s := 0; s < 2; s++ {
316 p := r.P[s]
317 p.Seal, p.Plan, p.Thought, p.Revealed = "", "", "", false
318 }
319 r.Round++
320 if g.Over() {
321 r.Phase = Done
322 r.Gold = [2]int{g.F[0].Gold, g.F[1].Gold}
323 r.Snap, r.BotSnap = "", [2]string{} // free the live state; the inputs replay it
324 chain.Emit("RoomDone", "room", strconv.Itoa(r.ID), "goldA", strconv.Itoa(g.F[0].Gold), "goldB", strconv.Itoa(g.F[1].Gold))
325 return
326 }
327 r.Snap = g.Snapshot()
328 r.Phase = Sealing
329 r.Deadline = height() + PhaseBlocks
330}
331
332// Reads for agents and the browser.
333
334// StateJSON is everything a player needs to plan the next round: the clock,
335// both fighters, and where the coins and power-ups are (square = y*15 + x).
336func StateJSON(id int) string {
337 r := mustRoom(id)
338 var b strings.Builder
339 b.WriteString(ufmt.Sprintf(`{"id":%d,"phase":"%s","round":%d,"roundTicks":%d,"deadline":%d,"height":%d,"seed":%d`,
340 r.ID, phaseNames[r.Phase], r.Round, r.RoundTicks, int(r.Deadline), int(height()), int(r.Seed)))
341 if r.Phase == Waiting {
342 b.WriteString(`,"players":[` + playerJSON(r.P[0], nil, 0) + "]}")
343 return b.String()
344 }
345 if r.Phase == Done {
346 b.WriteString(ufmt.Sprintf(`,"arena":"%s","tick":%d,"ticks":%d,"players":[%s,%s],"gold":[%d,%d]}`,
347 rules.ArenaName(r.Seed), r.MatchTicks, r.MatchTicks, playerJSON(r.P[0], nil, 0), playerJSON(r.P[1], nil, 1), r.Gold[0], r.Gold[1]))
348 return b.String()
349 }
350 g := rules.Restore(r.Snap)
351 b.WriteString(ufmt.Sprintf(`,"arena":"%s","tick":%d,"ticks":%d,"players":[%s,%s],"coins":[`,
352 rules.ArenaName(r.Seed), g.T, g.End, playerJSON(r.P[0], g, 0), playerJSON(r.P[1], g, 1)))
353 first := true
354 for c := 0; c < rules.Cells; c++ {
355 if v := g.Coin[c]; v != 0 {
356 if !first {
357 b.WriteString(",")
358 }
359 first = false
360 b.WriteString(ufmt.Sprintf(`[%d,%d]`, c, int(v)))
361 }
362 }
363 b.WriteString(`],"power":[`)
364 first = true
365 for c := 0; c < rules.Cells; c++ {
366 if v := g.Power[c]; v != 0 {
367 if !first {
368 b.WriteString(",")
369 }
370 first = false
371 b.WriteString(ufmt.Sprintf(`[%d,%d]`, c, int(v)-1))
372 }
373 }
374 b.WriteString("]}")
375 return b.String()
376}
377
378func playerJSON(p *Player, g *rules.Game, s int) string {
379 out := ufmt.Sprintf(`{"player":"%s","name":%s,"class":%d,"fallback":%d,"sealed":%t,"revealed":%t,"missed":%d`,
380 p.Addr.String(), strconv.Quote(p.Name), p.Class, p.Fallback, p.Seal != "", p.Revealed, p.Missed)
381 if g != nil {
382 f := g.F[s]
383 t := g.T
384 left := func(v int) int {
385 if v > t {
386 return v - t
387 }
388 return 0
389 }
390 out += ufmt.Sprintf(`,"x":%d,"y":%d,"gold":%d,"shield":%t,"double":%t,"special":%d,"attack":%d,"block":%d,"dodge":%d,"stunned":%d`,
391 f.X, f.Y, f.Gold, f.Shield, f.Double, left(f.CD), left(f.AtkCD), left(f.BlockCD), left(f.DodgeCD), left(f.StunT))
392 }
393 return out + "}"
394}
395
396// InputsJSON gives both players' inputs so far, to replay the match exactly
397// with the brawl rules (side B is not turned round: both played live).
398func InputsJSON(id int) string {
399 r := mustRoom(id)
400 if r.Phase == Waiting {
401 return `{"seed":0,"ticks":0,"a":"","b":""}`
402 }
403 return ufmt.Sprintf(`{"seed":%d,"ticks":%d,"classA":%d,"classB":%d,"a":%s,"b":%s}`,
404 int(r.Seed), r.MatchTicks, r.P[0].Class, r.P[1].Class, strconv.Quote(r.P[0].Inputs), strconv.Quote(r.P[1].Inputs))
405}
406
407// Open lists rooms waiting for a second player, newest first, as JSON.
408func Open() string {
409 parts := []string{}
410 rooms.ReverseIterate("", "", func(k string, v any) bool {
411 r := v.(*Room)
412 if r.Phase == Waiting {
413 parts = append(parts, ufmt.Sprintf(`{"id":%d,"name":%s,"class":%d,"roundTicks":%d,"seconds":%d}`, r.ID, strconv.Quote(r.P[0].Name), r.P[0].Class, r.RoundTicks, r.MatchTicks/rules.TPS))
414 }
415 return len(parts) >= 20
416 })
417 return "[" + strings.Join(parts, ",") + "]"
418}
419
420// RoomCount is the number of rooms ever created.
421func RoomCount() int { return nextID - 1 }