-
Notifications
You must be signed in to change notification settings - Fork 8
/
engine.go
391 lines (357 loc) · 11 KB
/
engine.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package game
import (
"database/sql"
"encoding/json"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/dascr/dascr-board/logger"
"github.com/dascr/dascr-board/player"
"github.com/dascr/dascr-board/settings"
"github.com/dascr/dascr-board/ws"
"github.com/go-chi/chi"
)
// Games hold the running games
var Games = make(map[string]Data)
// Data stuct will hold the generic game data
// handed over by the frontend. It might be used in
// the different game types
type Data struct {
UID string `json:"uid"`
Player []int `json:"player"`
Game string `json:"game"`
Variant string `json:"variant"`
In string `json:"in"`
Out string `json:"out"`
Punisher bool `json:"punisher"`
Sound bool `json:"sound"`
Podium bool `json:"podium"`
AutoSwitch bool `json:"autoswitch"`
CricketRandom bool `json:"cricketrandom"`
CricketGhost bool `json:"cricketghost"`
GameObject Game
}
// GetAllGames lists all in memory games
func GetAllGames() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var gamesSlice []Data
for _, element := range Games {
gamesSlice = append(gamesSlice, element)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(gamesSlice); err != nil {
logger.Errorf("Error when encoding json: %+v", err)
}
}
}
// GetSpecificGame lists a specific in memory game
func GetSpecificGame() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uid := chi.URLParam(r, "id")
if _, ok := Games[uid]; ok {
game := Games[uid]
status := game.GameObject.GetStatus()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(status); err != nil {
logger.Errorf("Error when encoding json: %+v", err)
}
} else {
http.Error(w, "There is no game with this id", http.StatusNotFound)
}
}
}
// GetSpecificGameDisplay lists a specific in memory game
// and only provides the data necessary to display the
// Scoreboard information (small data size)
func GetSpecificGameDisplay() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uid := chi.URLParam(r, "id")
if _, ok := Games[uid]; ok {
game := Games[uid]
status := game.GameObject.GetStatusDisplay()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(status); err != nil {
logger.Errorf("Error when encoding json: %+v", err)
}
} else {
http.Error(w, "There is no game with this id", http.StatusNotFound)
}
}
}
// CreateGame will dispatch the creation of a game
// to the corresponding game creation handler after
// adding it to the in memory games map
func CreateGame(db *sql.DB, h *ws.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var data Data
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
w.WriteHeader(http.StatusBadRequest)
if _, err := w.Write([]byte("Error parsing json data on backend")); err != nil {
logger.Errorf("Error when writing response back to browser: %+v", err)
}
return
}
// Init random number generator
s := rand.NewSource(time.Now().Unix())
rg := rand.New(s)
activePlayer := rg.Intn(len(data.Player))
// Get players from database
var players = player.GetPlayerList(db, data.Player)
// Dispatch to handler
switch game := data.Game; game {
case "x01":
data.GameObject = &X01Game{
Base: BaseGame{
UID: data.UID,
Game: data.Game,
Player: players,
Variant: data.Variant,
In: data.In,
Out: data.Out,
ActivePlayer: activePlayer,
ThrowRound: 1,
GameState: "THROW",
Message: "",
Settings: &settings.Settings{
Podium: data.Podium,
Sound: data.Sound,
AutoSwitch: data.AutoSwitch,
Punisher: data.Punisher,
},
},
}
case "cricket":
data.GameObject = &CricketGame{
Base: BaseGame{
UID: data.UID,
Game: data.Game,
Player: players,
Variant: data.Variant,
ActivePlayer: activePlayer,
ThrowRound: 1,
GameState: "THROW",
Message: "",
Settings: &settings.Settings{
Podium: data.Podium,
Sound: data.Sound,
AutoSwitch: data.AutoSwitch,
},
CricketController: &CricketGameController{
Random: data.CricketRandom,
Ghost: data.CricketGhost,
},
},
}
case "atc":
data.GameObject = &ATCGame{
Base: BaseGame{
UID: data.UID,
Game: data.Game,
Player: players,
Variant: data.Variant,
ActivePlayer: activePlayer,
ThrowRound: 1,
GameState: "THROW",
Message: "",
Settings: &settings.Settings{
Podium: data.Podium,
Sound: data.Sound,
AutoSwitch: data.AutoSwitch,
},
},
}
case "split":
data.GameObject = &SplitGame{
Base: BaseGame{
UID: data.UID,
Game: data.Game,
Player: players,
Variant: data.Variant,
ActivePlayer: activePlayer,
ThrowRound: 1,
GameState: "THROW",
Message: "",
Settings: &settings.Settings{
Podium: false,
Sound: data.Sound,
AutoSwitch: data.AutoSwitch,
},
},
}
case "shanghai":
data.GameObject = &ShanghaiGame{
Base: BaseGame{
UID: data.UID,
Game: data.Game,
Player: players,
Variant: data.Variant,
ActivePlayer: activePlayer,
ThrowRound: 1,
GameState: "THROW",
Message: "",
Settings: &settings.Settings{
Podium: false,
Sound: data.Sound,
AutoSwitch: data.AutoSwitch,
},
},
}
case "elim":
data.GameObject = &EliminiationGame{
Base: BaseGame{
UID: data.UID,
Game: data.Game,
Player: players,
Variant: data.Variant,
In: data.In,
Out: data.Out,
ActivePlayer: activePlayer,
ThrowRound: 1,
GameState: "THROW",
Message: "",
Settings: &settings.Settings{
Podium: data.Podium,
Sound: data.Sound,
AutoSwitch: data.AutoSwitch,
Punisher: data.Punisher,
},
},
}
}
if err := data.GameObject.StartGame(); err != nil {
logger.Errorf("Game cannot be started: %+v", err)
w.WriteHeader(http.StatusBadRequest)
if _, err := w.Write([]byte("Error occurred starting a Game")); err != nil {
logger.Errorf("Error writing response back to browser: %+v", err)
}
}
Games[data.UID] = data
// trigger redirect of scanpage and game setup page
message := ws.Message{
Room: chi.URLParam(r, "id"),
Data: []byte("redirect"),
}
h.Broadcast <- message
// json encode game as response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(data); err != nil {
logger.Errorf("Error when encoding json: %+v", err)
}
}
}
// DeleteGame will delete game from in memory map
func DeleteGame(h *ws.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
delete(Games, chi.URLParam(r, "id"))
// redirect scoreboard and controller page
message := ws.Message{
Room: chi.URLParam(r, "id"),
Data: []byte("redirect"),
}
h.Broadcast <- message
w.WriteHeader(http.StatusNoContent)
}
}
// NextPlayer will switch to next player in game
func NextPlayer(h *ws.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uid := chi.URLParam(r, "id")
if _, ok := Games[uid]; ok {
game := Games[uid]
game.GameObject.NextPlayer(h)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(game.GameObject); err != nil {
logger.Errorf("Error when encoding json: %+v", err)
}
} else {
http.Error(w, "There is no game with this id", http.StatusNotFound)
}
}
}
// InsertThrow will handle to add a throw to a game
func InsertThrow(h *ws.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var iNum, iMod int
var err error
uid := chi.URLParam(r, "id")
if _, ok := Games[uid]; ok {
number := chi.URLParam(r, "number")
modifier := chi.URLParam(r, "modifier")
if iNum, err = strconv.Atoi(number); err != nil {
logger.Errorf("When adding throw. Invalid number: %+v", err)
w.WriteHeader(http.StatusBadRequest)
if _, err := w.Write([]byte("Throw was not added")); err != nil {
logger.Errorf("Error writing response back to browser: %+v", err)
}
return
}
if iMod, err = strconv.Atoi(modifier); err != nil {
logger.Errorf("When adding throw. Invalid modifier: %+v", err)
w.WriteHeader(http.StatusBadRequest)
if _, err := w.Write([]byte("Throw was not added")); err != nil {
logger.Errorf("Error writing response back to browser: %+v", err)
}
return
}
game := Games[uid]
if err := game.GameObject.RequestThrow(iNum, iMod, h); err != nil {
logger.Errorf("When adding throw: %+v", err)
w.WriteHeader(http.StatusBadRequest)
if _, err := w.Write([]byte("Throw was not added")); err != nil {
logger.Errorf("Error writing response back to browser: %+v", err)
}
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(game.GameObject); err != nil {
logger.Errorf("Error when encoding json: %+v", err)
}
} else {
http.Error(w, "There is no game with this id", http.StatusNotFound)
}
}
}
// Undo will handle the undo actions per game
func Undo(h *ws.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if data, ok := Games[chi.URLParam(r, "id")]; ok {
if err := data.GameObject.Undo(h); err != nil {
logger.Errorf("There was an error undoing last turn: %+v", err)
http.Error(w, "There was an error undoing last turn", 500)
return
}
w.WriteHeader(http.StatusOK)
if _, err := w.Write([]byte("Turn was undone")); err != nil {
logger.Errorf("Error writing response back to browser: %+v", err)
}
} else {
http.Error(w, "There is no game with this id", http.StatusNotFound)
}
}
}
// Rematch will handle the rematch action per game
func Rematch(h *ws.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if data, ok := Games[chi.URLParam(r, "id")]; ok {
if err := data.GameObject.Rematch(h); err != nil {
logger.Errorf("There was an error triggering rematch: %+v", err)
http.Error(w, "There was an error triggering", 500)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(data.GameObject.GetStatusDisplay()); err != nil {
logger.Errorf("Error when encoding json: %+v", err)
}
} else {
http.Error(w, "There is no game with this id", http.StatusNotFound)
}
}
}