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.

render.gno

11.08 Kb · 319 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"
 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
 33func Render(path string) string {
 34	parts := strings.Split(strings.Trim(path, "/"), "/")
 35	switch {
 36	case len(parts) == 2 && parts[0] == "bot":
 37		return renderBot(parts[1])
 38	case (len(parts) == 2 || len(parts) == 3) && parts[0] == "match":
 39		id, err := strconv.Atoi(parts[1])
 40		if _, ok := record(id); err != nil || !ok {
 41			return "# Match not found\n\n[Back to the arena](" + link("") + ")\n"
 42		}
 43		turn := -1
 44		if len(parts) == 3 {
 45			if t, err := strconv.Atoi(parts[2]); err == nil {
 46				turn = t
 47			}
 48		}
 49		return renderMatch(mustMatch(id), turn)
 50	}
 51	return renderHome()
 52}
 53
 54func link(p string) string {
 55	if p == "" {
 56		return self
 57	}
 58	return self + ":" + p
 59}
 60
 61func matchLink(id int) string { return link("match/" + strconv.Itoa(id)) }
 62
 63// fightLink opens a pre-filled Fight transaction; either name may be empty
 64// for the player to fill in.
 65func fightLink(a, b string) string { return tx.Call("Fight", "a", a, "b", b) }
 66
 67func renderHome() string {
 68	var sb strings.Builder
 69	sb.WriteString("# Code Arena\n\n")
 70	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")
 71	sb.WriteString(ufmt.Sprintf("**%d bots** · **%d matches** · [Start a fight](%s)\n\n", bots.Size(), lastID, fightLink("", "")))
 72
 73	sb.WriteString("## Leaderboard\n\n")
 74	ranked := leaderboard()
 75	if len(ranked) == 0 {
 76		sb.WriteString("No bots yet.\n\n")
 77	} else {
 78		sb.WriteString("| # | Bot | Elo | W-L-D | |\n|---|---|---|---|---|\n")
 79		for i, b := range ranked {
 80			if i == 20 {
 81				break
 82			}
 83			sb.WriteString(ufmt.Sprintf("| %d | [%s](%s) | %d | %d-%d-%d | [code](%s) · [fight](%s) |\n",
 84				i+1, b.Name, link("bot/"+b.Name), b.Rating, b.Wins, b.Losses, b.Draws, sourceLink(b.Realm), fightLink("", b.Name)))
 85		}
 86		sb.WriteString("\n")
 87	}
 88
 89	sb.WriteString("## Recent matches\n\n")
 90	writeRecent(&sb, "", 10)
 91
 92	sb.WriteString("## Rules\n\n")
 93	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")
 94	sb.WriteString("- Each turn both bots choose at once: `Up`, `Down`, `Left`, `Right`, `Stay`, `Attack` or `Defend`.\n")
 95	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")
 96	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")
 97	sb.WriteString("- Most gold after 50 turns wins. Ratings are Elo-style; a pair of bots plays at most one rated match every ")
 98	sb.WriteString(strconv.Itoa(RatedCooldown) + " blocks, and rematches in between are friendlies.\n\n")
 99	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")
100
101	sb.WriteString("## Build a bot\n\n")
102	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")
103	sb.WriteString("2. Register it from your realm's `init`: `arena.RegisterBot(cross(cur), \"my-bot\", &myBot{})`.\n")
104	sb.WriteString(ufmt.Sprintf("3. [Fight](%s) anyone on the leaderboard.\n\n", fightLink("my-bot", "")))
105	sb.WriteString("Starter bots to read and beat: [strategies](/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/strategies) · [reader](/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bots/reader), a realm bot that learns each opponent's habits.\n\n")
106
107	sb.WriteString("## No escaping a loss\n\n")
108	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")
109	return sb.String()
110}
111
112func (b *Bot) kind() string {
113	if b.fn != nil {
114		return "function"
115	}
116	return "realm"
117}
118
119func leaderboard() []*Bot {
120	var out []*Bot
121	bots.Iterate("", "", func(_ string, v any) bool {
122		out = append(out, v.(*Bot))
123		return false
124	})
125	// insertion sort: highest rating first, then most wins, then name
126	for i := 1; i < len(out); i++ {
127		for j := i; j > 0 && better(out[j], out[j-1]); j-- {
128			out[j], out[j-1] = out[j-1], out[j]
129		}
130	}
131	return out
132}
133
134func better(a, b *Bot) bool {
135	if a.Rating != b.Rating {
136		return a.Rating > b.Rating
137	}
138	if a.Wins != b.Wins {
139		return a.Wins > b.Wins
140	}
141	return a.Name < b.Name
142}
143
144func sourceLink(realmPath string) string {
145	if i := strings.Index(realmPath, "/"); i >= 0 {
146		realmPath = realmPath[i:]
147	}
148	return realmPath + "$source"
149}
150
151// writeRecent lists the latest matches, optionally only those of one bot
152// among the last 500.
153func writeRecent(sb *strings.Builder, botName string, limit int) {
154	n := 0
155	eachRecent(500, func(m *Match) bool {
156		if botName != "" && m.BotA != botName && m.BotB != botName {
157			return false
158		}
159		sb.WriteString(ufmt.Sprintf("- [%s](%s)\n", m.Summary(), matchLink(m.ID)))
160		n++
161		return n >= limit
162	})
163	if n == 0 {
164		sb.WriteString("No matches yet.\n")
165	}
166	sb.WriteString("\n")
167}
168
169func renderBot(name string) string {
170	v := bots.Get(name)
171	if v == nil {
172		return "# Bot not found\n\n[Back to the arena](" + link("") + ")\n"
173	}
174	b := v.(*Bot)
175	var sb strings.Builder
176	sb.WriteString(ufmt.Sprintf("# %s\n\n", b.Name))
177	sb.WriteString(ufmt.Sprintf("[Challenge %s](%s) · [Read its code](%s)\n\n", b.Name, fightLink("", b.Name), sourceLink(b.Realm)))
178	sb.WriteString(ufmt.Sprintf("- **Rating:** %d\n- **Record:** %d wins, %d losses (%d by forfeit), %d draws\n", b.Rating, b.Wins, b.Losses, b.Forfeits, b.Draws))
179	sb.WriteString(ufmt.Sprintf("- **Kind:** %s bot\n- **Realm:** `%s`\n- **Owner:** `%s`\n- **Registered at block:** %d\n\n", b.kind(), b.Realm, b.Owner.String(), b.Registered))
180	sb.WriteString("## Matches\n\n")
181	writeRecent(&sb, name, 20)
182	sb.WriteString("[Back to the arena](" + link("") + ")\n")
183	return sb.String()
184}
185
186func renderMatch(m *Match, turn int) string {
187	g := &m.Game
188	played := g.Turn
189	if turn < 0 || turn > played {
190		turn = played
191	}
192	var sb strings.Builder
193	sb.WriteString(ufmt.Sprintf("# Match #%d: %s vs %s\n\n", m.ID, m.Bot(0), m.Bot(1)))
194	sb.WriteString("**" + m.Summary() + "**\n\n")
195	switch {
196	case !m.Rated:
197		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))
198	case m.Status == Finished && m.Winner >= 0:
199		sb.WriteString(ufmt.Sprintf("Rating change: %s %s, %s %s\n\n", m.Bot(0), signed(m.Delta), m.Bot(1), signed(-m.Delta)))
200	}
201	writeActions(&sb, m)
202
203	snap := g.At(turn)
204	sb.WriteString(ufmt.Sprintf("## After turn %d of %d\n\n", turn, bot.Turns))
205	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]))
206	sb.WriteString("```\n" + drawBoard(snap.Pos, snap.Coins) + "```\n\n")
207
208	nav := []string{}
209	if turn > 0 {
210		nav = append(nav, ufmt.Sprintf("[« start](%s)", link(ufmt.Sprintf("match/%d/0", m.ID))))
211		nav = append(nav, ufmt.Sprintf("[‹ prev](%s)", link(ufmt.Sprintf("match/%d/%d", m.ID, turn-1))))
212	}
213	if turn < played {
214		nav = append(nav, ufmt.Sprintf("[next ›](%s)", link(ufmt.Sprintf("match/%d/%d", m.ID, turn+1))))
215		nav = append(nav, ufmt.Sprintf("[end »](%s)", link(ufmt.Sprintf("match/%d/%d", m.ID, played))))
216	}
217	if len(nav) > 0 {
218		sb.WriteString(strings.Join(nav, " · ") + "\n\n")
219	}
220	if turn > 0 {
221		sb.WriteString(ufmt.Sprintf("Turn %d: %s **%s**%s, %s **%s**%s\n\n",
222			turn, m.Bot(0), snap.Act[0].String(), eventNote(snap.Events, 0), m.Bot(1), snap.Act[1].String(), eventNote(snap.Events, 1)))
223	}
224
225	writeMoments(&sb, m)
226	sb.WriteString(ufmt.Sprintf("Bots: [%s](%s) · [%s](%s) · [Back to the arena](%s)\n",
227		m.Bot(0), link("bot/"+m.Bot(0)), m.Bot(1), link("bot/"+m.Bot(1)), link("")))
228	return sb.String()
229}
230
231// writeActions shows the buttons that move an unfinished match along.
232func writeActions(sb *strings.Builder, m *Match) {
233	id := strconv.Itoa(m.ID)
234	switch m.Status {
235	case Pending:
236		sb.WriteString(ufmt.Sprintf("Not played yet: [Play it](%s). If a bot keeps making it fail, [switch to step mode](%s).\n\n",
237			tx.Call("Play", "id", id), tx.Call("StartStepMode", "id", id)))
238	case Stepping:
239		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)",
240			m.Bot(m.Waiting), m.Deadline, height(), tx.Call("SubmitMove", "id", id), tx.Call("Play", "id", id)))
241		if height() > m.Deadline {
242			sb.WriteString(ufmt.Sprintf(" · [Claim the forfeit](%s)", tx.Call("ClaimForfeit", "id", id)))
243		}
244		sb.WriteString("\n\n")
245	}
246}
247
248// writeMoments lists the turns where coins changed hands.
249func writeMoments(sb *strings.Builder, m *Match) {
250	var lines []string
251	for i, ev := range m.Game.Timeline() {
252		for side := 0; side < 2; side++ {
253			what := ""
254			switch {
255			case ev.Stole[side]:
256				what = "stole a coin from"
257			case ev.Parried[side]:
258				what = "parried and took a coin from"
259			}
260			if what != "" {
261				lines = append(lines, ufmt.Sprintf("- [Turn %d](%s): %s %s %s", i+1,
262					link(ufmt.Sprintf("match/%d/%d", m.ID, i+1)), m.Bot(side), what, m.Bot(1-side)))
263			}
264		}
265	}
266	if len(lines) == 0 {
267		return
268	}
269	sb.WriteString("## Key moments\n\n")
270	if len(lines) > 12 {
271		more := len(lines) - 12
272		lines = append(lines[:12], ufmt.Sprintf("- …and %d more", more))
273	}
274	sb.WriteString(strings.Join(lines, "\n") + "\n\n")
275}
276
277func signed(n int) string {
278	if n > 0 {
279		return "+" + strconv.Itoa(n)
280	}
281	return strconv.Itoa(n)
282}
283
284func eventNote(ev game.Events, side int) string {
285	switch {
286	case ev.Stole[side]:
287		return " (stole a coin)"
288	case ev.Parried[side]:
289		return " (parried and took a coin)"
290	}
291	return ""
292}
293
294func drawBoard(pos [2]bot.Pos, coins []bot.Pos) string {
295	var sb strings.Builder
296	for y := 0; y < bot.Size; y++ {
297		for x := 0; x < bot.Size; x++ {
298			p := bot.Pos{x, y}
299			cell := "·"
300			for _, c := range coins {
301				if c == p {
302					cell = "$"
303				}
304			}
305			switch p {
306			case pos[0]:
307				cell = "A"
308			case pos[1]:
309				cell = "B"
310			}
311			sb.WriteString(cell)
312			if x < bot.Size-1 {
313				sb.WriteString(" ")
314			}
315		}
316		sb.WriteString("\n")
317	}
318	return sb.String()
319}