-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleaderboard.go
90 lines (74 loc) · 1.7 KB
/
leaderboard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"GymBot/exercises"
"encoding/json"
"log"
"os"
"time"
)
const benchLeaderboardsFile = "benchleaderboards.json"
const squatLeaderboardsFile = "squatleaderboards.json"
const deadliftLeaderboardsFile = "deadliftleaderboards.json"
// All prs are in kg
var benchPrs = map[string]float64{}
var squatPrs = map[string]float64{}
var deadliftPrs = map[string]float64{}
var liftPrs = map[exercises.Exercise]map[string]float64{
exercises.BENCH: benchPrs,
exercises.SQUAT: squatPrs,
exercises.DEADLIFT: deadliftPrs,
}
func init() {
loadLeaderBoards()
}
func AddPr(userId string, exercise exercises.Exercise, amount float64) {
liftPrs[exercise][userId] = amount
}
func GetPr(userId string, exercise exercises.Exercise) (float64, bool) {
val, exists := liftPrs[exercise][userId]
return val, exists
}
func autoSave() {
ticker := time.NewTicker(15 * time.Minute)
defer ticker.Stop()
go func() {
for {
select {
case <-ticker.C:
saveAll()
}
}
}()
}
func saveAll() {
save(benchLeaderboardsFile, benchPrs)
save(squatLeaderboardsFile, squatPrs)
save(deadliftLeaderboardsFile, deadliftPrs)
}
func loadLeaderBoards() {
load(benchLeaderboardsFile, benchPrs)
load(squatLeaderboardsFile, squatPrs)
load(deadliftLeaderboardsFile, deadliftPrs)
}
func load(file string, prs map[string]float64) {
jsonBytes, err := os.ReadFile(file)
if err != nil {
log.Println(err)
return
}
err = json.Unmarshal(jsonBytes, &prs)
if err != nil {
log.Println(err)
}
}
func save(file string, prs map[string]float64) {
marshal, err := json.MarshalIndent(prs, "", " ")
if err != nil {
log.Println(err)
return
}
err = os.WriteFile(file, marshal, 0644)
if err != nil {
log.Println(err)
}
}