season.gno
2.44 Kb · 98 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// Seasons. Ratings and season records reset every SeasonLength blocks, and
12// each finished season's top 10 is kept. The switch happens lazily: the first
13// match or challenge after a season's end closes it, so no scheduler is
14// needed. All-time records (Wins, Losses, Draws) never reset.
15
16// SeasonLength is about 30 days at Onyx's ~3.6 s blocks.
17const SeasonLength = 720000
18
19var (
20 season = 1
21 seasonStart = int64(0) // set on the first activity
22 pastSeasons = avl.NewTree() // padded season number -> "name:rating:w-l-d," top 10
23 seasonTop = 10
24)
25
26// SeasonInfo reports the current season number and the block it ends at.
27func SeasonInfo() (number int, endsAt int64) {
28 return season, seasonStart + SeasonLength
29}
30
31// rollSeason closes the current season if it is over. Call it before any
32// state change that touches ratings.
33func rollSeason() {
34 now := height()
35 if seasonStart == 0 {
36 seasonStart = now
37 return
38 }
39 for now >= seasonStart+SeasonLength {
40 closeSeason()
41 seasonStart += SeasonLength
42 }
43}
44
45func closeSeason() {
46 var sb strings.Builder
47 for i, b := range leaderboard() {
48 if i == seasonTop {
49 break
50 }
51 if b.SeasonWins+b.SeasonLosses+b.SeasonDraws == 0 {
52 continue // didn't play this season
53 }
54 sb.WriteString(ufmt.Sprintf("%s:%d:%d-%d-%d,", b.Name, b.Rating, b.SeasonWins, b.SeasonLosses, b.SeasonDraws))
55 }
56 pastSeasons.Set(key(season), sb.String())
57 emit("SeasonEnded", "season", strconv.Itoa(season))
58 bots.Iterate("", "", func(_ string, v any) bool {
59 b := v.(*Bot)
60 b.Rating = startRating
61 b.SeasonWins, b.SeasonLosses, b.SeasonDraws = 0, 0, 0
62 b.recentRated = ""
63 return false
64 })
65 season++
66}
67
68// SeasonStanding is one line of a finished season's top 10.
69type SeasonStanding struct {
70 Bot string
71 Rating int
72 Wins, Losses, Draws int
73}
74
75// PastSeason returns the top 10 of a finished season.
76func PastSeason(number int) []SeasonStanding {
77 v := pastSeasons.Get(key(number))
78 if v == nil {
79 return nil
80 }
81 var out []SeasonStanding
82 for _, e := range strings.Split(v.(string), ",") {
83 f := strings.Split(e, ":")
84 if len(f) != 3 {
85 continue
86 }
87 r, _ := strconv.Atoi(f[1])
88 wld := strings.Split(f[2], "-")
89 if len(wld) != 3 {
90 continue
91 }
92 w, _ := strconv.Atoi(wld[0])
93 l, _ := strconv.Atoi(wld[1])
94 d, _ := strconv.Atoi(wld[2])
95 out = append(out, SeasonStanding{f[0], r, w, l, d})
96 }
97 return out
98}