arena.gno
5.24 Kb · 182 lines
1// Package arena runs matches between bots that other people deploy as their
2// own realms. Every turn the arena calls each bot's code, so the chain is the
3// referee and every bot's source is public.
4//
5// Matches have two speeds:
6//
7// - Fast: Play (or Fight) runs a whole match in one transaction.
8// - Step: if a match can't finish in one transaction (a bot crashes or runs
9// out of gas), StartStepMode switches it to one move per SubmitMove
10// transaction. The bot whose move can't be made misses its deadline and
11// ClaimForfeit records the loss. Crashing can't save a bot from a loss.
12package arena
13
14import (
15 "chain/runtime/unsafe"
16 "strings"
17
18 "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
19 "gno.land/p/nt/avl/v0"
20)
21
22const (
23 maxBotsPerRealm = 5
24 startRating = 1200
25)
26
27// Bot is a registered bot.
28type Bot struct {
29 Name string
30 Realm string // realm that registered it; its source is public
31 Owner address // account that sent the registering transaction
32 Registered int64 // block height
33 Rating int
34 Wins int
35 Losses int
36 Draws int
37 Forfeits int // losses by forfeit, also counted in Losses
38
39 // season record, reset when a new season starts (see season.gno)
40 SeasonWins, SeasonLosses, SeasonDraws int
41
42 // owner tools (see owner.gno)
43 Description string
44 Retired bool
45 Version int // 1 at registration, +1 per upgrade
46 History string // "realm@block," of previous versions
47
48 impl bot.Bot
49 fn bot.Strategy
50 recentRated string // "opponent@block," for recent rated matches, see claimRatedSlot
51}
52
53// Played is the number of finished matches.
54func (b *Bot) Played() int { return b.Wins + b.Losses + b.Draws }
55
56var (
57 bots = avl.NewTree() // name -> *Bot
58 botsPerRealm = avl.NewTree() // realm path -> int
59)
60
61// RegisterBot enters a bot with a Move method. Call it from your bot realm,
62// usually in init:
63//
64// func init(cur realm) { arena.RegisterBot(cross(cur), "my-bot", &myBot{}) }
65func RegisterBot(cur realm, name string, b bot.Bot) {
66 if b == nil {
67 panic("bot is nil")
68 }
69 register(cur, name, &Bot{impl: b})
70}
71
72// RegisterStrategy enters a bot written as a plain function. A function
73// declared in a /p/ package has one extra guarantee: if it crashes, the arena
74// can catch it straight away and score a forfeit without step mode.
75func RegisterStrategy(cur realm, name string, s bot.Strategy) {
76 if s == nil {
77 panic("strategy is nil")
78 }
79 register(cur, name, &Bot{fn: s})
80}
81
82func register(cur realm, name string, b *Bot) {
83 caller := cur.Previous()
84 if !caller.IsCode() || caller.IsEphemeral() {
85 panic("bots must be registered by a deployed realm, so their source is public")
86 }
87 if err := validName(name); err != "" {
88 panic(err)
89 }
90 if bots.Has(name) {
91 panic("bot name already taken: " + name)
92 }
93 realmPath := caller.PkgPath()
94 reserveRealmSlot(realmPath)
95 b.Name = name
96 b.Realm = realmPath
97 b.Owner = currentOrigin()
98 b.Registered = height()
99 b.Rating = startRating
100 b.Version = 1
101 bots.Set(name, b)
102 emit("BotRegistered", "name", name, "realm", realmPath)
103}
104
105// reserveRealmSlot counts one more bot for realmPath, up to maxBotsPerRealm.
106func reserveRealmSlot(realmPath string) {
107 count := 0
108 if v := botsPerRealm.Get(realmPath); v != nil {
109 count = v.(int)
110 }
111 if count >= maxBotsPerRealm {
112 panic("this realm already registered the maximum number of bots")
113 }
114 botsPerRealm.Set(realmPath, count+1)
115}
116
117func currentOrigin() address { return unsafe.OriginCaller() }
118
119func validName(name string) string {
120 if len(name) < 3 || len(name) > 24 {
121 return "bot names must be 3 to 24 characters"
122 }
123 for i, c := range name {
124 ok := (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '-' && i > 0 && i < len(name)-1)
125 if !ok {
126 return "bot names may only use a-z, 0-9 and inner dashes"
127 }
128 }
129 if strings.Contains(name, "--") {
130 return "bot names may not contain --"
131 }
132 return ""
133}
134
135func mustBot(name string) *Bot {
136 v := bots.Get(name)
137 if v == nil {
138 panic("unknown bot: " + name)
139 }
140 return v.(*Bot)
141}
142
143// ask gets one move from b. A crash inside a /p/ function bot is caught and
144// reported; a crash inside realm code aborts the transaction (Gno does not
145// let the caller recover it), which is what step mode is for.
146func (b *Bot) ask(s bot.State) (a bot.Action, crashed bool) {
147 defer func() {
148 if r := recover(); r != nil {
149 crashed = true
150 }
151 }()
152 if b.impl != nil {
153 return b.impl.Move(s), false
154 }
155 return b.fn(s), false
156}
157
158// BotInfo describes a bot for other realms and off-chain tools.
159type BotInfo struct {
160 Name, Realm, Description string
161 Owner address
162 Rating, Wins, Losses, Draws, Forfeits, Played int
163 Retired bool
164 Version int
165}
166
167// GetBot returns public information about a bot.
168func GetBot(name string) (BotInfo, bool) {
169 v := bots.Get(name)
170 if v == nil {
171 return BotInfo{}, false
172 }
173 b := v.(*Bot)
174 return BotInfo{
175 Name: b.Name, Realm: b.Realm, Description: b.Description, Owner: b.Owner,
176 Rating: b.Rating, Wins: b.Wins, Losses: b.Losses, Draws: b.Draws, Forfeits: b.Forfeits,
177 Played: b.Played(), Retired: b.Retired, Version: b.Version,
178 }, true
179}
180
181// BotCount is the number of registered bots.
182func BotCount() int { return bots.Size() }