Playground
api.gno
package arena
import (
"strconv"
"strings"
"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/game"
)
// Read API for apps and tools. Every function returns JSON and changes
// nothing, so it can be called for free with a vm/qeval query, e.g.
//
// gnokey query vm/qeval -data 'gno.land/r/<ns>/arena.BotsJSON()'
func jsonString(s string) string {
var sb strings.Builder
sb.WriteByte('"')
for _, c := range s {
switch {
case c == '"':
sb.WriteString(`\"`)
case c == '\\':
sb.WriteString(`\\`)
case c < 0x20:
sb.WriteString(`\u00`)
sb.WriteByte("0123456789abcdef"[c>>4])
sb.WriteByte("0123456789abcdef"[c&0xf])
default:
sb.WriteRune(c)
}
}
sb.WriteByte('"')
return sb.String()
}
type jsonObj struct{ parts []string }
func (o *jsonObj) str(k, v string) *jsonObj {
o.parts = append(o.parts, jsonString(k)+":"+jsonString(v))
return o
}
func (o *jsonObj) num(k string, v int) *jsonObj {
o.parts = append(o.parts, jsonString(k)+":"+strconv.Itoa(v))
return o
}
func (o *jsonObj) num64(k string, v int64) *jsonObj {
o.parts = append(o.parts, jsonString(k)+":"+strconv.FormatInt(v, 10))
return o
}
func (o *jsonObj) flag(k string, v bool) *jsonObj {
o.parts = append(o.parts, jsonString(k)+":"+strconv.FormatBool(v))
return o
}
func (o *jsonObj) raw(k, v string) *jsonObj {
o.parts = append(o.parts, jsonString(k)+":"+v)
return o
}
func (o *jsonObj) String() string { return "{" + strings.Join(o.parts, ",") + "}" }
func jsonArray(items []string) string { return "[" + strings.Join(items, ",") + "]" }
func posJSON(p bot.Pos) string { return "[" + strconv.Itoa(p.X) + "," + strconv.Itoa(p.Y) + "]" }
func botJSON(b *Bot) string {
o := &jsonObj{}
o.str("name", b.Name).str("realm", b.Realm).str("owner", b.Owner.String()).
str("kind", b.kind()).str("description", b.Description).
num("version", b.Version).flag("retired", b.Retired).
num("rating", b.Rating).
num("seasonWins", b.SeasonWins).num("seasonLosses", b.SeasonLosses).num("seasonDraws", b.SeasonDraws).
num("wins", b.Wins).num("losses", b.Losses).num("draws", b.Draws).num("forfeits", b.Forfeits).
num64("registered", b.Registered)
return o.String()
}
// ArenaJSON returns counts, the current season and the block height.
func ArenaJSON() string {
n, end := SeasonInfo()
o := &jsonObj{}
o.num("bots", bots.Size()).num("matches", lastID).num("tournaments", lastTID).
num("season", n).num64("seasonStart", seasonStart).num64("seasonEnds", end).
num64("height", height()).num("seasonLength", SeasonLength).
num("moveTimeout", MoveTimeout).num("ratedCooldown", RatedCooldown).
num("boardSize", bot.Size).num("turns", bot.Turns)
return o.String()
}
// BotsJSON returns every bot, ranked like the leaderboard.
func BotsJSON() string {
var items []string
for _, b := range leaderboard() {
items = append(items, botJSON(b))
}
return jsonArray(items)
}
// BotJSON returns one bot, with its earlier versions.
func BotJSON(name string) string {
b := mustBot(name)
var prev []string
for _, r := range b.PreviousVersions() {
prev = append(prev, jsonString(r))
}
return strings.TrimSuffix(botJSON(b), "}") + `,"previousVersions":` + jsonArray(prev) + "}"
}
func matchSummaryJSON(m *Match) string {
o := &jsonObj{}
o.num("id", m.ID).str("a", m.BotA).str("b", m.BotB).
str("status", m.Status.String()).num("turn", m.Game.Turn).
num("goldA", m.Game.GoldA).num("goldB", m.Game.GoldB).
num("winner", m.Winner).flag("forfeit", m.Forfeit).str("reason", m.Reason).
flag("rated", m.Rated).num("delta", m.Delta).
num("season", m.Season).num("tournament", m.Tournament).
num64("created", m.Created).num64("settled", m.Settled).
str("summary", m.Summary())
if m.Status == Stepping {
o.str("waitingFor", m.Bot(m.Waiting)).num64("deadline", m.Deadline)
}
return o.String()
}
// MatchesJSON returns up to limit matches, newest first, optionally only
// those of one bot (looking at no more than the last 500).
func MatchesJSON(botName string, limit int) string {
if limit <= 0 || limit > 100 {
limit = 20
}
var items []string
eachRecent(500, func(m *Match) bool {
if botName != "" && m.BotA != botName && m.BotB != botName {
return false
}
items = append(items, matchSummaryJSON(m))
return len(items) >= limit
})
return jsonArray(items)
}
// MatchJSON returns a match with every turn, for replays: positions, gold
// and coins after each turn, both actions and what happened.
func MatchJSON(id int) string {
m := mustMatch(id)
r := game.New(m.Game.Seed)
frames := []string{frameJSON(r, [2]bot.Action{}, game.Events{})}
g := &m.Game
for i := 0; i < g.Turn; i++ {
acts := [2]bot.Action{bot.Action(g.Moves[2*i]), bot.Action(g.Moves[2*i+1])}
ev := r.Step(acts[0], acts[1])
frames = append(frames, frameJSON(r, acts, ev))
}
return strings.TrimSuffix(matchSummaryJSON(m), "}") + `,"seed":` + strconv.Itoa(g.Seed) + `,"frames":` + jsonArray(frames) + "}"
}
func frameJSON(g *game.Game, acts [2]bot.Action, ev game.Events) string {
var coins []string
for _, c := range g.CoinList() {
coins = append(coins, posJSON(c))
}
o := &jsonObj{}
o.num("turn", g.Turn).
raw("pos", "["+posJSON(g.Pos(0))+","+posJSON(g.Pos(1))+"]").
raw("gold", "["+strconv.Itoa(g.GoldA)+","+strconv.Itoa(g.GoldB)+"]").
raw("actions", "["+jsonString(acts[0].String())+","+jsonString(acts[1].String())+"]").
raw("stole", "["+strconv.FormatBool(ev.Stole[0])+","+strconv.FormatBool(ev.Stole[1])+"]").
raw("parried", "["+strconv.FormatBool(ev.Parried[0])+","+strconv.FormatBool(ev.Parried[1])+"]").
num("spawned", ev.Spawned).
raw("coins", jsonArray(coins))
return o.String()
}
func tournamentJSON(t *Tournament, full bool) string {
o := &jsonObj{}
var entrants []string
for _, e := range t.Entrants {
entrants = append(entrants, jsonString(e))
}
o.num("id", t.ID).str("name", t.Name).str("creator", t.Creator.String()).
num64("created", t.Created).num("capacity", t.Capacity).
str("status", t.Status.String()).str("winner", t.Winner).
raw("entrants", jsonArray(entrants))
if !full {
return o.String()
}
var table []string
for _, r := range t.Standings() {
row := &jsonObj{}
row.str("bot", r.Bot).num("played", r.Played).num("wins", r.Wins).num("draws", r.Draws).
num("losses", r.Losses).num("goldFor", r.GoldFor).num("goldAgainst", r.GoldAgainst).num("points", r.Points)
table = append(table, row.String())
}
var sched []string
for i, p := range t.Pairs {
ab := strings.Split(p, "|")
row := &jsonObj{}
row.str("a", ab[0]).str("b", ab[1]).num("match", t.MatchIDs[i])
sched = append(sched, row.String())
}
o.raw("table", jsonArray(table)).raw("schedule", jsonArray(sched))
return o.String()
}
// TournamentsJSON returns every tournament, newest first.
func TournamentsJSON() string {
var items []string
tournaments.ReverseIterate("", "", func(_ string, v any) bool {
items = append(items, tournamentJSON(v.(*Tournament), false))
return false
})
return jsonArray(items)
}
// TournamentJSON returns one tournament with its table and schedule.
func TournamentJSON(id int) string { return tournamentJSON(mustTournament(id), true) }
// SeasonsJSON returns the top 10 of every finished season, newest first.
func SeasonsJSON() string {
var items []string
for n := season - 1; n >= 1; n-- {
var rows []string
for _, s := range PastSeason(n) {
row := &jsonObj{}
row.str("bot", s.Bot).num("rating", s.Rating).num("wins", s.Wins).num("losses", s.Losses).num("draws", s.Draws)
rows = append(rows, row.String())
}
o := &jsonObj{}
o.num("season", n).raw("top", jsonArray(rows))
items = append(items, o.String())
}
return jsonArray(items)
}
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
// season record, reset when a new season starts (see season.gno)
SeasonWins, SeasonLosses, SeasonDraws int
// owner tools (see owner.gno)
Description string
Retired bool
Version int // 1 at registration, +1 per upgrade
History string // "realm@block," of previous versions
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()
reserveRealmSlot(realmPath)
b.Name = name
b.Realm = realmPath
b.Owner = currentOrigin()
b.Registered = height()
b.Rating = startRating
b.Version = 1
bots.Set(name, b)
emit("BotRegistered", "name", name, "realm", realmPath)
}
// reserveRealmSlot counts one more bot for realmPath, up to maxBotsPerRealm.
func reserveRealmSlot(realmPath string) {
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")
}
botsPerRealm.Set(realmPath, count+1)
}
func currentOrigin() address { return unsafe.OriginCaller() }
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, Description string
Owner address
Rating, Wins, Losses, Draws, Forfeits, Played int
Retired bool
Version 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{
Name: b.Name, Realm: b.Realm, Description: b.Description, Owner: b.Owner,
Rating: b.Rating, Wins: b.Wins, Losses: b.Losses, Draws: b.Draws, Forfeits: b.Forfeits,
Played: b.Played(), Retired: b.Retired, Version: b.Version,
}, 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
codecV2 = "2"
)
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{
codecV2,
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),
itoa(m.Season), itoa(m.Tournament),
}, sep)
}
func decode(id int, s string) *Match {
f := strings.Split(s, sep)
if len(f) != 25 || f[0] != codecV2 {
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),
Season: n(23),
Tournament: n(24),
}
}
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))
if m.Status == Finished && m.Tournament != 0 {
mustTournament(m.Tournament).checkDone()
}
}
// 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/v2" gno = "0.9" [addpkg] creator = "g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28" height = 1454286 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
Season int // season the match was created in
Tournament int // tournament id, 0 for a normal challenge
// 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")
}
for _, name := range []string{a, b} {
if mustBot(name).Retired {
panic(name + " is retired")
}
}
rollSeason()
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),
Season: season,
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() {
rollSeason()
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++
a.SeasonWins++
b.Losses++
b.SeasonLosses++
if m.Forfeit {
b.Forfeits++
}
case 1:
b.Wins++
b.SeasonWins++
a.Losses++
a.SeasonLosses++
if m.Forfeit {
a.Forfeits++
}
default:
a.Draws++
a.SeasonDraws++
b.Draws++
b.SeasonDraws++
}
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 }
owner.gno
package arena
import (
"strconv"
"strings"
"gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
)
// Owner tools. A bot's owner is the account that sent the transaction which
// registered it. Only the owner can describe, retire or upgrade a bot.
const maxDescription = 200
func mustOwn(cur realm, name string) *Bot {
b := mustBot(name)
if cur.Previous().Address() != b.Owner {
panic("only the owner of " + name + " can do this")
}
return b
}
// cleanText keeps a description on one line and drops characters that would
// turn it into markdown links, images, tables or HTML on the bot's page.
func cleanText(s string) string {
var sb strings.Builder
for _, c := range s {
switch {
case c == '\n' || c == '\r' || c == '\t':
sb.WriteRune(' ')
case strings.ContainsRune("<>[]()|*_`#!\\", c):
// dropped
default:
sb.WriteRune(c)
}
}
out := strings.TrimSpace(sb.String())
if len(out) > maxDescription {
out = out[:maxDescription]
}
return out
}
// SetDescription sets the one-line description shown on the bot's page.
func SetDescription(cur realm, name, text string) {
b := mustOwn(cur, name)
b.Description = cleanText(text)
emit("BotDescribed", "name", name)
}
// Retire takes a bot off the leaderboard and stops new challenges against
// it. Its history stays. Matches already created can still be finished.
func Retire(cur realm, name string) {
b := mustOwn(cur, name)
if b.Retired {
panic(name + " is already retired")
}
b.Retired = true
emit("BotRetired", "name", name)
}
// Unretire brings a retired bot back.
func Unretire(cur realm, name string) {
b := mustOwn(cur, name)
if !b.Retired {
panic(name + " is not retired")
}
b.Retired = false
emit("BotUnretired", "name", name)
}
// UpgradeBot points an existing bot at new code, keeping its name, rating
// and record. Call it from the new bot realm's init, sent by the bot's owner:
//
// func init(cur realm) { arena.UpgradeBot(cross(cur), "my-bot", &myBotV2{}) }
func UpgradeBot(cur realm, name string, b bot.Bot) {
if b == nil {
panic("bot is nil")
}
upgrade(cur, name, b, nil)
}
// UpgradeStrategy is UpgradeBot for a bot written as a plain function.
func UpgradeStrategy(cur realm, name string, s bot.Strategy) {
if s == nil {
panic("strategy is nil")
}
upgrade(cur, name, nil, s)
}
func upgrade(cur realm, name string, impl bot.Bot, fn bot.Strategy) {
caller := cur.Previous()
if !caller.IsCode() || caller.IsEphemeral() {
panic("upgrades must come from a deployed realm, so the new source is public")
}
b := mustBot(name)
if currentOrigin() != b.Owner {
panic("only the owner of " + name + " can upgrade it")
}
newRealm := caller.PkgPath()
if newRealm == b.Realm {
panic("the new version must live in a new realm")
}
reserveRealmSlot(newRealm)
b.History = appendHistory(b.History, b.Realm)
b.Realm = newRealm
b.Version++
b.impl, b.fn = impl, fn
emit("BotUpgraded", "name", name, "realm", newRealm, "version", strconv.Itoa(b.Version))
}
// appendHistory adds a realm to a bot's "realm@block," history.
func appendHistory(h, realmPath string) string {
return h + realmPath + "@" + strconv.FormatInt(height(), 10) + ","
}
// PreviousVersions lists the realms a bot used before its current one, oldest
// first.
func (b *Bot) PreviousVersions() []string {
var out []string
for _, e := range strings.Split(b.History, ",") {
if at := strings.LastIndex(e, "@"); at > 0 {
out = append(out, e[:at])
}
}
return out
}
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/v2"
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
// "tournaments" all tournaments
// "tournament/<id>" a tournament's table, schedule and actions
// "seasons" champions of past seasons
func Render(path string) string {
parts := strings.Split(strings.Trim(path, "/"), "/")
switch {
case len(parts) == 1 && parts[0] == "tournaments":
return renderTournaments()
case len(parts) == 1 && parts[0] == "seasons":
return renderSeasons()
case len(parts) == 2 && parts[0] == "tournament":
id, err := strconv.Atoi(parts[1])
if err != nil || tournaments.Get(key(id)) == nil {
return "# Tournament not found\n\n[Back to the arena](" + link("") + ")\n"
}
return renderTournament(mustTournament(id))
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** · **%d tournaments** · [Start a fight](%s)\n\n", bots.Size(), lastID, lastTID, fightLink("", "")))
sb.WriteString(ufmt.Sprintf("## Season %d leaderboard\n\n", season))
sb.WriteString(seasonLine() + "\n\n")
ranked := activeLeaderboard()
if len(ranked) == 0 {
sb.WriteString("No bots yet.\n\n")
} else {
sb.WriteString("| # | Bot | Elo | Season 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.SeasonWins, b.SeasonLosses, b.SeasonDraws, sourceLink(b.Realm), fightLink("", b.Name)))
}
sb.WriteString("\n")
}
sb.WriteString("## Tournaments\n\n")
writeTournamentList(&sb, 5)
sb.WriteString(ufmt.Sprintf("[Open a tournament](%s) · [All tournaments](%s)\n\n", tx.Call("CreateTournament", "name", "", "capacity", "8"), link("tournaments")))
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/v2), 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))
if b.Description != "" {
sb.WriteString("> " + b.Description + "\n\n")
}
if b.Retired {
sb.WriteString("**Retired:** this bot no longer takes new challenges.\n\n")
} else {
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("- **Season %d:** Elo %d, %d-%d-%d\n", season, b.Rating, b.SeasonWins, b.SeasonLosses, b.SeasonDraws))
sb.WriteString(ufmt.Sprintf("- **All time:** %d wins, %d losses (%d by forfeit), %d draws\n", b.Wins, b.Losses, b.Forfeits, b.Draws))
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))
if prev := b.PreviousVersions(); len(prev) > 0 {
var links []string
for i, r := range prev {
links = append(links, ufmt.Sprintf("[v%d](%s)", i+1, sourceLink(r)))
}
sb.WriteString("- **Earlier versions:** " + strings.Join(links, " · ") + "\n")
}
sb.WriteString("\n## Matches\n\n")
writeRecent(&sb, name, 20)
sb.WriteString(ufmt.Sprintf("Owner actions: [describe](%s) · ", tx.Call("SetDescription", "name", b.Name, "text", "")))
if b.Retired {
sb.WriteString(ufmt.Sprintf("[unretire](%s) · ", tx.Call("Unretire", "name", b.Name)))
} else {
sb.WriteString(ufmt.Sprintf("[retire](%s) · ", tx.Call("Retire", "name", b.Name)))
}
sb.WriteString("[enter a tournament](" + link("tournaments") + ")\n\n")
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")
if m.Tournament != 0 {
sb.WriteString(ufmt.Sprintf("Part of [tournament #%d](%s).\n\n", m.Tournament, link("tournament/"+strconv.Itoa(m.Tournament))))
}
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()
}
render_more.gno
package arena
import (
"strconv"
"strings"
"gno.land/p/nt/ufmt/v0"
)
// blockSeconds is Onyx's approximate block time, for "about N days" hints.
const blockSeconds = 3.6
// seasonLine describes the current season's timing.
func seasonLine() string {
if seasonStart == 0 {
return ufmt.Sprintf("Season %d starts with the first match. [Past seasons](%s)", season, link("seasons"))
}
end := seasonStart + SeasonLength
left := end - height()
if left < 0 {
left = 0
}
days := int(float64(left) * blockSeconds / 86400)
return ufmt.Sprintf("Ends at block %d (about %d days). Ratings reset each season; the top 10 is kept. [Past seasons](%s)", end, days, link("seasons"))
}
// activeLeaderboard is the leaderboard without retired bots.
func activeLeaderboard() []*Bot {
var out []*Bot
for _, b := range leaderboard() {
if !b.Retired {
out = append(out, b)
}
}
return out
}
func writeTournamentList(sb *strings.Builder, limit int) {
if lastTID == 0 {
sb.WriteString("No tournaments yet.\n\n")
return
}
n := 0
tournaments.ReverseIterate("", "", func(_ string, v any) bool {
t := v.(*Tournament)
extra := ""
if t.Status == Done && t.Winner != "" {
extra = ", won by " + t.Winner
}
sb.WriteString(ufmt.Sprintf("- [#%d %s](%s): %d/%d bots, %s%s\n",
t.ID, t.Name, link("tournament/"+strconv.Itoa(t.ID)), len(t.Entrants), t.Capacity, t.Status.String(), extra))
n++
return limit > 0 && n >= limit
})
sb.WriteString("\n")
}
func renderTournaments() string {
var sb strings.Builder
sb.WriteString("# Tournaments\n\n")
sb.WriteString("Round-robins of 2 to 8 bots: everyone plays everyone once. 3 points for a win, 1 for a draw; ties go to gold difference.\n\n")
sb.WriteString(ufmt.Sprintf("[Open a tournament](%s)\n\n", tx.Call("CreateTournament", "name", "", "capacity", "8")))
writeTournamentList(&sb, 0)
sb.WriteString("[Back to the arena](" + link("") + ")\n")
return sb.String()
}
func renderTournament(t *Tournament) string {
var sb strings.Builder
id := strconv.Itoa(t.ID)
sb.WriteString(ufmt.Sprintf("# Tournament #%d: %s\n\n", t.ID, t.Name))
sb.WriteString(ufmt.Sprintf("**%s** · %d/%d bots · created by `%s`\n\n", t.Status.String(), len(t.Entrants), t.Capacity, t.Creator.String()))
if t.Status == Done && t.Winner != "" {
sb.WriteString(ufmt.Sprintf("**Winner: [%s](%s)**\n\n", t.Winner, link("bot/"+t.Winner)))
}
switch t.Status {
case Open:
sb.WriteString(ufmt.Sprintf("[Enter your bot](%s) · [Start (creator only)](%s)\n\n",
tx.Call("JoinTournament", "id", id, "botName", ""), tx.Call("StartTournament", "id", id)))
case Running:
idx, inProgress := t.next()
switch {
case inProgress:
mid := t.MatchIDs[idx]
sb.WriteString(ufmt.Sprintf("Match [#%d](%s) is being played: finish it from its page.\n\n", mid, matchLink(mid)))
case idx < len(t.Pairs):
sb.WriteString(ufmt.Sprintf("Next: %s. [Play it](%s) · if a bot keeps that failing, [create it](%s) and use step mode from its page.\n\n",
strings.Replace(t.Pairs[idx], "|", " vs ", 1), tx.Call("PlayTournament", "id", id), tx.Call("NextTournamentMatch", "id", id)))
default:
sb.WriteString(ufmt.Sprintf("All matches are played: [close the tournament](%s).\n\n", tx.Call("CloseTournament", "id", id)))
}
}
if len(t.Entrants) > 0 {
sb.WriteString("## Table\n\n| # | Bot | P | W | D | L | Gold | Pts |\n|---|---|---|---|---|---|---|---|\n")
for i, r := range t.Standings() {
sb.WriteString(ufmt.Sprintf("| %d | [%s](%s) | %d | %d | %d | %d | %d:%d | **%d** |\n",
i+1, r.Bot, link("bot/"+r.Bot), r.Played, r.Wins, r.Draws, r.Losses, r.GoldFor, r.GoldAgainst, r.Points))
}
sb.WriteString("\n")
}
if len(t.Pairs) > 0 {
sb.WriteString("## Schedule\n\n")
for i, pair := range t.Pairs {
vs := strings.Replace(pair, "|", " vs ", 1)
if mid := t.MatchIDs[i]; mid != 0 {
sb.WriteString(ufmt.Sprintf("%d. [%s](%s)\n", i+1, mustMatch(mid).Summary(), matchLink(mid)))
} else {
sb.WriteString(ufmt.Sprintf("%d. %s\n", i+1, vs))
}
}
sb.WriteString("\n")
}
sb.WriteString("[All tournaments](" + link("tournaments") + ") · [Back to the arena](" + link("") + ")\n")
return sb.String()
}
func renderSeasons() string {
var sb strings.Builder
sb.WriteString("# Seasons\n\n")
sb.WriteString(ufmt.Sprintf("Season %d is running. %s\n\n", season, seasonLine()))
if season == 1 {
sb.WriteString("No finished seasons yet.\n\n")
}
for n := season - 1; n >= 1; n-- {
sb.WriteString(ufmt.Sprintf("## Season %d\n\n", n))
top := PastSeason(n)
if len(top) == 0 {
sb.WriteString("Nobody played.\n\n")
continue
}
sb.WriteString("| # | Bot | Elo | W-L-D |\n|---|---|---|---|\n")
for i, s := range top {
sb.WriteString(ufmt.Sprintf("| %d | [%s](%s) | %d | %d-%d-%d |\n", i+1, s.Bot, link("bot/"+s.Bot), s.Rating, s.Wins, s.Losses, s.Draws))
}
sb.WriteString("\n")
}
sb.WriteString("[Back to the arena](" + link("") + ")\n")
return sb.String()
}
season.gno
package arena
import (
"strconv"
"strings"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/ufmt/v0"
)
// Seasons. Ratings and season records reset every SeasonLength blocks, and
// each finished season's top 10 is kept. The switch happens lazily: the first
// match or challenge after a season's end closes it, so no scheduler is
// needed. All-time records (Wins, Losses, Draws) never reset.
// SeasonLength is about 30 days at Onyx's ~3.6 s blocks.
const SeasonLength = 720000
var (
season = 1
seasonStart = int64(0) // set on the first activity
pastSeasons = avl.NewTree() // padded season number -> "name:rating:w-l-d," top 10
seasonTop = 10
)
// SeasonInfo reports the current season number and the block it ends at.
func SeasonInfo() (number int, endsAt int64) {
return season, seasonStart + SeasonLength
}
// rollSeason closes the current season if it is over. Call it before any
// state change that touches ratings.
func rollSeason() {
now := height()
if seasonStart == 0 {
seasonStart = now
return
}
for now >= seasonStart+SeasonLength {
closeSeason()
seasonStart += SeasonLength
}
}
func closeSeason() {
var sb strings.Builder
for i, b := range leaderboard() {
if i == seasonTop {
break
}
if b.SeasonWins+b.SeasonLosses+b.SeasonDraws == 0 {
continue // didn't play this season
}
sb.WriteString(ufmt.Sprintf("%s:%d:%d-%d-%d,", b.Name, b.Rating, b.SeasonWins, b.SeasonLosses, b.SeasonDraws))
}
pastSeasons.Set(key(season), sb.String())
emit("SeasonEnded", "season", strconv.Itoa(season))
bots.Iterate("", "", func(_ string, v any) bool {
b := v.(*Bot)
b.Rating = startRating
b.SeasonWins, b.SeasonLosses, b.SeasonDraws = 0, 0, 0
b.recentRated = ""
return false
})
season++
}
// SeasonStanding is one line of a finished season's top 10.
type SeasonStanding struct {
Bot string
Rating int
Wins, Losses, Draws int
}
// PastSeason returns the top 10 of a finished season.
func PastSeason(number int) []SeasonStanding {
v := pastSeasons.Get(key(number))
if v == nil {
return nil
}
var out []SeasonStanding
for _, e := range strings.Split(v.(string), ",") {
f := strings.Split(e, ":")
if len(f) != 3 {
continue
}
r, _ := strconv.Atoi(f[1])
wld := strings.Split(f[2], "-")
if len(wld) != 3 {
continue
}
w, _ := strconv.Atoi(wld[0])
l, _ := strconv.Atoi(wld[1])
d, _ := strconv.Atoi(wld[2])
out = append(out, SeasonStanding{f[0], r, w, l, d})
}
return out
}
tournament.gno
package arena
import (
"strconv"
"strings"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/ufmt/v0"
)
// Tournaments. Anyone can open a round-robin tournament; bot owners enter
// their bots; the creator starts it. Matches are then created one at a time
// and are ordinary matches, so a bot that crashes in a tournament game is
// handled exactly like anywhere else: step mode, then a forfeit. A
// tournament can therefore never get stuck on a broken bot.
//
// Scoring: 3 points for a win, 1 for a draw. Ties are broken by gold
// difference, then gold scored, then name.
const (
minEntrants = 2
maxEntrants = 8
)
// TournamentStatus of a tournament.
type TournamentStatus int
const (
Open TournamentStatus = iota
Running
Done
)
func (s TournamentStatus) String() string {
switch s {
case Open:
return "open for entries"
case Running:
return "running"
}
return "finished"
}
// Tournament is a round-robin between up to maxEntrants bots.
type Tournament struct {
ID int
Name string
Creator address
Created int64
Capacity int
Status TournamentStatus
Entrants []string
Pairs []string // "a|b", in play order, fixed at start
MatchIDs []int // match id for each pair once created
Winner string
}
var (
tournaments = avl.NewTree() // padded id -> *Tournament
lastTID = 0
)
func mustTournament(id int) *Tournament {
v := tournaments.Get(key(id))
if v == nil {
panic("unknown tournament: " + strconv.Itoa(id))
}
return v.(*Tournament)
}
// CreateTournament opens a round-robin for up to capacity bots (2 to 8).
func CreateTournament(cur realm, name string, capacity int) int {
name = cleanText(name)
if len(name) < 3 || len(name) > 48 {
panic("tournament names must be 3 to 48 characters")
}
if capacity < minEntrants || capacity > maxEntrants {
panic(ufmt.Sprintf("capacity must be %d to %d", minEntrants, maxEntrants))
}
lastTID++
t := &Tournament{
ID: lastTID, Name: name, Creator: cur.Previous().Address(),
Created: height(), Capacity: capacity, Status: Open,
}
tournaments.Set(key(t.ID), t)
emit("TournamentCreated", "id", strconv.Itoa(t.ID), "name", name)
return t.ID
}
// JoinTournament enters a bot you own into an open tournament.
func JoinTournament(cur realm, id int, botName string) {
t := mustTournament(id)
b := mustOwn(cur, botName)
if t.Status != Open {
panic("tournament is not open for entries")
}
if b.Retired {
panic(botName + " is retired")
}
if len(t.Entrants) >= t.Capacity {
panic("tournament is full")
}
for _, e := range t.Entrants {
if e == botName {
panic(botName + " is already entered")
}
}
t.Entrants = append(t.Entrants, botName)
emit("TournamentJoined", "id", strconv.Itoa(id), "bot", botName)
}
// StartTournament closes entries and fixes the schedule. Only the creator
// can start it.
func StartTournament(cur realm, id int) {
t := mustTournament(id)
if cur.Previous().Address() != t.Creator {
panic("only the creator can start this tournament")
}
if t.Status != Open {
panic("tournament already started")
}
if len(t.Entrants) < minEntrants {
panic("a tournament needs at least 2 bots")
}
t.Pairs = roundRobin(t.Entrants)
t.MatchIDs = make([]int, len(t.Pairs))
t.Status = Running
emit("TournamentStarted", "id", strconv.Itoa(id), "matches", strconv.Itoa(len(t.Pairs)))
}
// roundRobin schedules every pair once, round by round (circle method), so
// no bot plays twice in a row more than it must. Sides alternate by round.
func roundRobin(entrants []string) []string {
ps := append([]string{}, entrants...)
if len(ps)%2 == 1 {
ps = append(ps, "") // bye
}
n := len(ps)
var out []string
for round := 0; round < n-1; round++ {
for i := 0; i < n/2; i++ {
a, b := ps[i], ps[n-1-i]
if a == "" || b == "" {
continue
}
if round%2 == 1 {
a, b = b, a
}
out = append(out, a+"|"+b)
}
// rotate everyone but the first
last := ps[n-1]
copy(ps[2:], ps[1:n-1])
ps[1] = last
}
return out
}
// next returns the index of the first pair without a finished match, and
// whether that pair already has a match in progress.
func (t *Tournament) next() (idx int, inProgress bool) {
for i, id := range t.MatchIDs {
if id == 0 {
return i, false
}
if mustMatch(id).Status != Finished {
return i, true
}
}
return len(t.MatchIDs), false
}
// NextTournamentMatch creates the tournament's next match and returns its
// id. Play it with Play, or step mode if a bot keeps it from finishing.
// Anyone may call it.
func NextTournamentMatch(cur realm, id int) int {
t := mustTournament(id)
m := t.createNext(cur)
m.save()
return m.ID
}
// PlayTournament creates the next match and plays it in one transaction. If
// a bot makes it fail, nothing is recorded: use NextTournamentMatch, then
// Play or step mode. Anyone may call it.
func PlayTournament(cur realm, id int) string {
t := mustTournament(id)
m := t.createNext(cur)
m.play()
m.save()
t.checkDone()
return m.Summary()
}
func (t *Tournament) createNext(cur realm) *Match {
if t.Status != Running {
panic("tournament is " + t.Status.String())
}
idx, inProgress := t.next()
if inProgress {
panic(ufmt.Sprintf("match #%d is still being played: finish it with Play or step mode", t.MatchIDs[idx]))
}
if idx == len(t.Pairs) {
t.checkDone()
panic("all tournament matches are played")
}
ab := strings.Split(t.Pairs[idx], "|")
m := newMatch(cur, ab[0], ab[1])
m.Tournament = t.ID
t.MatchIDs[idx] = m.ID
return m
}
// checkDone finishes the tournament once every match is settled.
func (t *Tournament) checkDone() {
if t.Status != Running {
return
}
if idx, _ := t.next(); idx < len(t.Pairs) {
return
}
t.Status = Done
if st := t.Standings(); len(st) > 0 {
t.Winner = st[0].Bot
}
emit("TournamentFinished", "id", strconv.Itoa(t.ID), "winner", t.Winner)
}
// CloseTournament marks a tournament finished once all its matches are
// settled (matches finished through step mode don't do it themselves).
// Anyone may call it.
func CloseTournament(cur realm, id int) {
t := mustTournament(id)
t.checkDone()
if t.Status != Done {
panic("tournament still has matches to play")
}
}
// Standing is one bot's line in a tournament table.
type Standing struct {
Bot string
Played, Wins, Draws, Losses int
GoldFor, GoldAgainst int
Points int
}
// Standings returns the tournament table, best first.
func (t *Tournament) Standings() []Standing {
rows := map[string]*Standing{}
for _, e := range t.Entrants {
rows[e] = &Standing{Bot: e}
}
for _, id := range t.MatchIDs {
if id == 0 {
continue
}
m := mustMatch(id)
if m.Status != Finished {
continue
}
for side := 0; side < 2; side++ {
r := rows[m.Bot(side)]
r.Played++
r.GoldFor += m.Game.Gold(side)
r.GoldAgainst += m.Game.Gold(1 - side)
switch m.Winner {
case side:
r.Wins++
r.Points += 3
case -1:
r.Draws++
r.Points++
default:
r.Losses++
}
}
}
out := make([]Standing, 0, len(rows))
for _, e := range t.Entrants {
out = append(out, *rows[e])
}
for i := 1; i < len(out); i++ {
for j := i; j > 0 && aheadOf(out[j], out[j-1]); j-- {
out[j], out[j-1] = out[j-1], out[j]
}
}
return out
}
func aheadOf(a, b Standing) bool {
if a.Points != b.Points {
return a.Points > b.Points
}
if da, db := a.GoldFor-a.GoldAgainst, b.GoldFor-b.GoldAgainst; da != db {
return da > db
}
if a.GoldFor != b.GoldFor {
return a.GoldFor > b.GoldFor
}
return a.Bot < b.Bot
}
// TournamentCount is the number of tournaments ever created.
func TournamentCount() int { return lastTID }
// TournamentNext returns the next pairing still to be created, if any.
func TournamentNext(id int) (a, b string, ok bool) {
t := mustTournament(id)
idx, inProgress := t.next()
if t.Status != Running || inProgress || idx >= len(t.Pairs) {
return "", "", false
}
ab := strings.Split(t.Pairs[idx], "|")
return ab[0], ab[1], true
}