-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbolt_player_store.go
More file actions
81 lines (62 loc) · 1.54 KB
/
bolt_player_store.go
File metadata and controls
81 lines (62 loc) · 1.54 KB
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
package poker
import (
"fmt"
"sort"
"strconv"
bolt "go.etcd.io/bbolt"
)
const bucketName = "StoreBucket"
func NewBoltPlayerStore(store *bolt.DB) *BoltPlayerStore {
store.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(bucketName))
return err
})
return &BoltPlayerStore{store}
}
type BoltPlayerStore struct {
store *bolt.DB
}
func (b *BoltPlayerStore) RecordWin(name string) {
b.store.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
score, _ := strconv.Atoi(string(bucket.Get([]byte(name))))
score++
err := bucket.Put([]byte(name), []byte(strconv.Itoa(score)))
return err
})
}
func (b *BoltPlayerStore) GetPlayerScore(name string) int {
score := 0
err := b.store.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
value := string(bucket.Get([]byte(name)))
score, _ = strconv.Atoi(value)
return nil
})
if err != nil {
fmt.Println("Error while trying to get player score")
}
return score
}
func (b *BoltPlayerStore) GetLeague() []Player {
league := make([]Player, 0)
err := b.store.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket([]byte(bucketName))
return bucket.ForEach(func(k, v []byte) error {
wins, err := strconv.Atoi(string(v))
player := Player{
Name: string(k),
Wins: wins,
}
league = append(league, player)
return err
})
})
if err != nil {
fmt.Println("Error while trying to get league")
}
sort.Slice(league, func(i, j int) bool {
return league[i].Wins > league[j].Wins
})
return league
}