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