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.

Playground

arena.gno

// Package arena runs matches between bots that other people deploy as their
// own realms. Every turn the arena calls each bot's code, so the chain is the
// referee and every bot's source is public.
//
// Matches have two speeds:
//
//   - Fast: Play (or Fight) runs a whole match in one transaction.
//   - Step: if a match can't finish in one transaction (a bot crashes or runs
//     out of gas), StartStepMode switches it to one move per SubmitMove
//     transaction. The bot whose move can't be made misses its deadline and
//     ClaimForfeit records the loss. Crashing can't save a bot from a loss.
package arena

import (
	"chain/runtime/unsafe"
	"strings"

	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
	"gno.land/p/nt/avl/v0"
)

const (
	maxBotsPerRealm = 5
	startRating     = 1200
)

// Bot is a registered bot.
type Bot struct {
	Name       string
	Realm      string  // realm that registered it; its source is public
	Owner      address // account that sent the registering transaction
	Registered int64   // block height
	Rating     int
	Wins       int
	Losses     int
	Draws      int
	Forfeits   int // losses by forfeit, also counted in Losses

	impl        bot.Bot
	fn          bot.Strategy
	recentRated string // "opponent@block," for recent rated matches, see claimRatedSlot
}

// Played is the number of finished matches.
func (b *Bot) Played() int { return b.Wins + b.Losses + b.Draws }

var (
	bots         = avl.NewTree() // name -> *Bot
	botsPerRealm = avl.NewTree() // realm path -> int
)

// RegisterBot enters a bot with a Move method. Call it from your bot realm,
// usually in init:
//
//	func init(cur realm) { arena.RegisterBot(cross(cur), "my-bot", &myBot{}) }
func RegisterBot(cur realm, name string, b bot.Bot) {
	if b == nil {
		panic("bot is nil")
	}
	register(cur, name, &Bot{impl: b})
}

// RegisterStrategy enters a bot written as a plain function. A function
// declared in a /p/ package has one extra guarantee: if it crashes, the arena
// can catch it straight away and score a forfeit without step mode.
func RegisterStrategy(cur realm, name string, s bot.Strategy) {
	if s == nil {
		panic("strategy is nil")
	}
	register(cur, name, &Bot{fn: s})
}

func register(cur realm, name string, b *Bot) {
	caller := cur.Previous()
	if !caller.IsCode() || caller.IsEphemeral() {
		panic("bots must be registered by a deployed realm, so their source is public")
	}
	if err := validName(name); err != "" {
		panic(err)
	}
	if bots.Has(name) {
		panic("bot name already taken: " + name)
	}
	realmPath := caller.PkgPath()
	count := 0
	if v := botsPerRealm.Get(realmPath); v != nil {
		count = v.(int)
	}
	if count >= maxBotsPerRealm {
		panic("this realm already registered the maximum number of bots")
	}
	b.Name = name
	b.Realm = realmPath
	b.Owner = unsafe.OriginCaller()
	b.Registered = height()
	b.Rating = startRating
	bots.Set(name, b)
	botsPerRealm.Set(realmPath, count+1)
	emit("BotRegistered", "name", name, "realm", realmPath)
}

func validName(name string) string {
	if len(name) < 3 || len(name) > 24 {
		return "bot names must be 3 to 24 characters"
	}
	for i, c := range name {
		ok := (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '-' && i > 0 && i < len(name)-1)
		if !ok {
			return "bot names may only use a-z, 0-9 and inner dashes"
		}
	}
	if strings.Contains(name, "--") {
		return "bot names may not contain --"
	}
	return ""
}

func mustBot(name string) *Bot {
	v := bots.Get(name)
	if v == nil {
		panic("unknown bot: " + name)
	}
	return v.(*Bot)
}

// ask gets one move from b. A crash inside a /p/ function bot is caught and
// reported; a crash inside realm code aborts the transaction (Gno does not
// let the caller recover it), which is what step mode is for.
func (b *Bot) ask(s bot.State) (a bot.Action, crashed bool) {
	defer func() {
		if r := recover(); r != nil {
			crashed = true
		}
	}()
	if b.impl != nil {
		return b.impl.Move(s), false
	}
	return b.fn(s), false
}

