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.

reads.gno

7.12 Kb · 209 lines
  1package rooms
  2
  3import (
  4	"strconv"
  5	"strings"
  6
  7	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v2"
  8	"gno.land/p/nt/ufmt/v0"
  9)
 10
 11// MaxRoundTicks is the longest a round can be (5 minutes in 3 rounds).
 12const MaxRoundTicks = MaxSeconds * rules.TPS / MinRounds
 13
 14// Reads for agents and the browser. All are free (vm/qeval).
 15
 16// allowed lists what a player can do now: "seal", "reveal", "advance" (when
 17// a deadline has passed), or nothing while waiting for the other side.
 18func allowed(r *Room, p *Player) []string {
 19	out := []string{}
 20	if r.Spar && p == r.P[1] {
 21		return out // the sparring bot needs nothing
 22	}
 23	if r.Phase == Sealing || r.Phase == Revealing {
 24		if p.Seal == "" {
 25			out = append(out, "seal")
 26		} else if r.Phase == Revealing && !p.Revealed {
 27			out = append(out, "reveal")
 28		}
 29		if height() >= r.Deadline {
 30			out = append(out, "advance")
 31		}
 32	}
 33	return out
 34}
 35
 36func jsonList(items []string) string {
 37	q := make([]string, len(items))
 38	for i, s := range items {
 39		q[i] = strconv.Quote(s)
 40	}
 41	return "[" + strings.Join(q, ",") + "]"
 42}
 43
 44// StateJSON is everything a player needs to plan the next round: the clock,
 45// the deadline (blocksLeft, secondsLeft), what each player may do now
 46// (allowedActions), both fighters, and where the coins and power-ups are
 47// (square = y*15 + x; positions are in 1/1000 of a square).
 48func StateJSON(id int) string {
 49	r := mustRoom(id)
 50	left := int(r.Deadline - height())
 51	if left < 0 || r.Phase == Waiting || r.Phase == Done {
 52		left = 0
 53	}
 54	var b strings.Builder
 55	b.WriteString(ufmt.Sprintf(`{"id":%d,"phase":"%s","round":%d,"rounds":%d,"roundTicks":%d,"deadline":%d,"height":%d,"blocksLeft":%d,"secondsLeft":%d,"phaseBlocks":%d,"seed":%d`,
 56		r.ID, phaseNames[r.Phase], r.Round, r.Rounds, r.RoundTicks, int(r.Deadline), int(height()), left, left*BlockSeconds, r.PhaseBlocks, int(r.Seed)))
 57	if r.Phase == Waiting {
 58		b.WriteString(`,"players":[` + playerJSON(r, r.P[0], nil, 0) + "]}")
 59		return b.String()
 60	}
 61	if r.Phase == Done {
 62		b.WriteString(ufmt.Sprintf(`,"arena":"%s","tick":%d,"ticks":%d,"players":[%s,%s],"gold":[%d,%d]}`,
 63			rules.ArenaName(r.Seed), r.MatchTicks, r.MatchTicks, playerJSON(r, r.P[0], nil, 0), playerJSON(r, r.P[1], nil, 1), r.Gold[0], r.Gold[1]))
 64		return b.String()
 65	}
 66	g := rules.Restore(r.Snap)
 67	b.WriteString(ufmt.Sprintf(`,"arena":"%s","tick":%d,"ticks":%d,"players":[%s,%s],"coins":[`,
 68		rules.ArenaName(r.Seed), g.T, g.End, playerJSON(r, r.P[0], g, 0), playerJSON(r, r.P[1], g, 1)))
 69	first := true
 70	for c := 0; c < rules.Cells; c++ {
 71		if v := g.Coin[c]; v != 0 {
 72			if !first {
 73				b.WriteString(",")
 74			}
 75			first = false
 76			b.WriteString(ufmt.Sprintf(`[%d,%d]`, c, int(v)))
 77		}
 78	}
 79	b.WriteString(`],"power":[`)
 80	first = true
 81	for c := 0; c < rules.Cells; c++ {
 82		if v := g.Power[c]; v != 0 {
 83			if !first {
 84				b.WriteString(",")
 85			}
 86			first = false
 87			b.WriteString(ufmt.Sprintf(`[%d,%d]`, c, int(v)-1))
 88		}
 89	}
 90	b.WriteString("]}")
 91	return b.String()
 92}
 93
 94func playerJSON(r *Room, p *Player, g *rules.Game, s int) string {
 95	out := ufmt.Sprintf(`{"player":"%s","name":%s,"side":"%s","class":%d,"fallback":%d,"sealed":%t,"revealed":%t,"missed":%d,"allowedActions":%s`,
 96		p.Addr.String(), strconv.Quote(p.Name), string(rune('A'+s)), p.Class, p.Fallback, p.Seal != "", p.Revealed, p.Missed, jsonList(allowed(r, p)))
 97	if g != nil {
 98		f := g.F[s]
 99		t := g.T
100		left := func(v int) int {
101			if v > t {
102				return v - t
103			}
104			return 0
105		}
106		out += ufmt.Sprintf(`,"x":%d,"y":%d,"gold":%d,"shield":%t,"double":%t,"special":%d,"attack":%d,"block":%d,"dodge":%d,"stunned":%d`,
107			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))
108	}
109	return out + "}"
110}
111
112// LastResult says what happened in the last round played: each side's plan,
113// thought, gold before and after, where they ended, whether their bot played
114// it, and the inputs that were played.
115func LastResult(id int) string {
116	r := mustRoom(id)
117	if r.Last == "" {
118		return `{"round":-1}`
119	}
120	return r.Last
121}
122
123// InputsJSON gives both players' inputs and thoughts so far. The inputs
124// replay the match exactly with the brawl rules (NewLength with "ticks";
125// side B is not turned round: both played live).
126func InputsJSON(id int) string {
127	r := mustRoom(id)
128	if r.Phase == Waiting {
129		return `{"seed":0,"ticks":0,"a":"","b":""}`
130	}
131	th := func(p *Player) string {
132		if p.Thoughts == "" && r.Round == 0 {
133			return "[]"
134		}
135		return jsonList(strings.Split(p.Thoughts, "\n"))
136	}
137	return ufmt.Sprintf(`{"seed":%d,"ticks":%d,"roundTicks":%d,"classA":%d,"classB":%d,"nameA":%s,"nameB":%s,"a":%s,"b":%s,"thoughtsA":%s,"thoughtsB":%s}`,
138		int(r.Seed), r.MatchTicks, r.RoundTicks, r.P[0].Class, r.P[1].Class, strconv.Quote(r.P[0].Name), strconv.Quote(r.P[1].Name),
139		strconv.Quote(r.P[0].Inputs), strconv.Quote(r.P[1].Inputs), th(r.P[0]), th(r.P[1]))
140}
141
142// PlanPreview plays candidate plans for side (0 = A, 1 = B) over the next
143// round from the live state, against a model of the rival (their fallback
144// bot), and reports what would happen. Pass up to 8 plans separated by
145// "||" and compare them in one free read. It can't see the rival's real plan:
146// it's a forecast, not a promise.
147func PlanPreview(id, side int, plans string) string {
148	r := mustRoom(id)
149	if r.Phase != Sealing && r.Phase != Revealing {
150		panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ": nothing to preview")
151	}
152	if side != 0 && side != 1 {
153		panic("side: 0 for A, 1 for B")
154	}
155	list := strings.Split(plans, "||")
156	if len(list) > MaxPreviews {
157		panic("at most 8 plans per preview")
158	}
159	parts := []string{}
160	for _, plan := range list {
161		plan = strings.TrimSpace(plan)
162		parts = append(parts, previewOne(r, side, plan))
163	}
164	return "[" + strings.Join(parts, ",") + "]"
165}
166
167func previewOne(r *Room, side int, plan string) (out string) {
168	defer func() {
169		if e := recover(); e != nil {
170			out = ufmt.Sprintf(`{"plan":%s,"error":%s}`, strconv.Quote(plan), strconv.Quote(ufmt.Sprintf("%v", e)))
171		}
172	}()
173	checkPlan(plan, r.RoundTicks)
174	g := rules.Restore(r.Snap)
175	rival := rules.RestoreActor(r.BotSnap[1-side])
176	run := newRunner(plan)
177	before := [2]int{g.F[0].Gold, g.F[1].Gold}
178	ticks := 0
179	for i := 0; i < r.RoundTicks && !g.Over(); i++ {
180		mm, ma := run.next(g, side)
181		rm, ra := rival.Act(g, 1-side)
182		if side == 0 {
183			g.Step(mm, ma, rm, ra)
184		} else {
185			g.Step(rm, ra, mm, ma)
186		}
187		ticks++
188	}
189	me, o := g.F[side], g.F[1-side]
190	return ufmt.Sprintf(`{"plan":%s,"ticks":%d,"gold":%d,"rivalGold":%d,"gain":%d,"rivalGain":%d,"x":%d,"y":%d,"rivalX":%d,"rivalY":%d}`,
191		strconv.Quote(plan), ticks, me.Gold, o.Gold, me.Gold-before[side], o.Gold-before[1-side], me.X, me.Y, o.X, o.Y)
192}
193
194// Open lists rooms waiting for a second player, newest first, as JSON.
195func Open() string {
196	parts := []string{}
197	rooms.ReverseIterate("", "", func(k string, v any) bool {
198		r := v.(*Room)
199		if r.Phase == Waiting {
200			parts = append(parts, ufmt.Sprintf(`{"id":%d,"name":%s,"class":%d,"rounds":%d,"seconds":%d,"phaseBlocks":%d}`,
201				r.ID, strconv.Quote(r.P[0].Name), r.P[0].Class, r.Rounds, r.MatchTicks/rules.TPS, r.PhaseBlocks))
202		}
203		return len(parts) >= 20
204	})
205	return "[" + strings.Join(parts, ",") + "]"
206}
207
208// RoomCount is the number of rooms ever created.
209func RoomCount() int { return nextID - 1 }