api.gno
7.54 Kb · 232 lines
1package arena
2
3import (
4 "strconv"
5 "strings"
6
7 "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
8 "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/game"
9)
10
11// Read API for apps and tools. Every function returns JSON and changes
12// nothing, so it can be called for free with a vm/qeval query, e.g.
13//
14// gnokey query vm/qeval -data 'gno.land/r/<ns>/arena.BotsJSON()'
15
16func jsonString(s string) string {
17 var sb strings.Builder
18 sb.WriteByte('"')
19 for _, c := range s {
20 switch {
21 case c == '"':
22 sb.WriteString(`\"`)
23 case c == '\\':
24 sb.WriteString(`\\`)
25 case c < 0x20:
26 sb.WriteString(`\u00`)
27 sb.WriteByte("0123456789abcdef"[c>>4])
28 sb.WriteByte("0123456789abcdef"[c&0xf])
29 default:
30 sb.WriteRune(c)
31 }
32 }
33 sb.WriteByte('"')
34 return sb.String()
35}
36
37type jsonObj struct{ parts []string }
38
39func (o *jsonObj) str(k, v string) *jsonObj {
40 o.parts = append(o.parts, jsonString(k)+":"+jsonString(v))
41 return o
42}
43func (o *jsonObj) num(k string, v int) *jsonObj {
44 o.parts = append(o.parts, jsonString(k)+":"+strconv.Itoa(v))
45 return o
46}
47func (o *jsonObj) num64(k string, v int64) *jsonObj {
48 o.parts = append(o.parts, jsonString(k)+":"+strconv.FormatInt(v, 10))
49 return o
50}
51func (o *jsonObj) flag(k string, v bool) *jsonObj {
52 o.parts = append(o.parts, jsonString(k)+":"+strconv.FormatBool(v))
53 return o
54}
55func (o *jsonObj) raw(k, v string) *jsonObj {
56 o.parts = append(o.parts, jsonString(k)+":"+v)
57 return o
58}
59func (o *jsonObj) String() string { return "{" + strings.Join(o.parts, ",") + "}" }
60
61func jsonArray(items []string) string { return "[" + strings.Join(items, ",") + "]" }
62
63func posJSON(p bot.Pos) string { return "[" + strconv.Itoa(p.X) + "," + strconv.Itoa(p.Y) + "]" }
64
65func botJSON(b *Bot) string {
66 o := &jsonObj{}
67 o.str("name", b.Name).str("realm", b.Realm).str("owner", b.Owner.String()).
68 str("kind", b.kind()).str("description", b.Description).
69 num("version", b.Version).flag("retired", b.Retired).
70 num("rating", b.Rating).
71 num("seasonWins", b.SeasonWins).num("seasonLosses", b.SeasonLosses).num("seasonDraws", b.SeasonDraws).
72 num("wins", b.Wins).num("losses", b.Losses).num("draws", b.Draws).num("forfeits", b.Forfeits).
73 num64("registered", b.Registered)
74 return o.String()
75}
76
77// ArenaJSON returns counts, the current season and the block height.
78func ArenaJSON() string {
79 n, end := SeasonInfo()
80 o := &jsonObj{}
81 o.num("bots", bots.Size()).num("matches", lastID).num("tournaments", lastTID).
82 num("season", n).num64("seasonStart", seasonStart).num64("seasonEnds", end).
83 num64("height", height()).num("seasonLength", SeasonLength).
84 num("moveTimeout", MoveTimeout).num("ratedCooldown", RatedCooldown).
85 num("boardSize", bot.Size).num("turns", bot.Turns)
86 return o.String()
87}
88
89// BotsJSON returns every bot, ranked like the leaderboard.
90func BotsJSON() string {
91 var items []string
92 for _, b := range leaderboard() {
93 items = append(items, botJSON(b))
94 }
95 return jsonArray(items)
96}
97
98// BotJSON returns one bot, with its earlier versions.
99func BotJSON(name string) string {
100 b := mustBot(name)
101 var prev []string
102 for _, r := range b.PreviousVersions() {
103 prev = append(prev, jsonString(r))
104 }
105 return strings.TrimSuffix(botJSON(b), "}") + `,"previousVersions":` + jsonArray(prev) + "}"
106}
107
108func matchSummaryJSON(m *Match) string {
109 o := &jsonObj{}
110 o.num("id", m.ID).str("a", m.BotA).str("b", m.BotB).
111 str("status", m.Status.String()).num("turn", m.Game.Turn).
112 num("goldA", m.Game.GoldA).num("goldB", m.Game.GoldB).
113 num("winner", m.Winner).flag("forfeit", m.Forfeit).str("reason", m.Reason).
114 flag("rated", m.Rated).num("delta", m.Delta).
115 num("season", m.Season).num("tournament", m.Tournament).
116 num64("created", m.Created).num64("settled", m.Settled).
117 str("summary", m.Summary())
118 if m.Status == Stepping {
119 o.str("waitingFor", m.Bot(m.Waiting)).num64("deadline", m.Deadline)
120 }
121 return o.String()
122}
123
124// MatchesJSON returns up to limit matches, newest first, optionally only
125// those of one bot (looking at no more than the last 500).
126func MatchesJSON(botName string, limit int) string {
127 if limit <= 0 || limit > 100 {
128 limit = 20
129 }
130 var items []string
131 eachRecent(500, func(m *Match) bool {
132 if botName != "" && m.BotA != botName && m.BotB != botName {
133 return false
134 }
135 items = append(items, matchSummaryJSON(m))
136 return len(items) >= limit
137 })
138 return jsonArray(items)
139}
140
141// MatchJSON returns a match with every turn, for replays: positions, gold
142// and coins after each turn, both actions and what happened.
143func MatchJSON(id int) string {
144 m := mustMatch(id)
145 r := game.New(m.Game.Seed)
146 frames := []string{frameJSON(r, [2]bot.Action{}, game.Events{})}
147 g := &m.Game
148 for i := 0; i < g.Turn; i++ {
149 acts := [2]bot.Action{bot.Action(g.Moves[2*i]), bot.Action(g.Moves[2*i+1])}
150 ev := r.Step(acts[0], acts[1])
151 frames = append(frames, frameJSON(r, acts, ev))
152 }
153 return strings.TrimSuffix(matchSummaryJSON(m), "}") + `,"seed":` + strconv.Itoa(g.Seed) + `,"frames":` + jsonArray(frames) + "}"
154}
155
156func frameJSON(g *game.Game, acts [2]bot.Action, ev game.Events) string {
157 var coins []string
158 for _, c := range g.CoinList() {
159 coins = append(coins, posJSON(c))
160 }
161 o := &jsonObj{}
162 o.num("turn", g.Turn).
163 raw("pos", "["+posJSON(g.Pos(0))+","+posJSON(g.Pos(1))+"]").
164 raw("gold", "["+strconv.Itoa(g.GoldA)+","+strconv.Itoa(g.GoldB)+"]").
165 raw("actions", "["+jsonString(acts[0].String())+","+jsonString(acts[1].String())+"]").
166 raw("stole", "["+strconv.FormatBool(ev.Stole[0])+","+strconv.FormatBool(ev.Stole[1])+"]").
167 raw("parried", "["+strconv.FormatBool(ev.Parried[0])+","+strconv.FormatBool(ev.Parried[1])+"]").
168 num("spawned", ev.Spawned).
169 raw("coins", jsonArray(coins))
170 return o.String()
171}
172
173func tournamentJSON(t *Tournament, full bool) string {
174 o := &jsonObj{}
175 var entrants []string
176 for _, e := range t.Entrants {
177 entrants = append(entrants, jsonString(e))
178 }
179 o.num("id", t.ID).str("name", t.Name).str("creator", t.Creator.String()).
180 num64("created", t.Created).num("capacity", t.Capacity).
181 str("status", t.Status.String()).str("winner", t.Winner).
182 raw("entrants", jsonArray(entrants))
183 if !full {
184 return o.String()
185 }
186 var table []string
187 for _, r := range t.Standings() {
188 row := &jsonObj{}
189 row.str("bot", r.Bot).num("played", r.Played).num("wins", r.Wins).num("draws", r.Draws).
190 num("losses", r.Losses).num("goldFor", r.GoldFor).num("goldAgainst", r.GoldAgainst).num("points", r.Points)
191 table = append(table, row.String())
192 }
193 var sched []string
194 for i, p := range t.Pairs {
195 ab := strings.Split(p, "|")
196 row := &jsonObj{}
197 row.str("a", ab[0]).str("b", ab[1]).num("match", t.MatchIDs[i])
198 sched = append(sched, row.String())
199 }
200 o.raw("table", jsonArray(table)).raw("schedule", jsonArray(sched))
201 return o.String()
202}
203
204// TournamentsJSON returns every tournament, newest first.
205func TournamentsJSON() string {
206 var items []string
207 tournaments.ReverseIterate("", "", func(_ string, v any) bool {
208 items = append(items, tournamentJSON(v.(*Tournament), false))
209 return false
210 })
211 return jsonArray(items)
212}
213
214// TournamentJSON returns one tournament with its table and schedule.
215func TournamentJSON(id int) string { return tournamentJSON(mustTournament(id), true) }
216
217// SeasonsJSON returns the top 10 of every finished season, newest first.
218func SeasonsJSON() string {
219 var items []string
220 for n := season - 1; n >= 1; n-- {
221 var rows []string
222 for _, s := range PastSeason(n) {
223 row := &jsonObj{}
224 row.str("bot", s.Bot).num("rating", s.Rating).num("wins", s.Wins).num("losses", s.Losses).num("draws", s.Draws)
225 rows = append(rows, row.String())
226 }
227 o := &jsonObj{}
228 o.num("season", n).raw("top", jsonArray(rows))
229 items = append(items, o.String())
230 }
231 return jsonArray(items)
232}