// BotInfo describes a bot for other realms and off-chain tools.
type BotInfo struct {
	Name, Realm                                   string
	Owner                                         address
	Rating, Wins, Losses, Draws, Forfeits, Played int
}

// GetBot returns public information about a bot.
func GetBot(name string) (BotInfo, bool) {
	v := bots.Get(name)
	if v == nil {
		return BotInfo{}, false
	}
	b := v.(*Bot)
	return BotInfo{b.Name, b.Realm, b.Owner, b.Rating, b.Wins, b.Losses, b.Draws, b.Forfeits, b.Played()}, true
}

// BotCount is the number of registered bots.
func BotCount() int { return bots.Size() }

codec.gno

package arena

import (
	"strconv"
	"strings"

	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/game"
)

// Matches are stored as one compact string each, not as Go objects. Every
// stored object carries its own id, hash and type information, so a Match
// struct with an embedded Game used to cost several KB. A string costs little
// more than its bytes. On top of that, bucketSize records share one tree node:
// storage is paid on the bytes a transaction adds, so a new match mostly pays
// for its own record and only every bucketSize-th match pays for a new node.
// A Match is decoded when a transaction or page needs it and encoded again
// when it changes.

const (
	bucketSize = 16
	recSep     = "\x1e" // record separator inside a bucket
	sep        = "\x1f" // field separator; never appears in names or reasons
	byteOffset = 40     // coins (0-80) and moves (0-6) are shifted into printable bytes
	codecV1    = "1"
)

func shift(raw string) string {
	b := []byte(raw)
	for i := range b {
		b[i] += byteOffset
	}
	return string(b)
}

func unshift(enc string) string {
	b := []byte(enc)
	for i := range b {
		b[i] -= byteOffset
	}
	return string(b)
}

func itoa(n int) string  { return strconv.Itoa(n) }
func i64(n int64) string { return strconv.FormatInt(n, 10) }
func flag(b bool) string {
	if b {
		return "1"
	}
	return "0"
}

func (m *Match) encode() string {
	g := &m.Game
	return strings.Join([]string{
		codecV1,
		m.BotA, m.BotB, itoa(int(m.Status)),
		itoa(g.Seed), itoa(g.Turn), itoa(g.CellA), itoa(g.CellB), itoa(g.GoldA), itoa(g.GoldB),
		shift(g.Coins), shift(g.Moves),
		m.Challenger.String(), i64(m.Created), flag(m.Rated),
		itoa(m.Waiting), itoa(int(m.Held)), i64(m.Deadline),
		itoa(m.Winner), flag(m.Forfeit), m.Reason, itoa(m.Delta), i64(m.Settled),
	}, sep)
}

func decode(id int, s string) *Match {
	f := strings.Split(s, sep)
	if len(f) != 23 || f[0] != codecV1 {
		panic("corrupt match record " + itoa(id))
	}
	n := func(i int) int {
		v, err := strconv.Atoi(f[i])
		if err != nil {
			panic("corrupt match record " + itoa(id))
		}
		return v
	}
	n64 := func(i int) int64 { return int64(n(i)) }
	return &Match{
		ID:     id,
		BotA:   f[1],
		BotB:   f[2],
		Status: Status(n(3)),
		Game: game.Game{
			Seed: n(4), Turn: n(5), CellA: n(6), CellB: n(7), GoldA: n(8), GoldB: n(9),
			Coins: unshift(f[10]), Moves: unshift(f[11]),
		},
		Challenger: address(f[12]),
		Created:    n64(13),
		Rated:      f[14] == "1",
		Waiting:    n(15),
		Held:       bot.Action(n(16)),
		Deadline:   n64(17),
		Winner:     n(18),
		Forfeit:    f[19] == "1",
		Reason:     f[20],
		Delta:      n(21),
		Settled:    n64(22),
	}
}

func bucketKey(id int) string { return key((id - 1) / bucketSize) }

func bucket(id int) []string {
	v := matches.Get(bucketKey(id))
	if v == nil {
		return nil
	}
	return strings.Split(v.(string), recSep)
}

// record returns the stored string for match id.
func record(id int) (string, bool) {
	if id < 1 || id > lastID {
		return "", false
	}
	recs := bucket(id)
	i := (id - 1) % bucketSize
	if i >= len(recs) {
		return "", false
	}
	return recs[i], true
}

