tournament.gno
7.80 Kb · 316 lines
1package arena
2
3import (
4 "strconv"
5 "strings"
6
7 "gno.land/p/nt/avl/v0"
8 "gno.land/p/nt/ufmt/v0"
9)
10
11// Tournaments. Anyone can open a round-robin tournament; bot owners enter
12// their bots; the creator starts it. Matches are then created one at a time
13// and are ordinary matches, so a bot that crashes in a tournament game is
14// handled exactly like anywhere else: step mode, then a forfeit. A
15// tournament can therefore never get stuck on a broken bot.
16//
17// Scoring: 3 points for a win, 1 for a draw. Ties are broken by gold
18// difference, then gold scored, then name.
19
20const (
21 minEntrants = 2
22 maxEntrants = 8
23)
24
25// TournamentStatus of a tournament.
26type TournamentStatus int
27
28const (
29 Open TournamentStatus = iota
30 Running
31 Done
32)
33
34func (s TournamentStatus) String() string {
35 switch s {
36 case Open:
37 return "open for entries"
38 case Running:
39 return "running"
40 }
41 return "finished"
42}
43
44// Tournament is a round-robin between up to maxEntrants bots.
45type Tournament struct {
46 ID int
47 Name string
48 Creator address
49 Created int64
50 Capacity int
51 Status TournamentStatus
52 Entrants []string
53 Pairs []string // "a|b", in play order, fixed at start
54 MatchIDs []int // match id for each pair once created
55 Winner string
56}
57
58var (
59 tournaments = avl.NewTree() // padded id -> *Tournament
60 lastTID = 0
61)
62
63func mustTournament(id int) *Tournament {
64 v := tournaments.Get(key(id))
65 if v == nil {
66 panic("unknown tournament: " + strconv.Itoa(id))
67 }
68 return v.(*Tournament)
69}
70
71// CreateTournament opens a round-robin for up to capacity bots (2 to 8).
72func CreateTournament(cur realm, name string, capacity int) int {
73 name = cleanText(name)
74 if len(name) < 3 || len(name) > 48 {
75 panic("tournament names must be 3 to 48 characters")
76 }
77 if capacity < minEntrants || capacity > maxEntrants {
78 panic(ufmt.Sprintf("capacity must be %d to %d", minEntrants, maxEntrants))
79 }
80 lastTID++
81 t := &Tournament{
82 ID: lastTID, Name: name, Creator: cur.Previous().Address(),
83 Created: height(), Capacity: capacity, Status: Open,
84 }
85 tournaments.Set(key(t.ID), t)
86 emit("TournamentCreated", "id", strconv.Itoa(t.ID), "name", name)
87 return t.ID
88}
89
90// JoinTournament enters a bot you own into an open tournament.
91func JoinTournament(cur realm, id int, botName string) {
92 t := mustTournament(id)
93 b := mustOwn(cur, botName)
94 if t.Status != Open {
95 panic("tournament is not open for entries")
96 }
97 if b.Retired {
98 panic(botName + " is retired")
99 }
100 if len(t.Entrants) >= t.Capacity {
101 panic("tournament is full")
102 }
103 for _, e := range t.Entrants {
104 if e == botName {
105 panic(botName + " is already entered")
106 }
107 }
108 t.Entrants = append(t.Entrants, botName)
109 emit("TournamentJoined", "id", strconv.Itoa(id), "bot", botName)
110}
111
112// StartTournament closes entries and fixes the schedule. Only the creator
113// can start it.
114func StartTournament(cur realm, id int) {
115 t := mustTournament(id)
116 if cur.Previous().Address() != t.Creator {
117 panic("only the creator can start this tournament")
118 }
119 if t.Status != Open {
120 panic("tournament already started")
121 }
122 if len(t.Entrants) < minEntrants {
123 panic("a tournament needs at least 2 bots")
124 }
125 t.Pairs = roundRobin(t.Entrants)
126 t.MatchIDs = make([]int, len(t.Pairs))
127 t.Status = Running
128 emit("TournamentStarted", "id", strconv.Itoa(id), "matches", strconv.Itoa(len(t.Pairs)))
129}
130
131// roundRobin schedules every pair once, round by round (circle method), so
132// no bot plays twice in a row more than it must. Sides alternate by round.
133func roundRobin(entrants []string) []string {
134 ps := append([]string{}, entrants...)
135 if len(ps)%2 == 1 {
136 ps = append(ps, "") // bye
137 }
138 n := len(ps)
139 var out []string
140 for round := 0; round < n-1; round++ {
141 for i := 0; i < n/2; i++ {
142 a, b := ps[i], ps[n-1-i]
143 if a == "" || b == "" {
144 continue
145 }
146 if round%2 == 1 {
147 a, b = b, a
148 }
149 out = append(out, a+"|"+b)
150 }
151 // rotate everyone but the first
152 last := ps[n-1]
153 copy(ps[2:], ps[1:n-1])
154 ps[1] = last
155 }
156 return out
157}
158
159// next returns the index of the first pair without a finished match, and
160// whether that pair already has a match in progress.
161func (t *Tournament) next() (idx int, inProgress bool) {
162 for i, id := range t.MatchIDs {
163 if id == 0 {
164 return i, false
165 }
166 if mustMatch(id).Status != Finished {
167 return i, true
168 }
169 }
170 return len(t.MatchIDs), false
171}
172
173// NextTournamentMatch creates the tournament's next match and returns its
174// id. Play it with Play, or step mode if a bot keeps it from finishing.
175// Anyone may call it.
176func NextTournamentMatch(cur realm, id int) int {
177 t := mustTournament(id)
178 m := t.createNext(cur)
179 m.save()
180 return m.ID
181}
182
183// PlayTournament creates the next match and plays it in one transaction. If
184// a bot makes it fail, nothing is recorded: use NextTournamentMatch, then
185// Play or step mode. Anyone may call it.
186func PlayTournament(cur realm, id int) string {
187 t := mustTournament(id)
188 m := t.createNext(cur)
189 m.play()
190 m.save()
191 t.checkDone()
192 return m.Summary()
193}
194
195func (t *Tournament) createNext(cur realm) *Match {
196 if t.Status != Running {
197 panic("tournament is " + t.Status.String())
198 }
199 idx, inProgress := t.next()
200 if inProgress {
201 panic(ufmt.Sprintf("match #%d is still being played: finish it with Play or step mode", t.MatchIDs[idx]))
202 }
203 if idx == len(t.Pairs) {
204 t.checkDone()
205 panic("all tournament matches are played")
206 }
207 ab := strings.Split(t.Pairs[idx], "|")
208 m := newMatch(cur, ab[0], ab[1])
209 m.Tournament = t.ID
210 t.MatchIDs[idx] = m.ID
211 return m
212}
213
214// checkDone finishes the tournament once every match is settled.
215func (t *Tournament) checkDone() {
216 if t.Status != Running {
217 return
218 }
219 if idx, _ := t.next(); idx < len(t.Pairs) {
220 return
221 }
222 t.Status = Done
223 if st := t.Standings(); len(st) > 0 {
224 t.Winner = st[0].Bot
225 }
226 emit("TournamentFinished", "id", strconv.Itoa(t.ID), "winner", t.Winner)
227}
228
229// CloseTournament marks a tournament finished once all its matches are
230// settled (matches finished through step mode don't do it themselves).
231// Anyone may call it.
232func CloseTournament(cur realm, id int) {
233 t := mustTournament(id)
234 t.checkDone()
235 if t.Status != Done {
236 panic("tournament still has matches to play")
237 }
238}
239
240// Standing is one bot's line in a tournament table.
241type Standing struct {
242 Bot string
243 Played, Wins, Draws, Losses int
244 GoldFor, GoldAgainst int
245 Points int
246}
247
248// Standings returns the tournament table, best first.
249func (t *Tournament) Standings() []Standing {
250 rows := map[string]*Standing{}
251 for _, e := range t.Entrants {
252 rows[e] = &Standing{Bot: e}
253 }
254 for _, id := range t.MatchIDs {
255 if id == 0 {
256 continue
257 }
258 m := mustMatch(id)
259 if m.Status != Finished {
260 continue
261 }
262 for side := 0; side < 2; side++ {
263 r := rows[m.Bot(side)]
264 r.Played++
265 r.GoldFor += m.Game.Gold(side)
266 r.GoldAgainst += m.Game.Gold(1 - side)
267 switch m.Winner {
268 case side:
269 r.Wins++
270 r.Points += 3
271 case -1:
272 r.Draws++
273 r.Points++
274 default:
275 r.Losses++
276 }
277 }
278 }
279 out := make([]Standing, 0, len(rows))
280 for _, e := range t.Entrants {
281 out = append(out, *rows[e])
282 }
283 for i := 1; i < len(out); i++ {
284 for j := i; j > 0 && aheadOf(out[j], out[j-1]); j-- {
285 out[j], out[j-1] = out[j-1], out[j]
286 }
287 }
288 return out
289}
290
291func aheadOf(a, b Standing) bool {
292 if a.Points != b.Points {
293 return a.Points > b.Points
294 }
295 if da, db := a.GoldFor-a.GoldAgainst, b.GoldFor-b.GoldAgainst; da != db {
296 return da > db
297 }
298 if a.GoldFor != b.GoldFor {
299 return a.GoldFor > b.GoldFor
300 }
301 return a.Bot < b.Bot
302}
303
304// TournamentCount is the number of tournaments ever created.
305func TournamentCount() int { return lastTID }
306
307// TournamentNext returns the next pairing still to be created, if any.
308func TournamentNext(id int) (a, b string, ok bool) {
309 t := mustTournament(id)
310 idx, inProgress := t.next()
311 if t.Status != Running || inProgress || idx >= len(t.Pairs) {
312 return "", "", false
313 }
314 ab := strings.Split(t.Pairs[idx], "|")
315 return ab[0], ab[1], true
316}