match.gno
8.70 Kb · 356 lines
1package arena
2
3import (
4 "chain"
5 "chain/runtime"
6 "strconv"
7 "strings"
8
9 "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/bot"
10 "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/game"
11 "gno.land/p/nt/avl/v0"
12 "gno.land/p/nt/ufmt/v0"
13)
14
15const (
16 // MoveTimeout is how many blocks a bot has to make its move in step mode
17 // before anyone can claim a forfeit.
18 MoveTimeout = 100
19 // RatedCooldown is how many blocks must pass between two rated matches of
20 // the same pair of bots. Rematches in between are friendlies, so nobody
21 // can pump a rating by replaying the same opponent.
22 RatedCooldown = 1000
23)
24
25// Status of a match.
26type Status int
27
28const (
29 Pending Status = iota // challenged, not played yet
30 Stepping // being played one move per transaction
31 Finished
32)
33
34func (s Status) String() string {
35 switch s {
36 case Pending:
37 return "pending"
38 case Stepping:
39 return "step mode"
40 }
41 return "finished"
42}
43
44// Match is one game between two bots. Side 0 is A, side 1 is B.
45type Match struct {
46 ID int
47 BotA, BotB string
48 Status Status
49 Game game.Game
50 Challenger address
51 Created int64
52 Rated bool // decided when the match is created, see RatedCooldown
53
54 // step mode
55 Waiting int // side whose move is due
56 Held bot.Action // side 0's move for the current turn, once made
57 Deadline int64 // block height by which Waiting must move
58
59 // result
60 Winner int // 0, 1, or -1 for a draw
61 Forfeit bool // the loser forfeited
62 Reason string // why, for forfeits
63 Delta int // rating change for A (B gets the opposite)
64 Settled int64 // block height
65}
66
67var (
68 matches = avl.NewTree() // padded bucket number -> encoded matches (see codec.gno)
69 lastID = 0
70)
71
72// claimRatedSlot reports whether a new match between a and b is rated, and
73// if so starts the pair's cooldown. The cooldown is kept on the bot whose
74// name sorts first, as a short "opponent@block," list that drops expired
75// entries, so it costs a few bytes instead of a tree node per pair.
76func claimRatedSlot(a, b string) bool {
77 if b < a {
78 a, b = b, a
79 }
80 keeper := mustBot(a)
81 now := height()
82 var kept []string
83 rated := true
84 for _, e := range strings.Split(keeper.recentRated, ",") {
85 at := strings.LastIndex(e, "@")
86 if at < 0 {
87 continue
88 }
89 h, err := strconv.ParseInt(e[at+1:], 10, 64)
90 if err != nil || now-h >= RatedCooldown {
91 continue // expired
92 }
93 if e[:at] == b {
94 rated = false
95 }
96 kept = append(kept, e)
97 }
98 if rated {
99 kept = append(kept, b+"@"+strconv.FormatInt(now, 10))
100 }
101 keeper.recentRated = strings.Join(kept, ",")
102 return rated
103}
104
105// Bot returns the name of the bot playing side.
106func (m *Match) Bot(side int) string {
107 if side == 0 {
108 return m.BotA
109 }
110 return m.BotB
111}
112
113func key(id int) string {
114 s := strconv.Itoa(id)
115 for len(s) < 10 {
116 s = "0" + s
117 }
118 return s
119}
120
121func height() int64 { return runtime.ChainHeight() }
122
123func emit(typ string, attrs ...string) { chain.Emit(typ, attrs...) }
124
125func mustMatch(id int) *Match {
126 r, ok := record(id)
127 if !ok {
128 panic("unknown match: " + strconv.Itoa(id))
129 }
130 return decode(id, r)
131}
132
133// seedFor gives every match its own board. The pair is mixed in so two
134// matches created back to back between different bots differ too.
135func seedFor(id int, a, b string) int {
136 h := uint32(2166136261)
137 for _, s := range []string{a, "|", b} {
138 for i := 0; i < len(s); i++ {
139 h = (h ^ uint32(s[i])) * 16777619
140 }
141 }
142 return int((h + uint32(id)*7919) % 1000003)
143}
144
145// Challenge records a new match between two registered bots and returns its
146// id. It runs no bot code, so it always succeeds; play it with Play or, if
147// that fails, with step mode.
148func Challenge(cur realm, a, b string) int {
149 m := newMatch(cur, a, b)
150 m.save()
151 return m.ID
152}
153
154func newMatch(cur realm, a, b string) *Match {
155 if a == b {
156 panic("a bot can't fight itself")
157 }
158 mustBot(a)
159 mustBot(b)
160 lastID++
161 m := &Match{
162 ID: lastID,
163 BotA: a,
164 BotB: b,
165 Status: Pending,
166 Game: *game.New(seedFor(lastID, a, b)),
167 Challenger: cur.Previous().Address(),
168 Created: height(),
169 Rated: claimRatedSlot(a, b),
170 Winner: -1,
171 }
172 emit("MatchCreated", "id", strconv.Itoa(m.ID), "a", a, "b", b)
173 return m
174}
175
176// Play runs the rest of a match in this transaction. If a bot written in
177// realm code crashes or runs out of gas, the whole transaction fails and the
178// match stays as it was: switch it to step mode with StartStepMode.
179func Play(cur realm, id int) string {
180 m := mustMatch(id)
181 if m.Status == Finished {
182 panic("match already finished")
183 }
184 m.play()
185 m.save()
186 return m.Summary()
187}
188
189// Fight challenges and plays in one transaction, saving the match once. If
190// it fails, nothing is recorded: use Challenge, then Play or step mode.
191func Fight(cur realm, a, b string) string {
192 m := newMatch(cur, a, b)
193 m.play()
194 m.save()
195 return m.Summary()
196}
197
198// play runs the match to the end in memory.
199func (m *Match) play() {
200 players := [2]*Bot{mustBot(m.BotA), mustBot(m.BotB)}
201 for !m.Game.Over() {
202 var acts [2]bot.Action
203 for side := 0; side < 2; side++ {
204 if m.Status == Stepping && side == 0 && m.Waiting == 1 {
205 acts[0] = m.Held // already made in step mode
206 continue
207 }
208 a, crashed := players[side].ask(m.view(side))
209 if crashed {
210 m.forfeit(side, "crashed on turn "+strconv.Itoa(m.Game.Turn+1))
211 return
212 }
213 acts[side] = a
214 }
215 m.Game.Step(acts[0], acts[1])
216 m.Waiting = 0
217 }
218 m.finish()
219}
220
221// StartStepMode switches a pending match to one move per transaction.
222// Anyone may call it.
223func StartStepMode(cur realm, id int) {
224 m := mustMatch(id)
225 if m.Status != Pending {
226 panic("only a pending match can switch to step mode")
227 }
228 defer m.save()
229 m.Status = Stepping
230 m.Waiting = 0
231 m.Deadline = height() + MoveTimeout
232 emit("StepModeStarted", "id", strconv.Itoa(id))
233}
234
235// SubmitMove asks the bot whose turn it is for its move and records it. The
236// move comes from the bot's own code, so nobody can submit a fake one.
237// Anyone may call it.
238func SubmitMove(cur realm, id int) string {
239 m := mustMatch(id)
240 if m.Status != Stepping {
241 panic("match is not in step mode")
242 }
243 defer m.save()
244 side := m.Waiting
245 a, crashed := mustBot(m.Bot(side)).ask(m.view(side))
246 if crashed {
247 m.forfeit(side, "crashed on turn "+strconv.Itoa(m.Game.Turn+1))
248 return m.Summary()
249 }
250 if side == 0 {
251 m.Held = a
252 m.Waiting = 1
253 } else {
254 m.Game.Step(m.Held, a)
255 m.Waiting = 0
256 }
257 m.Deadline = height() + MoveTimeout
258 if m.Game.Over() {
259 m.finish()
260 }
261 return m.Summary()
262}
263
264// ClaimForfeit ends a step-mode match whose waiting bot missed its deadline.
265// Anyone may call it.
266func ClaimForfeit(cur realm, id int) string {
267 m := mustMatch(id)
268 if m.Status != Stepping {
269 panic("match is not in step mode")
270 }
271 if height() <= m.Deadline {
272 panic(ufmt.Sprintf("%s still has until block %d to move", m.Bot(m.Waiting), m.Deadline))
273 }
274 defer m.save()
275 m.forfeit(m.Waiting, "missed its move deadline on turn "+strconv.Itoa(m.Game.Turn+1))
276 return m.Summary()
277}
278
279// view is what side's bot sees this turn.
280func (m *Match) view(side int) bot.State {
281 s := m.Game.View(m.ID, side)
282 s.EnemyBot = m.Bot(1 - side)
283 return s
284}
285
286func (m *Match) finish() {
287 m.Winner = m.Game.Winner()
288 m.settle()
289}
290
291func (m *Match) forfeit(loser int, reason string) {
292 m.Winner = 1 - loser
293 m.Forfeit = true
294 m.Reason = m.Bot(loser) + " " + reason
295 m.settle()
296}
297
298func (m *Match) settle() {
299 m.Status = Finished
300 m.Settled = height()
301 a, b := mustBot(m.BotA), mustBot(m.BotB)
302 if m.Rated {
303 m.Delta = rate(a, b, m.Winner)
304 }
305 switch m.Winner {
306 case 0:
307 a.Wins++
308 b.Losses++
309 if m.Forfeit {
310 b.Forfeits++
311 }
312 case 1:
313 b.Wins++
314 a.Losses++
315 if m.Forfeit {
316 a.Forfeits++
317 }
318 default:
319 a.Draws++
320 b.Draws++
321 }
322 winner := "draw"
323 if m.Winner >= 0 {
324 winner = m.Bot(m.Winner)
325 }
326 emit("MatchFinished", "id", strconv.Itoa(m.ID), "winner", winner,
327 "gold", ufmt.Sprintf("%d-%d", m.Game.GoldA, m.Game.GoldB))
328}
329
330// Summary is a one-line description of the match.
331func (m *Match) Summary() string {
332 g := &m.Game
333 score := ufmt.Sprintf("%s %d - %d %s", m.Bot(0), g.GoldA, g.GoldB, m.Bot(1))
334 switch {
335 case m.Status != Finished:
336 return ufmt.Sprintf("#%d %s (%s, turn %d of %d)", m.ID, score, m.Status.String(), g.Turn, bot.Turns)
337 case m.Forfeit:
338 return ufmt.Sprintf("#%d %s wins by forfeit: %s%s", m.ID, m.Bot(m.Winner), m.Reason, m.friendlyNote())
339 case m.Winner < 0:
340 return ufmt.Sprintf("#%d %s, draw%s", m.ID, score, m.friendlyNote())
341 }
342 return ufmt.Sprintf("#%d %s, %s wins%s", m.ID, score, m.Bot(m.Winner), m.friendlyNote())
343}
344
345func (m *Match) friendlyNote() string {
346 if m.Rated {
347 return ""
348 }
349 return " (friendly)"
350}
351
352// MatchSummary returns the summary of a match, for other realms and tools.
353func MatchSummary(id int) string { return mustMatch(id).Summary() }
354
355// MatchCount is the number of matches ever created.
356func MatchCount() int { return lastID }