// save writes the match back into its bucket.
func (m *Match) save() {
	recs := bucket(m.ID)
	i := (m.ID - 1) % bucketSize
	switch {
	case i == len(recs):
		recs = append(recs, m.encode())
	case i < len(recs):
		recs[i] = m.encode()
	default:
		panic("match records out of order")
	}
	matches.Set(bucketKey(m.ID), strings.Join(recs, recSep))
}

// eachRecent calls fn on matches from newest to oldest, looking at no more
// than maxScan of them, until fn returns true.
func eachRecent(maxScan int, fn func(m *Match) bool) {
	var recs []string
	cached := -1
	for id := lastID; id >= 1 && id > lastID-maxScan; id-- {
		if b := (id - 1) / bucketSize; b != cached {
			recs, cached = bucket(id), b
		}
		if fn(decode(id, recs[(id-1)%bucketSize])) {
			return
		}
	}
}

codec_test.gno

package arena

import (
	"testing"

	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/game"
)

func TestCodecRoundTrip(t *testing.T) {
	g := game.New(77)
	for i := 0; i < 23; i++ {
		g.Step(bot.Action(i%7), bot.Action((i+3)%7))
	}
	m := &Match{
		ID: 42, BotA: "alpha-1", BotB: "zeta", Status: Stepping, Game: *g,
		Challenger: address("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"),
		Created:    123456789012, Rated: true, Waiting: 1, Held: bot.Defend, Deadline: 123456789112,
		Winner: 1, Forfeit: true, Reason: "zeta missed its move deadline on turn 24", Delta: -17, Settled: 99,
	}
	got := decode(42, m.encode())
	if got.encode() != m.encode() {
		t.Fatal("round trip changed the record")
	}
	if got.Game.Moves != g.Moves || got.Game.Coins != g.Coins || got.Game.Turn != 23 {
		t.Fatal("game state lost")
	}
	if got.Challenger != m.Challenger || got.Held != bot.Defend || got.Delta != -17 || !got.Rated || got.Created != 123456789012 {
		t.Fatalf("fields lost: %+v", got)
	}
	// the replay rebuilt from the decoded record matches the live game
	if got.Game.At(23).Pos != g.At(23).Pos {
		t.Fatal("replay differs after decoding")
	}
}

func TestCodecRejectsCorruptRecords(t *testing.T) {
	defer func() {
		if recover() == nil {
			t.Fatal("expected a panic")
		}
	}()
	decode(1, "garbage")
}

gnomod.toml

module = "gno.land/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/arena"
gno = "0.9"

[addpkg]
  creator = "g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28"
  height = 1445161
  max_deposit = "50000000ugnot"

match.gno

package arena

import (
	"chain"
	"chain/runtime"
	"strconv"
	"strings"

	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/game"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ufmt/v0"
)

const (
	// MoveTimeout is how many blocks a bot has to make its move in step mode
	// before anyone can claim a forfeit.
	MoveTimeout = 100
	// RatedCooldown is how many blocks must pass between two rated matches of
	// the same pair of bots. Rematches in between are friendlies, so nobody
	// can pump a rating by replaying the same opponent.
	RatedCooldown = 1000
)

// Status of a match.
type Status int

const (
	Pending  Status = iota // challenged, not played yet
	Stepping               // being played one move per transaction
	Finished
)

func (s Status) String() string {
	switch s {
	case Pending:
		return "pending"
	case Stepping:
		return "step mode"
	}
	return "finished"
}

// Match is one game between two bots. Side 0 is A, side 1 is B.
type Match struct {
	ID         int
	BotA, BotB string
	Status     Status
	Game       game.Game
	Challenger address
	Created    int64
	Rated      bool // decided when the match is created, see RatedCooldown

	// step mode
	Waiting  int        // side whose move is due
	Held     bot.Action // side 0's move for the current turn, once made
	Deadline int64      // block height by which Waiting must move

	// result
	Winner  int    // 0, 1, or -1 for a draw
	Forfeit bool   // the loser forfeited
	Reason  string // why, for forfeits
	Delta   int    // rating change for A (B gets the opposite)
	Settled int64  // block height
}

var (
	matches   = avl.NewTree() // padded bucket number -> encoded matches (see codec.gno)
	lastID    = 0
)

