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

8.64 Kb · 253 lines
  1package rooms
  2
  3import (
  4	"strconv"
  5	"strings"
  6
  7	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v3"
  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 and reports what would happen. Pass up to 8
144// plans separated by "||" and compare them in one free read. The rival is
145// modelled by the plan they revealed last round, or by their fallback bot if
146// they have none yet (round 1, or their bot played). It can't see the
147// rival's real plan for this round: it's a forecast, not a promise.
148func PlanPreview(id, side int, plans string) string {
149	return PlanPreviewVs(id, side, plans, "last")
150}
151
152// PlanPreviewVs is PlanPreview with the rival model chosen: "last" (their
153// last revealed plan, else their bot), "bot" (their fallback bot), or a
154// style profile played by a profile bot. LearnStyle's whole answer works
155// too: the profile is read out of it.
156func PlanPreviewVs(id, side int, plans, rival string) string {
157	r := mustRoom(id)
158	rival = profileArg(rival)
159	if r.Phase != Sealing && r.Phase != Revealing {
160		panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ": nothing to preview")
161	}
162	if side != 0 && side != 1 {
163		panic("side: 0 for A, 1 for B")
164	}
165	if rival != "last" && rival != "bot" {
166		if _, err := rules.ParseProfile(rival); err != nil {
167			panic("rival: \"last\", \"bot\" or a style profile (" + err.Error() + ")")
168		}
169	}
170	list := strings.Split(plans, "||")
171	if len(list) > MaxPreviews {
172		panic("at most 8 plans per preview")
173	}
174	parts := []string{}
175	for _, plan := range list {
176		plan = strings.TrimSpace(plan)
177		parts = append(parts, previewOne(r, side, plan, rival))
178	}
179	return "[" + strings.Join(parts, ",") + "]"
180}
181
182// profileArg takes the profile out of a LearnStyle answer; anything else is
183// returned as it is.
184func profileArg(s string) string {
185	const k = `"profile":"`
186	i := strings.Index(s, k)
187	if i < 0 {
188		return strings.TrimSpace(s)
189	}
190	rest := s[i+len(k):]
191	if j := strings.Index(rest, `"`); j >= 0 {
192		return rest[:j]
193	}
194	return s
195}
196
197// rivalModel says how a preview plays the rival, and how it was modelled.
198func rivalModel(r *Room, side int, rival string) (func(g *rules.Game, s int) (int, int), string) {
199	if rival == "last" && r.P[1-side].LastPlan != "" {
200		run := newRunner(r.P[1-side].LastPlan)
201		return run.next, "last"
202	}
203	if rival != "last" && rival != "bot" {
204		b := rules.NewProfileBot(rules.MustProfile(rival), r.Seed*7+uint32(r.Round))
205		return b.Act, "profile"
206	}
207	b := rules.RestoreActor(r.BotSnap[1-side])
208	return b.Act, "bot"
209}
210
211func previewOne(r *Room, side int, plan, rival string) (out string) {
212	defer func() {
213		if e := recover(); e != nil {
214			out = ufmt.Sprintf(`{"plan":%s,"error":%s}`, strconv.Quote(plan), strconv.Quote(ufmt.Sprintf("%v", e)))
215		}
216	}()
217	checkPlan(plan, r.RoundTicks)
218	g := rules.Restore(r.Snap)
219	act, model := rivalModel(r, side, rival)
220	run := newRunner(plan)
221	before := [2]int{g.F[0].Gold, g.F[1].Gold}
222	ticks := 0
223	for i := 0; i < r.RoundTicks && !g.Over(); i++ {
224		mm, ma := run.next(g, side)
225		rm, ra := act(g, 1-side)
226		if side == 0 {
227			g.Step(mm, ma, rm, ra)
228		} else {
229			g.Step(rm, ra, mm, ma)
230		}
231		ticks++
232	}
233	me, o := g.F[side], g.F[1-side]
234	return ufmt.Sprintf(`{"plan":%s,"rival":%s,"ticks":%d,"gold":%d,"rivalGold":%d,"gain":%d,"rivalGain":%d,"x":%d,"y":%d,"rivalX":%d,"rivalY":%d}`,
235		strconv.Quote(plan), strconv.Quote(model), ticks, me.Gold, o.Gold, me.Gold-before[side], o.Gold-before[1-side], me.X, me.Y, o.X, o.Y)
236}
237
238// Open lists rooms waiting for a second player, newest first, as JSON.
239func Open() string {
240	parts := []string{}
241	rooms.ReverseIterate("", "", func(k string, v any) bool {
242		r := v.(*Room)
243		if r.Phase == Waiting {
244			parts = append(parts, ufmt.Sprintf(`{"id":%d,"name":%s,"class":%d,"rounds":%d,"seconds":%d,"phaseBlocks":%d}`,
245				r.ID, strconv.Quote(r.P[0].Name), r.P[0].Class, r.Rounds, r.MatchTicks/rules.TPS, r.PhaseBlocks))
246		}
247		return len(parts) >= 20
248	})
249	return "[" + strings.Join(parts, ",") + "]"
250}
251
252// RoomCount is the number of rooms ever created.
253func RoomCount() int { return nextID - 1 }