package rooms import ( "strconv" "strings" rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v4" "gno.land/p/nt/ufmt/v0" ) // MaxRoundTicks is the longest a round can be (5 minutes in 3 rounds). const MaxRoundTicks = MaxSeconds * rules.TPS / MinRounds // Reads for agents and the browser. All are free (vm/qeval). // allowed lists what a player can do now: "seal", "reveal", "advance" (when // a deadline has passed), or nothing while waiting for the other side. func allowed(r *Room, p *Player) []string { out := []string{} if r.Spar && p == r.P[1] { return out // the sparring bot needs nothing } if r.Phase == Sealing || r.Phase == Revealing { if p.Seal == "" { out = append(out, "seal") } else if r.Phase == Revealing && !p.Revealed { out = append(out, "reveal") } if height() >= r.Deadline { out = append(out, "advance") } } return out } func jsonList(items []string) string { q := make([]string, len(items)) for i, s := range items { q[i] = strconv.Quote(s) } return "[" + strings.Join(q, ",") + "]" } // StateJSON is everything a player needs to plan the next round: the clock, // the deadline (blocksLeft, secondsLeft), what each player may do now // (allowedActions), both fighters, and where the coins and power-ups are // (square = y*15 + x; positions are in 1/1000 of a square). func StateJSON(id int) string { r := mustRoom(id) left := int(r.Deadline - height()) if left < 0 || r.Phase == Waiting || r.Phase == Done { left = 0 } var b strings.Builder 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`, r.ID, phaseNames[r.Phase], r.Round, r.Rounds, r.RoundTicks, int(r.Deadline), int(height()), left, left*BlockSeconds, r.PhaseBlocks, int(r.Seed))) if r.Phase == Waiting { b.WriteString(`,"players":[` + playerJSON(r, r.P[0], nil, 0) + "]}") return b.String() } if r.Phase == Done { b.WriteString(ufmt.Sprintf(`,"arena":"%s","tick":%d,"ticks":%d,"players":[%s,%s],"gold":[%d,%d]}`, 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])) return b.String() } g := rules.Restore(r.Snap) b.WriteString(ufmt.Sprintf(`,"arena":"%s","tick":%d,"ticks":%d,"players":[%s,%s],"coins":[`, rules.ArenaName(r.Seed), g.T, g.End, playerJSON(r, r.P[0], g, 0), playerJSON(r, r.P[1], g, 1))) first := true for c := 0; c < rules.Cells; c++ { if v := g.Coin[c]; v != 0 { if !first { b.WriteString(",") } first = false b.WriteString(ufmt.Sprintf(`[%d,%d]`, c, int(v))) } } b.WriteString(`],"power":[`) first = true for c := 0; c < rules.Cells; c++ { if v := g.Power[c]; v != 0 { if !first { b.WriteString(",") } first = false b.WriteString(ufmt.Sprintf(`[%d,%d]`, c, int(v)-1)) } } b.WriteString("]}") return b.String() } func playerJSON(r *Room, p *Player, g *rules.Game, s int) string { out := ufmt.Sprintf(`{"player":"%s","name":%s,"side":"%s","class":%d,"fallback":%d,"sealed":%t,"revealed":%t,"missed":%d,"allowedActions":%s`, 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))) if g != nil { f := g.F[s] t := g.T left := func(v int) int { if v > t { return v - t } return 0 } out += ufmt.Sprintf(`,"x":%d,"y":%d,"gold":%d,"shield":%t,"double":%t,"special":%d,"attack":%d,"block":%d,"dodge":%d,"stunned":%d`, 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)) } return out + "}" } // LastResult says what happened in the last round played: each side's plan, // thought, gold before and after, where they ended, whether their bot played // it, and the inputs that were played. func LastResult(id int) string { r := mustRoom(id) if r.Last == "" { return `{"round":-1}` } return r.Last } // InputsJSON gives both players' inputs and thoughts so far. The inputs // replay the match exactly with the brawl rules (NewLength with "ticks"; // side B is not turned round: both played live). func InputsJSON(id int) string { r := mustRoom(id) if r.Phase == Waiting { return `{"seed":0,"ticks":0,"a":"","b":""}` } th := func(p *Player) string { if p.Thoughts == "" && r.Round == 0 { return "[]" } return jsonList(strings.Split(p.Thoughts, "\n")) } 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}`, 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), strconv.Quote(r.P[0].Inputs), strconv.Quote(r.P[1].Inputs), th(r.P[0]), th(r.P[1])) } // PlanPreview plays candidate plans for side (0 = A, 1 = B) over the next // round from the live state and reports what would happen. Pass up to 8 // plans separated by "||" and compare them in one free read. The rival is // modelled by the plan they revealed last round, or by their fallback bot if // they have none yet (round 1, or their bot played). It can't see the // rival's real plan for this round: it's a forecast, not a promise. func PlanPreview(id, side int, plans string) string { return PlanPreviewVs(id, side, plans, "last") } // PlanPreviewVs is PlanPreview with the rival model chosen: "last" (their // last revealed plan, else their bot), "bot" (their fallback bot), or a // style profile played by a profile bot. LearnStyle's whole answer works // too: the profile is read out of it. func PlanPreviewVs(id, side int, plans, rival string) string { r := mustRoom(id) rival = profileArg(rival) if r.Phase != Sealing && r.Phase != Revealing { panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ": nothing to preview") } if side != 0 && side != 1 { panic("side: 0 for A, 1 for B") } if rival != "last" && rival != "bot" { if _, err := rules.ParseProfile(rival); err != nil { panic("rival: \"last\", \"bot\" or a style profile (" + err.Error() + ")") } } list := strings.Split(plans, "||") if len(list) > MaxPreviews { panic("at most 8 plans per preview") } parts := []string{} for _, plan := range list { plan = strings.TrimSpace(plan) parts = append(parts, previewOne(r, side, plan, rival)) } return "[" + strings.Join(parts, ",") + "]" } // profileArg takes the profile out of a LearnStyle answer; anything else is // returned as it is. func profileArg(s string) string { const k = `"profile":"` i := strings.Index(s, k) if i < 0 { return strings.TrimSpace(s) } rest := s[i+len(k):] if j := strings.Index(rest, `"`); j >= 0 { return rest[:j] } return s } // rivalModel says how a preview plays the rival, and how it was modelled. func rivalModel(r *Room, side int, rival string) (func(g *rules.Game, s int) (int, int), string) { if rival == "last" && r.P[1-side].LastPlan != "" { run := newRunner(r.P[1-side].LastPlan) return run.next, "last" } if rival != "last" && rival != "bot" { b := rules.NewProfileBot(rules.MustProfile(rival), r.Seed*7+uint32(r.Round)) return b.Act, "profile" } b := rules.RestoreActor(r.BotSnap[1-side]) return b.Act, "bot" } func previewOne(r *Room, side int, plan, rival string) (out string) { defer func() { if e := recover(); e != nil { out = ufmt.Sprintf(`{"plan":%s,"error":%s}`, strconv.Quote(plan), strconv.Quote(ufmt.Sprintf("%v", e))) } }() checkPlan(plan, r.RoundTicks) g := rules.Restore(r.Snap) act, model := rivalModel(r, side, rival) run := newRunner(plan) before := [2]int{g.F[0].Gold, g.F[1].Gold} ticks := 0 for i := 0; i < r.RoundTicks && !g.Over(); i++ { mm, ma := run.next(g, side) rm, ra := act(g, 1-side) if side == 0 { g.Step(mm, ma, rm, ra) } else { g.Step(rm, ra, mm, ma) } ticks++ } me, o := g.F[side], g.F[1-side] 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}`, 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) } // Open lists rooms waiting for a second player, newest first, as JSON. func Open() string { parts := []string{} rooms.ReverseIterate("", "", func(k string, v any) bool { r := v.(*Room) if r.Phase == Waiting { parts = append(parts, ufmt.Sprintf(`{"id":%d,"name":%s,"class":%d,"rounds":%d,"seconds":%d,"phaseBlocks":%d}`, r.ID, strconv.Quote(r.P[0].Name), r.P[0].Class, r.Rounds, r.MatchTicks/rules.TPS, r.PhaseBlocks)) } return len(parts) >= 20 }) return "[" + strings.Join(parts, ",") + "]" } // RoomCount is the number of rooms ever created. func RoomCount() int { return nextID - 1 }