// claimRatedSlot reports whether a new match between a and b is rated, and
// if so starts the pair's cooldown. The cooldown is kept on the bot whose
// name sorts first, as a short "opponent@block," list that drops expired
// entries, so it costs a few bytes instead of a tree node per pair.
func claimRatedSlot(a, b string) bool {
	if b < a {
		a, b = b, a
	}
	keeper := mustBot(a)
	now := height()
	var kept []string
	rated := true
	for _, e := range strings.Split(keeper.recentRated, ",") {
		at := strings.LastIndex(e, "@")
		if at < 0 {
			continue
		}
		h, err := strconv.ParseInt(e[at+1:], 10, 64)
		if err != nil || now-h >= RatedCooldown {
			continue // expired
		}
		if e[:at] == b {
			rated = false
		}
		kept = append(kept, e)
	}
	if rated {
		kept = append(kept, b+"@"+strconv.FormatInt(now, 10))
	}
	keeper.recentRated = strings.Join(kept, ",")
	return rated
}

// Bot returns the name of the bot playing side.
func (m *Match) Bot(side int) string {
	if side == 0 {
		return m.BotA
	}
	return m.BotB
}

func key(id int) string {
	s := strconv.Itoa(id)
	for len(s) < 10 {
		s = "0" + s
	}
	return s
}

func height() int64 { return runtime.ChainHeight() }

func emit(typ string, attrs ...string) { chain.Emit(typ, attrs...) }

func mustMatch(id int) *Match {
	r, ok := record(id)
	if !ok {
		panic("unknown match: " + strconv.Itoa(id))
	}
	return decode(id, r)
}

// seedFor gives every match its own board. The pair is mixed in so two
// matches created back to back between different bots differ too.
func seedFor(id int, a, b string) int {
	h := uint32(2166136261)
	for _, s := range []string{a, "|", b} {
		for i := 0; i < len(s); i++ {
			h = (h ^ uint32(s[i])) * 16777619
		}
	}
	return int((h + uint32(id)*7919) % 1000003)
}

// Challenge records a new match between two registered bots and returns its
// id. It runs no bot code, so it always succeeds; play it with Play or, if
// that fails, with step mode.
func Challenge(cur realm, a, b string) int {
	m := newMatch(cur, a, b)
	m.save()
	return m.ID
}

func newMatch(cur realm, a, b string) *Match {
	if a == b {
		panic("a bot can't fight itself")
	}
	mustBot(a)
	mustBot(b)
	lastID++
	m := &Match{
		ID:         lastID,
		BotA:       a,
		BotB:       b,
		Status:     Pending,
		Game:       *game.New(seedFor(lastID, a, b)),
		Challenger: cur.Previous().Address(),
		Created:    height(),
		Rated:      claimRatedSlot(a, b),
		Winner:     -1,
	}
	emit("MatchCreated", "id", strconv.Itoa(m.ID), "a", a, "b", b)
	return m
}

// Play runs the rest of a match in this transaction. If a bot written in
// realm code crashes or runs out of gas, the whole transaction fails and the
// match stays as it was: switch it to step mode with StartStepMode.
func Play(cur realm, id int) string {
	m := mustMatch(id)
	if m.Status == Finished {
		panic("match already finished")
	}
	m.play()
	m.save()
	return m.Summary()
}

// Fight challenges and plays in one transaction, saving the match once. If
// it fails, nothing is recorded: use Challenge, then Play or step mode.
func Fight(cur realm, a, b string) string {
	m := newMatch(cur, a, b)
	m.play()
	m.save()
	return m.Summary()
}

// play runs the match to the end in memory.
func (m *Match) play() {
	players := [2]*Bot{mustBot(m.BotA), mustBot(m.BotB)}
	for !m.Game.Over() {
		var acts [2]bot.Action
		for side := 0; side < 2; side++ {
			if m.Status == Stepping && side == 0 && m.Waiting == 1 {
				acts[0] = m.Held // already made in step mode
				continue
			}
			a, crashed := players[side].ask(m.view(side))
			if crashed {
				m.forfeit(side, "crashed on turn "+strconv.Itoa(m.Game.Turn+1))
				return
			}
			acts[side] = a
		}
		m.Game.Step(acts[0], acts[1])
		m.Waiting = 0
	}
	m.finish()
}

