-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbasic_server.go
More file actions
652 lines (496 loc) · 18.2 KB
/
basic_server.go
File metadata and controls
652 lines (496 loc) · 18.2 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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
package main
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/Akavall/GoGamesProject/dice"
"github.com/Akavall/GoGamesProject/dynamo_db_tools"
"github.com/Akavall/GoGamesProject/statistics"
"github.com/Akavall/GoGamesProject/zombie_dice"
"github.com/nu7hatch/gouuid"
)
const MAX_ZOMBIE_DICE_GAMES = 60
var templates = template.Must(template.ParseFiles("web/index.html", "web/zombie_dice.html", "web/zombie_dice_multi_player.html"))
var zombie_games = make(map[string]*zombie_dice.GameState)
var zombie_chats = make(map[string]*zombie_dice.ZombieChat)
type id_to_name_type map[string]string
var id_to_name id_to_name_type = map[string]string{}
func zombie_game(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-type", "text/html")
err := templates.ExecuteTemplate(response, "zombie_dice.html", nil)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
}
}
func zombie_game_multi_player(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-type", "text/html")
err := templates.ExecuteTemplate(response, "zombie_dice_multi_player.html", nil)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
}
}
func index(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-type", "text/html")
err := templates.ExecuteTemplate(response, "index.html", nil)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
}
}
func start_zombie_dice(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-type", "text/plain")
// Parse URL and POST data into the request.Form
err := request.ParseForm()
if err != nil {
log.Fatal(response, fmt.Sprintf("error parsing url %v", err), 500)
}
num_players_input := request.Form["num_players"]
log.Println("num_players_input", num_players_input)
var num_players int
if len(num_players_input) == 1 {
num_players, err = strconv.Atoi(num_players_input[0])
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
} else {
log.Printf("Bad input on number of players! Received %d inputs, expected only 1", len(num_players_input))
http.Error(response, err.Error(), http.StatusBadRequest)
return
}
players := make([]zombie_dice.Player, num_players)
log.Println("num_players", num_players)
for i := 1; i <= num_players; i++ {
player := "player" + strconv.Itoa(i)
player_id_input := request.Form[player]
var player_id string
if len(player_id_input) == 1 {
player_id = player_id_input[0]
} else {
error_message := fmt.Sprintf("Bad input on %s! Received %d inputs, expected only 1", player, len(player_id_input))
log.Printf(error_message)
http.Error(response, error_message, http.StatusBadRequest)
return
}
is_ai_input := request.Form[player+"_ai"]
var is_player_ai bool
if len(is_ai_input) == 1 {
is_player_ai, err = strconv.ParseBool(is_ai_input[0])
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
} else {
error_message := fmt.Sprintf("Bad input on AI flag for %s_ai! Received %d inputs, expected only 1", player, len(is_ai_input))
log.Printf(error_message)
http.Error(response, error_message, http.StatusBadRequest)
return
}
score := 0
players[i-1] = zombie_dice.Player{PlayerState: zombie_dice.InitPlayerState(), Id: player_id, IsAI: is_player_ai, TotalScore: &score}
}
uuid, err := uuid.NewV4()
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
}
uuid_string := uuid.String()
game_state, err := zombie_dice.InitGameState(players, uuid_string)
err = dynamo_db_tools.PutGameStateInDynamoDB(game_state)
if err != nil {
log.Println("Was not able to put GameState in DynamoDB", err)
} else {
log.Printf("Put GateState associated with %s in DynamoDB table: GameStates", uuid_string)
}
zombie_chat := zombie_dice.ZombieChat{}
if len(zombie_chats) < MAX_ZOMBIE_DICE_GAMES {
zombie_chats[uuid_string] = &zombie_chat
log.Printf("Successfully started new Zombie Dice chat with ID: %s; Number of running chats: %d", uuid_string, len(zombie_chats))
} else {
error_message := fmt.Sprintf("Maximum number of zombie dice chats (%d) reached!", MAX_ZOMBIE_DICE_GAMES)
log.Printf(error_message)
http.Error(response, error_message, http.StatusBadRequest)
return
}
fmt.Fprintf(response, "%s", uuid_string)
}
func join_game(response http.ResponseWriter, request *http.Request) {
log.Println("Joining the game...")
response.Header().Set("Content-type", "text/plain")
// Parse URL and POST data into the request.Form
err := request.ParseForm()
if err != nil {
log.Fatal(response, fmt.Sprintf("error parsing url %v", err), 500)
}
game_id_input := request.Form["game_id"]
game_id := game_id_input[0]
game_state, err := dynamo_db_tools.GetGameStateFromDynamoDB(game_id)
if err != nil {
http.Error(response, fmt.Sprintf("Game with id %s not found!, %v", game_id, err), http.StatusBadRequest)
return
} else {
log.Printf("Grabbed game state with id: %s", game_id)
}
player2_input := request.Form["player2"]
player2_name := player2_input[0]
score := 0
player2 := zombie_dice.Player{PlayerState: zombie_dice.InitPlayerState(), Id: player2_name, IsAI: false, TotalScore: &score}
(game_state).Players = append((game_state).Players, player2)
err = dynamo_db_tools.PutGameStateInDynamoDB(game_state)
if err != nil {
log.Println("Was not able to put GameState in DynamoDB", err)
} else {
log.Printf("Put/update GameState associated with %s in DynamoDB table: GameStates, updating players", game_id)
}
log.Printf("Player: %s joined game: %s", player2_name, game_id)
}
func take_zombie_dice_turn(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-type", "text/plain")
err := request.ParseForm()
if err != nil {
log.Fatal(response, fmt.Sprintf("error parsing url %v", err), 500)
}
uuid, err := parse_input(request, "uuid")
if err != nil {
http.Error(response, err.Error(), http.StatusBadRequest)
return
}
player_id, err := parse_input(request, "player")
if err != nil {
http.Error(response, err.Error(), http.StatusBadRequest)
return
}
log.Print("PLAYERS NAME : ", player_id)
continue_turn_string, err := parse_input(request, "continue")
if err != nil {
http.Error(response, err.Error(), http.StatusBadRequest)
return
}
continue_turn, err := strconv.ParseBool(continue_turn_string)
if err != nil {
http.Error(response, err.Error(), http.StatusBadRequest)
return
}
log.Printf("continue_turn_0 : %t", continue_turn)
log.Printf("uuid : %s", uuid)
game_state, err := dynamo_db_tools.GetGameStateFromDynamoDB(uuid)
if err != nil {
http.Error(response, fmt.Sprintf("Game with id %s not found!, %v", uuid, err), http.StatusBadRequest)
return
} else {
log.Printf("Grabbed game state with id: %s", uuid)
}
if game_state.IsActive {
http.Error(response, fmt.Sprintf("Game state with id %s is already active!", uuid), http.StatusBadRequest)
return
} else {
game_state.IsActive = true
}
player_index := game_state.PlayerTurn
active_player := game_state.Players[player_index]
if player_id != active_player.Id {
http.Error(response, fmt.Sprintf("%s is currently taking a turn, not %s!", active_player.Id, player_id), http.StatusBadRequest)
game_state.IsActive = false
return
}
if active_player.IsAI {
log.Printf("Size of deck : %d\n", len(game_state.ZombieDeck.Deck.Dices))
log.Printf("\033[034mshot: %d,brains: %d, walks: %d\033[0m", active_player.PlayerState.TimesShot, active_player.PlayerState.BrainsRolled, active_player.PlayerState.WalksTakenLastRoll)
if zombie_dice.SimulationistAI(active_player.PlayerState.TimesShot,
active_player.PlayerState.BrainsRolled,
active_player.PlayerState.WalksTakenLastRoll,
&game_state.ZombieDeck) == 0 {
continue_turn = false
}
}
turn_result := make([][]string, 3)
for i := 0; i < 3; i++ {
turn_result[i] = make([]string, 2)
}
if continue_turn {
turn_result, err = active_player.TakeTurn(&game_state.ZombieDeck)
if err != nil {
http.Error(response, fmt.Sprintf("Error occured while player %s was taking turn: %s", active_player.Id, err.Error()), http.StatusBadRequest)
return
}
} else {
*active_player.TotalScore += active_player.PlayerState.CurrentScore
active_player.PlayerState.Reset()
game_state.EndTurn()
}
player_turn_result := zombie_dice.PlayerTurnResult{
TurnResult: turn_result,
RoundScore: active_player.PlayerState.CurrentScore,
TimesShot: active_player.PlayerState.TimesShot,
TotalScore: *active_player.TotalScore,
IsDead: active_player.PlayerState.IsDead,
Winner: game_state.Winner.Id,
PlayerId: active_player.Id,
ContinueTurn: continue_turn}
json_string, err := json.Marshal(player_turn_result)
if err != nil {
panic(err) //TO-DO: handle this error better
}
game_state.MoveLog = append(game_state.MoveLog, player_turn_result)
fmt.Fprintf(response, string(json_string))
if game_state.GameOver {
// sleeping to display the game status
// for multi player, skiping for games with AI
// TODO: There has to be a better way to do this
skip_sleep := false
for _, player := range game_state.Players {
if player.IsAI {
skip_sleep = true
}
}
if !skip_sleep {
log.Println("Sleeping...")
time.Sleep(time.Second * 30)
}
err := dynamo_db_tools.DeleteGameStateFromDynamoDB(uuid)
if err != nil {
log.Println("Was not able to delete GameState in DynamoDB, uuid: %s", err, uuid)
} else {
log.Printf("Deleted GameState associated with %s in DynamoDB table: GameStates", uuid)
}
delete(zombie_chats, uuid)
}
if active_player.PlayerState.IsDead {
active_player.PlayerState.Reset()
game_state.EndTurn()
}
game_state.IsActive = false
err = dynamo_db_tools.PutGameStateInDynamoDB(game_state)
if err != nil {
log.Println("Was not able to put GameState in DynamoDB", err)
} else {
log.Printf("Put/update GameState associated with %s in DynamoDB table: GameStates", uuid)
}
}
func get_player_turn_results(response http.ResponseWriter, request *http.Request) {
err := request.ParseForm()
if err != nil {
panic(err)
}
game_id_form, _ := request.Form["game_id"]
game_id := game_id_form[0]
game_state, err := dynamo_db_tools.GetGameStateFromDynamoDB(game_id)
if err != nil {
http.Error(response, fmt.Sprintf("Game with id %s not found!, %v", game_id, err), http.StatusBadRequest)
return
} else {
log.Printf("Grabbed game state with id: %s", game_id)
}
move_log := (game_state).MoveLog
all_rolls := []string{}
for _, tr := range move_log {
roll_strings := []string{"Player: " + tr.PlayerId}
player_name, ok := id_to_name[tr.PlayerId]
if !ok {
log.Println("could not find player_name in id_to_name, player_name set to empty string")
}
for i := 0; i < 3; i++ {
roll_strings = append(roll_strings, fmt.Sprintf("%s:%s : %s", player_name, tr.TurnResult[i][0], tr.TurnResult[i][1]))
}
if tr.IsDead == true || tr.ContinueTurn == false {
turn_end_string := fmt.Sprintf("%s:%s, Total Score: %d, Turn Ended\n", player_name, tr.PlayerId, tr.TotalScore)
roll_strings = append(roll_strings, turn_end_string)
}
if tr.Winner != "" {
winner_string := fmt.Sprintf("Winner: Player: %s", tr.Winner)
roll_strings = append(roll_strings, winner_string)
}
one_roll_string := strings.Join(roll_strings, "\n")
all_rolls = append(all_rolls, one_roll_string)
}
formated_moves := strings.Join(all_rolls, "\n")
fmt.Fprintf(response, formated_moves)
}
func get_n_players_in_game(response http.ResponseWriter, request *http.Request) {
err := request.ParseForm()
if err != nil {
panic(err)
}
game_id_form, _ := request.Form["game_id"]
game_id := game_id_form[0]
game_state, err := dynamo_db_tools.GetGameStateFromDynamoDB(game_id)
if err != nil {
http.Error(response, fmt.Sprintf("Game with id %s not found!, %v", game_id, err), http.StatusBadRequest)
return
} else {
log.Printf("Grabbed game state with id: %s", game_id)
}
fmt.Fprintf(response, "%d", len(game_state.Players))
}
func send_chat_message(response http.ResponseWriter, request *http.Request) {
log.Println("Sending Message")
response.Header().Set("Content-type", "text/plain")
err := request.ParseForm()
if err != nil {
log.Fatal(response, fmt.Sprintf("error parsing url %v", err), 500)
}
chat_id, err := parse_input(request, "chat_id")
if err != nil {
http.Error(response, err.Error(), http.StatusBadRequest)
return
}
player_id, err := parse_input(request, "player")
if err != nil {
http.Error(response, err.Error(), http.StatusBadRequest)
return
}
player_name, ok := id_to_name[player_id]
if !ok {
log.Println("could not find player_name in id_to_name, player_name set to empty string")
}
log.Print("PLAYERS NAME ID: ", player_id)
log.Printf("chat id : %s", chat_id)
zombie_chat, ok := zombie_chats[chat_id]
if !ok {
log.Printf("Could not find chat with id: %s\n", chat_id)
}
body, err := ioutil.ReadAll(io.LimitReader(request.Body, 1048576))
if err != nil {
fmt.Println("Could not parse request body")
}
err = request.Body.Close()
if err != nil {
fmt.Println("Could not close request Body")
}
message_info := map[string]string{}
err = json.Unmarshal(body, &message_info)
if err != nil {
panic(err)
}
message := message_info["message"]
player_message := fmt.Sprintf("%s:%s : %s", player_name, player_id, message)
zombie_chat.ThreadSafeAppend(player_message)
fmt.Fprintf(response, player_message)
}
func receive_all_chat_messages(response http.ResponseWriter, request *http.Request) {
err := request.ParseForm()
if err != nil {
panic(err)
}
chat_id_form, _ := request.Form["chat_id"]
chat_id := chat_id_form[0]
current_chat, ok := zombie_chats[chat_id]
if !ok {
log.Printf("Chat id has not been found")
return
}
var messages_str string
if len((*current_chat).Messages) >= 100 {
messages_str = strings.Join((*current_chat).Messages[len((*current_chat).Messages)-10:], "\n")
} else {
messages_str = strings.Join((*current_chat).Messages, "\n")
}
fmt.Fprintf(response, messages_str)
}
func (i_to_n *id_to_name_type) set_player_name(response http.ResponseWriter, request *http.Request) {
log.Println("Setting Name")
body, err := ioutil.ReadAll(io.LimitReader(request.Body, 1048576))
if err != nil {
log.Println("Could not read Body")
}
err = request.Body.Close()
if err != nil {
log.Println("Could not close Body")
}
name_and_id_info := map[string]string{}
err = json.Unmarshal(body, &name_and_id_info)
if err != nil {
log.Println("Could not Unmarshal Body into name_and_id_info")
}
player_name, ok := name_and_id_info["player_name"]
if !ok {
log.Println("player_name not in name_and_id_info")
}
player_id, ok := name_and_id_info["player_id"]
if !ok {
log.Println("player_id not in name_and_id_info")
}
log.Printf("Adding player_id, player_name: %s -> %s\n", player_id, player_name)
(*i_to_n)[player_id] = player_name
}
func parse_input(request *http.Request, field string) (s string, err error) {
input_array := request.Form[field]
parsed_input := ""
if len(input_array) == 1 {
parsed_input = input_array[0]
} else {
error_message := fmt.Sprintf("Bad input on %s! Received %d inputs, expected only 1", field, len(input_array))
log.Printf(error_message)
return "", errors.New(error_message)
}
return parsed_input, nil
}
func four_dice_roll(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-type", "text/plain")
// Parse URL and POST data into the request.Form
err := request.ParseForm()
if err != nil {
log.Fatal(response, fmt.Sprintf("error parsing url %v", err), 500)
}
num_sides := 6
sides_input := request.Form["sides"]
if len(sides_input) == 1 {
num_sides, _ = strconv.Atoi(sides_input[0])
}
roll_times := 4
roll_times_input := request.Form["rolltimes"]
if len(roll_times_input) == 1 {
roll_times, _ = strconv.Atoi(roll_times_input[0])
}
score := dice.InitDefaultDice(num_sides).RollNTimes(roll_times).SumSides()
roll_prob, prob_lower, prob_higher := statistics.CalcRollProbabilities(score, roll_times, num_sides)
log.Printf("Rolled %d for request: \n\t%v", score, request)
// Actual response sent to web client
fmt.Fprintf(response, "\nRolling dice with %d sides %d times:\n", num_sides, roll_times)
fmt.Fprintf(response, " score : %d\n roll prob : %f\n prob lower : %f\n prob higher : %f\n", score, roll_prob, prob_lower, prob_higher)
}
func roll_dice(response http.ResponseWriter, request *http.Request) {
// Parse URL and POST data into the request.Form
err := request.ParseForm()
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
}
num_sides := 6
sides_input := request.Form["sides"]
if len(sides_input) == 1 {
num_sides, _ = strconv.Atoi(sides_input[0])
}
my_dice := dice.InitDefaultDice(num_sides)
side := my_dice.Roll()
log.Printf("Rolled %d for request: \n\t%v", side.Numerical_value, request)
fmt.Fprintf(response, "%d", side.Numerical_value)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", index)
mux.HandleFunc("/zombie_dice", zombie_game)
mux.HandleFunc("/zombie_dice_multi_player", zombie_game_multi_player)
mux.HandleFunc("/zombie_dice/start_game", start_zombie_dice)
mux.HandleFunc("/zombie_dice_multi_player/start_game", start_zombie_dice)
mux.HandleFunc("/zombie_dice_multi_player/join_game", join_game)
mux.HandleFunc("/zombie_dice/take_turn", take_zombie_dice_turn)
mux.HandleFunc("/zombie_dice_multi_player/take_turn", take_zombie_dice_turn)
mux.HandleFunc("/zombie_dice_multi_player/get_player_turn_results", get_player_turn_results)
mux.HandleFunc("/zombie_dice_multi_player/get_n_players_in_game", get_n_players_in_game)
mux.HandleFunc("/zombie_dice_multi_player/send_chat_message", send_chat_message)
mux.HandleFunc("/zombie_dice_multi_player/receive_all_chat_messages", receive_all_chat_messages)
mux.HandleFunc("/zombie_dice_multi_player/set_player_name", id_to_name.set_player_name)
mux.HandleFunc("/four_dice_roll", four_dice_roll)
mux.HandleFunc("/roll_dice", roll_dice)
log.Printf("Started dumb Dice web server! Try it on http://ip_address:8000")
err := http.ListenAndServe("0.0.0.0:8000", mux)
if err != nil {
log.Fatal(err)
}
}