/
cloud.go
107 lines (86 loc) · 2.35 KB
/
cloud.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// SPDX-FileCopyrightText: 2021 Softbear, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
package server
import (
"fmt"
"time"
)
// A nil cloud is valid to use with any methods (acts as a no-op)
// This just means server is in offline mode
type Cloud interface {
fmt.Stringer
UpdateServer(players int) error
IncrementPlayerStatistic()
IncrementNewPlayerStatistic()
IncrementPlaysStatistic()
FlushStatistics() error
UpdateLeaderboard(playerScores map[string]int) error
UploadTerrainSnapshot(data []byte) error // takes an encoded PNG
UpdatePeriod() time.Duration
}
type Offline struct{}
func (offline Offline) String() string {
return "offline"
}
func (offline Offline) UpdateServer(players int) error {
return nil
}
func (offline Offline) IncrementPlayerStatistic() {}
func (offline Offline) IncrementNewPlayerStatistic() {}
func (offline Offline) IncrementPlaysStatistic() {}
func (offline Offline) FlushStatistics() error {
return nil
}
func (offline Offline) UpdateLeaderboard(playerScores map[string]int) error {
return nil
}
func (offline Offline) UploadTerrainSnapshot(data []byte) error {
return nil
}
func (offline Offline) UpdatePeriod() time.Duration {
return time.Hour
}
func (h *Hub) Cloud() {
fmt.Println("Updating cloud")
err := h.cloud.FlushStatistics()
if err != nil {
fmt.Println("Error flushing statistics:", err)
}
playerCount := 0
// Note: Cannot use to determine number of players, as long as there
// are duplicate names
playerScores := make(map[string]int)
for client := h.clients.First; client != nil; client = client.Data().Next {
if !client.Bot() {
playerCount++
player := &client.Data().Player
if player.Score > playerScores[player.Name] {
playerScores[player.Name] = player.Score
}
}
}
go func() {
err := h.cloud.UpdateLeaderboard(playerScores)
if err != nil {
fmt.Println("Error updating leaderboard:", err)
}
}()
statusJSON, err := json.Marshal(struct {
Players int `json:"players"`
}{
Players: playerCount,
})
if err == nil {
h.statusJSON.Store(statusJSON)
} else {
fmt.Println("error marshaling status:", err)
}
err = h.cloud.UpdateServer(playerCount)
if err != nil {
fmt.Println("Error updating server:", err)
}
if _, offline := h.cloud.(Offline); !offline {
// High overhead, don't do when offline and the data has nowhere to go
h.SnapshotTerrain()
}
}