// StartStepMode switches a pending match to one move per transaction.
// Anyone may call it.
func StartStepMode(cur realm, id int) {
	m := mustMatch(id)
	if m.Status != Pending {
		panic("only a pending match can switch to step mode")
	}
	defer m.save()
	m.Status = Stepping
	m.Waiting = 0
	m.Deadline = height() + MoveTimeout
	emit("StepModeStarted", "id", strconv.Itoa(id))
}

// SubmitMove asks the bot whose turn it is for its move and records it. The
// move comes from the bot's own code, so nobody can submit a fake one.
// Anyone may call it.
func SubmitMove(cur realm, id int) string {
	m := mustMatch(id)
	if m.Status != Stepping {
		panic("match is not in step mode")
	}
	defer m.save()
	side := m.Waiting
	a, crashed := mustBot(m.Bot(side)).ask(m.view(side))
	if crashed {
		m.forfeit(side, "crashed on turn "+strconv.Itoa(m.Game.Turn+1))
		return m.Summary()
	}
	if side == 0 {
		m.Held = a
		m.Waiting = 1
	} else {
		m.Game.Step(m.Held, a)
		m.Waiting = 0
	}
	m.Deadline = height() + MoveTimeout
	if m.Game.Over() {
		m.finish()
	}
	return m.Summary()
}

// ClaimForfeit ends a step-mode match whose waiting bot missed its deadline.
// Anyone may call it.
func ClaimForfeit(cur realm, id int) string {
	m := mustMatch(id)
	if m.Status != Stepping {
		panic("match is not in step mode")
	}
	if height() <= m.Deadline {
		panic(ufmt.Sprintf("%s still has until block %d to move", m.Bot(m.Waiting), m.Deadline))
	}
	defer m.save()
	m.forfeit(m.Waiting, "missed its move deadline on turn "+strconv.Itoa(m.Game.Turn+1))
	return m.Summary()
}

// view is what side's bot sees this turn.
func (m *Match) view(side int) bot.State {
	s := m.Game.View(m.ID, side)
	s.EnemyBot = m.Bot(1 - side)
	return s
}

func (m *Match) finish() {
	m.Winner = m.Game.Winner()
	m.settle()
}

func (m *Match) forfeit(loser int, reason string) {
	m.Winner = 1 - loser
	m.Forfeit = true
	m.Reason = m.Bot(loser) + " " + reason
	m.settle()
}

func (m *Match) settle() {
	m.Status = Finished
	m.Settled = height()
	a, b := mustBot(m.BotA), mustBot(m.BotB)
	if m.Rated {
		m.Delta = rate(a, b, m.Winner)
	}
	switch m.Winner {
	case 0:
		a.Wins++
		b.Losses++
		if m.Forfeit {
			b.Forfeits++
		}
	case 1:
		b.Wins++
		a.Losses++
		if m.Forfeit {
			a.Forfeits++
		}
	default:
		a.Draws++
		b.Draws++
	}
	winner := "draw"
	if m.Winner >= 0 {
		winner = m.Bot(m.Winner)
	}
	emit("MatchFinished", "id", strconv.Itoa(m.ID), "winner", winner,
		"gold", ufmt.Sprintf("%d-%d", m.Game.GoldA, m.Game.GoldB))
}

// Summary is a one-line description of the match.
func (m *Match) Summary() string {
	g := &m.Game
	score := ufmt.Sprintf("%s %d - %d %s", m.Bot(0), g.GoldA, g.GoldB, m.Bot(1))
	switch {
	case m.Status != Finished:
		return ufmt.Sprintf("#%d %s (%s, turn %d of %d)", m.ID, score, m.Status.String(), g.Turn, bot.Turns)
	case m.Forfeit:
		return ufmt.Sprintf("#%d %s wins by forfeit: %s%s", m.ID, m.Bot(m.Winner), m.Reason, m.friendlyNote())
	case m.Winner < 0:
		return ufmt.Sprintf("#%d %s, draw%s", m.ID, score, m.friendlyNote())
	}
	return ufmt.Sprintf("#%d %s, %s wins%s", m.ID, score, m.Bot(m.Winner), m.friendlyNote())
}

func (m *Match) friendlyNote() string {
	if m.Rated {
		return ""
	}
	return " (friendly)"
}

