render.gno
13.11 Kb · 362 lines
1package arena
2
3import (
4 "strconv"
5 "strings"
6
7 "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
8 "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/game"
9 "gno.land/p/moul/txlink/v0"
10 "gno.land/p/nt/ufmt/v0"
11)
12
13var (
14 self string // this realm's path as gnoweb links it, e.g. "/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/arena/v2"
15 tx txlink.Realm // builds transaction links to this realm
16)
17
18func init(cur realm) {
19 full := cur.PkgPath()
20 tx = txlink.Realm(full)
21 self = full
22 if i := strings.Index(full, "/"); i >= 0 {
23 self = full[i:] // drop the chain domain
24 }
25}
26
27// Render draws the arena pages in gnoweb:
28//
29// "" leaderboard, recent matches, rules
30// "bot/<name>" a bot's record, source link and a challenge button
31// "match/<id>" the final board, key moments and actions
32// "match/<id>/<turn>" the board after one turn
33// "tournaments" all tournaments
34// "tournament/<id>" a tournament's table, schedule and actions
35// "seasons" champions of past seasons
36func Render(path string) string {
37 parts := strings.Split(strings.Trim(path, "/"), "/")
38 switch {
39 case len(parts) == 1 && parts[0] == "tournaments":
40 return renderTournaments()
41 case len(parts) == 1 && parts[0] == "seasons":
42 return renderSeasons()
43 case len(parts) == 2 && parts[0] == "tournament":
44 id, err := strconv.Atoi(parts[1])
45 if err != nil || tournaments.Get(key(id)) == nil {
46 return "# Tournament not found\n\n[Back to the arena](" + link("") + ")\n"
47 }
48 return renderTournament(mustTournament(id))
49 case len(parts) == 2 && parts[0] == "bot":
50 return renderBot(parts[1])
51 case (len(parts) == 2 || len(parts) == 3) && parts[0] == "match":
52 id, err := strconv.Atoi(parts[1])
53 if _, ok := record(id); err != nil || !ok {
54 return "# Match not found\n\n[Back to the arena](" + link("") + ")\n"
55 }
56 turn := -1
57 if len(parts) == 3 {
58 if t, err := strconv.Atoi(parts[2]); err == nil {
59 turn = t
60 }
61 }
62 return renderMatch(mustMatch(id), turn)
63 }
64 return renderHome()
65}
66
67func link(p string) string {
68 if p == "" {
69 return self
70 }
71 return self + ":" + p
72}
73
74func matchLink(id int) string { return link("match/" + strconv.Itoa(id)) }
75
76// fightLink opens a pre-filled Fight transaction; either name may be empty
77// for the player to fill in.
78func fightLink(a, b string) string { return tx.Call("Fight", "a", a, "b", b) }
79
80func renderHome() string {
81 var sb strings.Builder
82 sb.WriteString("# Code Arena\n\n")
83 sb.WriteString("Bots are realms. Deploy one, register it, and the chain referees every match by calling each bot's code turn by turn. Every bot's source is public, so you can study a rival before you challenge it.\n\n")
84 sb.WriteString(ufmt.Sprintf("**%d bots** · **%d matches** · **%d tournaments** · [Start a fight](%s)\n\n", bots.Size(), lastID, lastTID, fightLink("", "")))
85
86 sb.WriteString(ufmt.Sprintf("## Season %d leaderboard\n\n", season))
87 sb.WriteString(seasonLine() + "\n\n")
88 ranked := activeLeaderboard()
89 if len(ranked) == 0 {
90 sb.WriteString("No bots yet.\n\n")
91 } else {
92 sb.WriteString("| # | Bot | Elo | Season W-L-D | |\n|---|---|---|---|---|\n")
93 for i, b := range ranked {
94 if i == 20 {
95 break
96 }
97 sb.WriteString(ufmt.Sprintf("| %d | [%s](%s) | %d | %d-%d-%d | [code](%s) · [fight](%s) |\n",
98 i+1, b.Name, link("bot/"+b.Name), b.Rating, b.SeasonWins, b.SeasonLosses, b.SeasonDraws, sourceLink(b.Realm), fightLink("", b.Name)))
99 }
100 sb.WriteString("\n")
101 }
102
103 sb.WriteString("## Tournaments\n\n")
104 writeTournamentList(&sb, 5)
105 sb.WriteString(ufmt.Sprintf("[Open a tournament](%s) · [All tournaments](%s)\n\n", tx.Call("CreateTournament", "name", "", "capacity", "8"), link("tournaments")))
106
107 sb.WriteString("## Recent matches\n\n")
108 writeRecent(&sb, "", 10)
109
110 sb.WriteString("## Rules\n\n")
111 sb.WriteString("- 9×9 board, 50 turns. Bots start in opposite corners; coins are placed point-symmetrically, so neither corner has an advantage. A new pair of coins appears every 5 turns.\n")
112 sb.WriteString("- Each turn both bots choose at once: `Up`, `Down`, `Left`, `Right`, `Stay`, `Attack` or `Defend`.\n")
113 sb.WriteString("- Step on a coin to take it. Bots never share a square: if both step onto the same one, priority alternates each turn.\n")
114 sb.WriteString("- Next to the enemy, `Attack` steals one coin. But attacking into a `Defend` is parried, and the defender takes a coin from you instead.\n")
115 sb.WriteString("- Most gold after 50 turns wins. Ratings are Elo-style; a pair of bots plays at most one rated match every ")
116 sb.WriteString(strconv.Itoa(RatedCooldown) + " blocks, and rematches in between are friendlies.\n\n")
117 sb.WriteString("Each turn a bot sees the board, both scores, and what both bots did last turn, so a bot can learn its opponent's habits.\n\n")
118
119 sb.WriteString("## Build a bot\n\n")
120 sb.WriteString("1. Import [`gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot`](/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot) and write a `Move(bot.State) bot.Action` method (a realm bot can keep memory) or a plain function.\n")
121 sb.WriteString("2. Register it from your realm's `init`: `arena.RegisterBot(cross(cur), \"my-bot\", &myBot{})`.\n")
122 sb.WriteString(ufmt.Sprintf("3. [Fight](%s) anyone on the leaderboard.\n\n", fightLink("my-bot", "")))
123 sb.WriteString("Starter bots to read and beat: [strategies](/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/strategies) · [reader](/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bots/reader/v2), a realm bot that learns each opponent's habits.\n\n")
124
125 sb.WriteString("## No escaping a loss\n\n")
126 sb.WriteString("A crash inside a realm cancels the whole transaction, so a bot could crash on purpose to cancel a match it is losing. It doesn't work here: the match switches to step mode, one move per transaction, and a bot that can't make its move by the deadline loses by forfeit.\n")
127 return sb.String()
128}
129
130func (b *Bot) kind() string {
131 if b.fn != nil {
132 return "function"
133 }
134 return "realm"
135}
136
137func leaderboard() []*Bot {
138 var out []*Bot
139 bots.Iterate("", "", func(_ string, v any) bool {
140 out = append(out, v.(*Bot))
141 return false
142 })
143 // insertion sort: highest rating first, then most wins, then name
144 for i := 1; i < len(out); i++ {
145 for j := i; j > 0 && better(out[j], out[j-1]); j-- {
146 out[j], out[j-1] = out[j-1], out[j]
147 }
148 }
149 return out
150}
151
152func better(a, b *Bot) bool {
153 if a.Rating != b.Rating {
154 return a.Rating > b.Rating
155 }
156 if a.Wins != b.Wins {
157 return a.Wins > b.Wins
158 }
159 return a.Name < b.Name
160}
161
162func sourceLink(realmPath string) string {
163 if i := strings.Index(realmPath, "/"); i >= 0 {
164 realmPath = realmPath[i:]
165 }
166 return realmPath + "$source"
167}
168
169// writeRecent lists the latest matches, optionally only those of one bot
170// among the last 500.
171func writeRecent(sb *strings.Builder, botName string, limit int) {
172 n := 0
173 eachRecent(500, func(m *Match) bool {
174 if botName != "" && m.BotA != botName && m.BotB != botName {
175 return false
176 }
177 sb.WriteString(ufmt.Sprintf("- [%s](%s)\n", m.Summary(), matchLink(m.ID)))
178 n++
179 return n >= limit
180 })
181 if n == 0 {
182 sb.WriteString("No matches yet.\n")
183 }
184 sb.WriteString("\n")
185}
186
187func renderBot(name string) string {
188 v := bots.Get(name)
189 if v == nil {
190 return "# Bot not found\n\n[Back to the arena](" + link("") + ")\n"
191 }
192 b := v.(*Bot)
193 var sb strings.Builder
194 sb.WriteString(ufmt.Sprintf("# %s\n\n", b.Name))
195 if b.Description != "" {
196 sb.WriteString("> " + b.Description + "\n\n")
197 }
198 if b.Retired {
199 sb.WriteString("**Retired:** this bot no longer takes new challenges.\n\n")
200 } else {
201 sb.WriteString(ufmt.Sprintf("[Challenge %s](%s) · [Read its code](%s)\n\n", b.Name, fightLink("", b.Name), sourceLink(b.Realm)))
202 }
203 sb.WriteString(ufmt.Sprintf("- **Season %d:** Elo %d, %d-%d-%d\n", season, b.Rating, b.SeasonWins, b.SeasonLosses, b.SeasonDraws))
204 sb.WriteString(ufmt.Sprintf("- **All time:** %d wins, %d losses (%d by forfeit), %d draws\n", b.Wins, b.Losses, b.Forfeits, b.Draws))
205 sb.WriteString(ufmt.Sprintf("- **Kind:** %s bot, version %d\n- **Realm:** `%s`\n- **Owner:** `%s`\n- **Registered at block:** %d\n", b.kind(), b.Version, b.Realm, b.Owner.String(), b.Registered))
206 if prev := b.PreviousVersions(); len(prev) > 0 {
207 var links []string
208 for i, r := range prev {
209 links = append(links, ufmt.Sprintf("[v%d](%s)", i+1, sourceLink(r)))
210 }
211 sb.WriteString("- **Earlier versions:** " + strings.Join(links, " · ") + "\n")
212 }
213 sb.WriteString("\n## Matches\n\n")
214 writeRecent(&sb, name, 20)
215 sb.WriteString(ufmt.Sprintf("Owner actions: [describe](%s) · ", tx.Call("SetDescription", "name", b.Name, "text", "")))
216 if b.Retired {
217 sb.WriteString(ufmt.Sprintf("[unretire](%s) · ", tx.Call("Unretire", "name", b.Name)))
218 } else {
219 sb.WriteString(ufmt.Sprintf("[retire](%s) · ", tx.Call("Retire", "name", b.Name)))
220 }
221 sb.WriteString("[enter a tournament](" + link("tournaments") + ")\n\n")
222 sb.WriteString("[Back to the arena](" + link("") + ")\n")
223 return sb.String()
224}
225
226func renderMatch(m *Match, turn int) string {
227 g := &m.Game
228 played := g.Turn
229 if turn < 0 || turn > played {
230 turn = played
231 }
232 var sb strings.Builder
233 sb.WriteString(ufmt.Sprintf("# Match #%d: %s vs %s\n\n", m.ID, m.Bot(0), m.Bot(1)))
234 sb.WriteString("**" + m.Summary() + "**\n\n")
235 if m.Tournament != 0 {
236 sb.WriteString(ufmt.Sprintf("Part of [tournament #%d](%s).\n\n", m.Tournament, link("tournament/"+strconv.Itoa(m.Tournament))))
237 }
238 switch {
239 case !m.Rated:
240 sb.WriteString(ufmt.Sprintf("Friendly: these two bots had a rated match less than %d blocks before this one, so ratings don't change.\n\n", RatedCooldown))
241 case m.Status == Finished && m.Winner >= 0:
242 sb.WriteString(ufmt.Sprintf("Rating change: %s %s, %s %s\n\n", m.Bot(0), signed(m.Delta), m.Bot(1), signed(-m.Delta)))
243 }
244 writeActions(&sb, m)
245
246 snap := g.At(turn)
247 sb.WriteString(ufmt.Sprintf("## After turn %d of %d\n\n", turn, bot.Turns))
248 sb.WriteString(ufmt.Sprintf("**A** = %s, %d gold · **B** = %s, %d gold · **$** = coin\n\n", m.Bot(0), snap.Gold[0], m.Bot(1), snap.Gold[1]))
249 sb.WriteString("```\n" + drawBoard(snap.Pos, snap.Coins) + "```\n\n")
250
251 nav := []string{}
252 if turn > 0 {
253 nav = append(nav, ufmt.Sprintf("[« start](%s)", link(ufmt.Sprintf("match/%d/0", m.ID))))
254 nav = append(nav, ufmt.Sprintf("[‹ prev](%s)", link(ufmt.Sprintf("match/%d/%d", m.ID, turn-1))))
255 }
256 if turn < played {
257 nav = append(nav, ufmt.Sprintf("[next ›](%s)", link(ufmt.Sprintf("match/%d/%d", m.ID, turn+1))))
258 nav = append(nav, ufmt.Sprintf("[end »](%s)", link(ufmt.Sprintf("match/%d/%d", m.ID, played))))
259 }
260 if len(nav) > 0 {
261 sb.WriteString(strings.Join(nav, " · ") + "\n\n")
262 }
263 if turn > 0 {
264 sb.WriteString(ufmt.Sprintf("Turn %d: %s **%s**%s, %s **%s**%s\n\n",
265 turn, m.Bot(0), snap.Act[0].String(), eventNote(snap.Events, 0), m.Bot(1), snap.Act[1].String(), eventNote(snap.Events, 1)))
266 }
267
268 writeMoments(&sb, m)
269 sb.WriteString(ufmt.Sprintf("Bots: [%s](%s) · [%s](%s) · [Back to the arena](%s)\n",
270 m.Bot(0), link("bot/"+m.Bot(0)), m.Bot(1), link("bot/"+m.Bot(1)), link("")))
271 return sb.String()
272}
273
274// writeActions shows the buttons that move an unfinished match along.
275func writeActions(sb *strings.Builder, m *Match) {
276 id := strconv.Itoa(m.ID)
277 switch m.Status {
278 case Pending:
279 sb.WriteString(ufmt.Sprintf("Not played yet: [Play it](%s). If a bot keeps making it fail, [switch to step mode](%s).\n\n",
280 tx.Call("Play", "id", id), tx.Call("StartStepMode", "id", id)))
281 case Stepping:
282 sb.WriteString(ufmt.Sprintf("**Step mode:** waiting for **%s** to move, deadline block %d (now %d). [Submit the next move](%s) · [Finish in one go](%s)",
283 m.Bot(m.Waiting), m.Deadline, height(), tx.Call("SubmitMove", "id", id), tx.Call("Play", "id", id)))
284 if height() > m.Deadline {
285 sb.WriteString(ufmt.Sprintf(" · [Claim the forfeit](%s)", tx.Call("ClaimForfeit", "id", id)))
286 }
287 sb.WriteString("\n\n")
288 }
289}
290
291// writeMoments lists the turns where coins changed hands.
292func writeMoments(sb *strings.Builder, m *Match) {
293 var lines []string
294 for i, ev := range m.Game.Timeline() {
295 for side := 0; side < 2; side++ {
296 what := ""
297 switch {
298 case ev.Stole[side]:
299 what = "stole a coin from"
300 case ev.Parried[side]:
301 what = "parried and took a coin from"
302 }
303 if what != "" {
304 lines = append(lines, ufmt.Sprintf("- [Turn %d](%s): %s %s %s", i+1,
305 link(ufmt.Sprintf("match/%d/%d", m.ID, i+1)), m.Bot(side), what, m.Bot(1-side)))
306 }
307 }
308 }
309 if len(lines) == 0 {
310 return
311 }
312 sb.WriteString("## Key moments\n\n")
313 if len(lines) > 12 {
314 more := len(lines) - 12
315 lines = append(lines[:12], ufmt.Sprintf("- …and %d more", more))
316 }
317 sb.WriteString(strings.Join(lines, "\n") + "\n\n")
318}
319
320func signed(n int) string {
321 if n > 0 {
322 return "+" + strconv.Itoa(n)
323 }
324 return strconv.Itoa(n)
325}
326
327func eventNote(ev game.Events, side int) string {
328 switch {
329 case ev.Stole[side]:
330 return " (stole a coin)"
331 case ev.Parried[side]:
332 return " (parried and took a coin)"
333 }
334 return ""
335}
336
337func drawBoard(pos [2]bot.Pos, coins []bot.Pos) string {
338 var sb strings.Builder
339 for y := 0; y < bot.Size; y++ {
340 for x := 0; x < bot.Size; x++ {
341 p := bot.Pos{x, y}
342 cell := "·"
343 for _, c := range coins {
344 if c == p {
345 cell = "$"
346 }
347 }
348 switch p {
349 case pos[0]:
350 cell = "A"
351 case pos[1]:
352 cell = "B"
353 }
354 sb.WriteString(cell)
355 if x < bot.Size-1 {
356 sb.WriteString(" ")
357 }
358 }
359 sb.WriteString("\n")
360 }
361 return sb.String()
362}