// MatchSummary returns the summary of a match, for other realms and tools.
func MatchSummary(id int) string { return mustMatch(id).Summary() }

// MatchCount is the number of matches ever created.
func MatchCount() int { return lastID }

rating.gno

package arena

const kFactor = 32

// expected is a's chance of beating b, in thousandths, from an Elo-style
// rating gap. It uses a straight-line approximation of the logistic curve:
// even ratings give 500, and a gap of 400 or more is capped at 50 / 950.
func expected(ra, rb int) int {
	e := 500 + (ra-rb)*450/400
	if e < 50 {
		return 50
	}
	if e > 950 {
		return 950
	}
	return e
}

// rate updates both ratings for a result (0, 1, or -1 for a draw) and
// returns the change for a (b's is the opposite).
func rate(a, b *Bot, winner int) int {
	score := 500 // thousandths: 1000 win, 500 draw, 0 loss for side a
	switch winner {
	case 0:
		score = 1000
	case 1:
		score = 0
	}
	d := kFactor * (score - expected(a.Rating, b.Rating)) / 1000
	a.Rating += d
	b.Rating -= d
	return d
}

render.gno

package arena

import (
	"strconv"
	"strings"

	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
	"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/game"
	"gno.land/p/moul/txlink/v0"
	"gno.land/p/nt/ufmt/v0"
)

var (
	self string        // this realm's path as gnoweb links it, e.g. "/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/arena"
	tx   txlink.Realm  // builds transaction links to this realm
)

func init(cur realm) {
	full := cur.PkgPath()
	tx = txlink.Realm(full)
	self = full
	if i := strings.Index(full, "/"); i >= 0 {
		self = full[i:] // drop the chain domain
	}
}

// Render draws the arena pages in gnoweb:
//
//	""                   leaderboard, recent matches, rules
//	"bot/<name>"         a bot's record, source link and a challenge button
//	"match/<id>"         the final board, key moments and actions
//	"match/<id>/<turn>"  the board after one turn
func Render(path string) string {
	parts := strings.Split(strings.Trim(path, "/"), "/")
	switch {
	case len(parts) == 2 && parts[0] == "bot":
		return renderBot(parts[1])
	case (len(parts) == 2 || len(parts) == 3) && parts[0] == "match":
		id, err := strconv.Atoi(parts[1])
		if _, ok := record(id); err != nil || !ok {
			return "# Match not found\n\n[Back to the arena](" + link("") + ")\n"
		}
		turn := -1
		if len(parts) == 3 {
			if t, err := strconv.Atoi(parts[2]); err == nil {
				turn = t
			}
		}
		return renderMatch(mustMatch(id), turn)
	}
	return renderHome()
}

func link(p string) string {
	if p == "" {
		return self
	}
	return self + ":" + p
}

func matchLink(id int) string { return link("match/" + strconv.Itoa(id)) }

// fightLink opens a pre-filled Fight transaction; either name may be empty
// for the player to fill in.
func fightLink(a, b string) string { return tx.Call("Fight", "a", a, "b", b) }

func renderHome() string {
	var sb strings.Builder
	sb.WriteString("# Code Arena\n\n")
	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")
	sb.WriteString(ufmt.Sprintf("**%d bots** · **%d matches** · [Start a fight](%s)\n\n", bots.Size(), lastID, fightLink("", "")))

	sb.WriteString("## Leaderboard\n\n")
	ranked := leaderboard()
	if len(ranked) == 0 {
		sb.WriteString("No bots yet.\n\n")
	} else {
		sb.WriteString("| # | Bot | Elo | W-L-D | |\n|---|---|---|---|---|\n")
		for i, b := range ranked {
			if i == 20 {
				break
			}
			sb.WriteString(ufmt.Sprintf("| %d | [%s](%s) | %d | %d-%d-%d | [code](%s) · [fight](%s) |\n",
				i+1, b.Name, link("bot/"+b.Name), b.Rating, b.Wins, b.Losses, b.Draws, sourceLink(b.Realm), fightLink("", b.Name)))
		}
		sb.WriteString("\n")
	}

	sb.WriteString("## Recent matches\n\n")
	writeRecent(&sb, "", 10)

	sb.WriteString("## Rules\n\n")
	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")
	sb.WriteString("- Each turn both bots choose at once: `Up`, `Down`, `Left`, `Right`, `Stay`, `Attack` or `Defend`.\n")
	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")
	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")
	sb.WriteString("- Most gold after 50 turns wins. Ratings are Elo-style; a pair of bots plays at most one rated match every ")
	sb.WriteString(strconv.Itoa(RatedCooldown) + " blocks, and rematches in between are friendlies.\n\n")
	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")

	sb.WriteString("## Build a bot\n\n")
	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")
	sb.WriteString("2. Register it from your realm's `init`: `arena.RegisterBot(cross(cur), \"my-bot\", &myBot{})`.\n")
	sb.WriteString(ufmt.Sprintf("3. [Fight](%s) anyone on the leaderboard.\n\n", fightLink("my-bot", "")))
	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")

	sb.WriteString("## No escaping a loss\n\n")
	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")
	return sb.String()
}

func (b *Bot) kind() string {
	if b.fn != nil {
		return "function"
	}
	return "realm"
}

func leaderboard() []*Bot {
	var out []*Bot
	bots.Iterate("", "", func(_ string, v any) bool {
		out = append(out, v.(*Bot))
		return false
	})
	// insertion sort: highest rating first, then most wins, then name
	for i := 1; i < len(out); i++ {
		for j := i; j > 0 && better(out[j], out[j-1]); j-- {
			out[j], out[j-1] = out[j-1], out[j]
		}
	}
	return out
}

func better(a, b *Bot) bool {
	if a.Rating != b.Rating {
		return a.Rating > b.Rating
	}
	if a.Wins != b.Wins {
		return a.Wins > b.Wins
	}
	return a.Name < b.Name
}

func sourceLink(realmPath string) string {
	if i := strings.Index(realmPath, "/"); i >= 0 {
		realmPath = realmPath[i:]
	}
	return realmPath + "$source"
}

// writeRecent lists the latest matches, optionally only those of one bot
// among the last 500.
func writeRecent(sb *strings.Builder, botName string, limit int) {
	n := 0
	eachRecent(500, func(m *Match) bool {
		if botName != "" && m.BotA != botName && m.BotB != botName {
			return false
		}
		sb.WriteString(ufmt.Sprintf("- [%s](%s)\n", m.Summary(), matchLink(m.ID)))
		n++
		return n >= limit
	})
	if n == 0 {
		sb.WriteString("No matches yet.\n")
	}
	sb.WriteString("\n")
}

func renderBot(name string) string {
	v := bots.Get(name)
	if v == nil {
		return "# Bot not found\n\n[Back to the arena](" + link("") + ")\n"
	}
	b := v.(*Bot)
	var sb strings.Builder
	sb.WriteString(ufmt.Sprintf("# %s\n\n", b.Name))
	sb.WriteString(ufmt.Sprintf("[Challenge %s](%s) · [Read its code](%s)\n\n", b.Name, fightLink("", b.Name), sourceLink(b.Realm)))
	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))
	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))
	sb.WriteString("## Matches\n\n")
	writeRecent(&sb, name, 20)
	sb.WriteString("[Back to the arena](" + link("") + ")\n")
	return sb.String()
}

func renderMatch(m *Match, turn int) string {
	g := &m.Game
	played := g.Turn
	if turn < 0 || turn > played {
		turn = played
	}
	var sb strings.Builder
	sb.WriteString(ufmt.Sprintf("# Match #%d: %s vs %s\n\n", m.ID, m.Bot(0), m.Bot(1)))
	sb.WriteString("**" + m.Summary() + "**\n\n")
	switch {
	case !m.Rated:
		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))
	case m.Status == Finished && m.Winner >= 0:
		sb.WriteString(ufmt.Sprintf("Rating change: %s %s, %s %s\n\n", m.Bot(0), signed(m.Delta), m.Bot(1), signed(-m.Delta)))
	}
	writeActions(&sb, m)

	snap := g.At(turn)
	sb.WriteString(ufmt.Sprintf("## After turn %d of %d\n\n", turn, bot.Turns))
	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]))
	sb.WriteString("```\n" + drawBoard(snap.Pos, snap.Coins) + "```\n\n")

	nav := []string{}
	if turn > 0 {
		nav = append(nav, ufmt.Sprintf("[« start](%s)", link(ufmt.Sprintf("match/%d/0", m.ID))))
		nav = append(nav, ufmt.Sprintf("[‹ prev](%s)", link(ufmt.Sprintf("match/%d/%d", m.ID, turn-1))))
	}
	if turn < played {
		nav = append(nav, ufmt.Sprintf("[next ›](%s)", link(ufmt.Sprintf("match/%d/%d", m.ID, turn+1))))
		nav = append(nav, ufmt.Sprintf("[end »](%s)", link(ufmt.Sprintf("match/%d/%d", m.ID, played))))
	}
	if len(nav) > 0 {
		sb.WriteString(strings.Join(nav, " · ") + "\n\n")
	}
	if turn > 0 {
		sb.WriteString(ufmt.Sprintf("Turn %d: %s **%s**%s, %s **%s**%s\n\n",
			turn, m.Bot(0), snap.Act[0].String(), eventNote(snap.Events, 0), m.Bot(1), snap.Act[1].String(), eventNote(snap.Events, 1)))
	}

	writeMoments(&sb, m)
	sb.WriteString(ufmt.Sprintf("Bots: [%s](%s) · [%s](%s) · [Back to the arena](%s)\n",
		m.Bot(0), link("bot/"+m.Bot(0)), m.Bot(1), link("bot/"+m.Bot(1)), link("")))
	return sb.String()
}

// writeActions shows the buttons that move an unfinished match along.
func writeActions(sb *strings.Builder, m *Match) {
	id := strconv.Itoa(m.ID)
	switch m.Status {
	case Pending:
		sb.WriteString(ufmt.Sprintf("Not played yet: [Play it](%s). If a bot keeps making it fail, [switch to step mode](%s).\n\n",
			tx.Call("Play", "id", id), tx.Call("StartStepMode", "id", id)))
	case Stepping:
		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)",
			m.Bot(m.Waiting), m.Deadline, height(), tx.Call("SubmitMove", "id", id), tx.Call("Play", "id", id)))
		if height() > m.Deadline {
			sb.WriteString(ufmt.Sprintf(" · [Claim the forfeit](%s)", tx.Call("ClaimForfeit", "id", id)))
		}
		sb.WriteString("\n\n")
	}
}

// writeMoments lists the turns where coins changed hands.
func writeMoments(sb *strings.Builder, m *Match) {
	var lines []string
	for i, ev := range m.Game.Timeline() {
		for side := 0; side < 2; side++ {
			what := ""
			switch {
			case ev.Stole[side]:
				what = "stole a coin from"
			case ev.Parried[side]:
				what = "parried and took a coin from"
			}
			if what != "" {
				lines = append(lines, ufmt.Sprintf("- [Turn %d](%s): %s %s %s", i+1,
					link(ufmt.Sprintf("match/%d/%d", m.ID, i+1)), m.Bot(side), what, m.Bot(1-side)))
			}
		}
	}
	if len(lines) == 0 {
		return
	}
	sb.WriteString("## Key moments\n\n")
	if len(lines) > 12 {
		more := len(lines) - 12
		lines = append(lines[:12], ufmt.Sprintf("- …and %d more", more))
	}
	sb.WriteString(strings.Join(lines, "\n") + "\n\n")
}

func signed(n int) string {
	if n > 0 {
		return "+" + strconv.Itoa(n)
	}
	return strconv.Itoa(n)
}

func eventNote(ev game.Events, side int) string {
	switch {
	case ev.Stole[side]:
		return " (stole a coin)"
	case ev.Parried[side]:
		return " (parried and took a coin)"
	}
	return ""
}

func drawBoard(pos [2]bot.Pos, coins []bot.Pos) string {
	var sb strings.Builder
	for y := 0; y < bot.Size; y++ {
		for x := 0; x < bot.Size; x++ {
			p := bot.Pos{x, y}
			cell := "·"
			for _, c := range coins {
				if c == p {
					cell = "$"
				}
			}
			switch p {
			case pos[0]:
				cell = "A"
			case pos[1]:
				cell = "B"
			}
			sb.WriteString(cell)
			if x < bot.Size-1 {
				sb.WriteString(" ")
			}
		}
		sb.WriteString("\n")
	}
	return sb.String()
}