-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
98 lines (90 loc) · 1.84 KB
/
server.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
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"time"
)
type server struct {
game *Game
port string
router *http.ServeMux
clients []*client
msg chan []byte
server *http.Server
}
func newServer() *server {
return &server{
game: newGame(),
port: *flagPort,
router: http.NewServeMux(),
server: &http.Server{
Addr: *flagPort,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
},
}
}
func (s *server) run() error {
s.routes()
s.server.Handler = s.router
return s.server.ListenAndServe()
}
func (s *server) sendState() {
for _, c := range s.clients {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
s.game.State()
ps, _ := s.playerState(c.playerID)
err := enc.Encode(ps)
if err != nil {
log.Println("sendState encoding error:", err)
}
b := buf.Bytes()
c.messages <- b
}
}
type PlayerState struct {
Player Player `json:"player"`
Oponents []Player `json:"oponent"`
HeapHead Card `json:"heap_head"`
}
func (s *server) playerState(id string) (PlayerState, bool) {
ps := PlayerState{}
found := false
s.game.State()
for _, p := range s.game.Players {
switch p.ID {
case id:
ps.Player = *p
if p.Active {
ps.Player.Class = "active"
}
found = true
default:
// Hide oponent cards and id
oponent := Player{
ID: "",
Name: p.Name,
Cards: &CardStack{
Cards: make([]Card, len(p.Cards.Cards)),
},
}
if p.Active {
oponent.Class = "active"
}
for i := range p.Cards.Cards {
oponent.Cards.Cards[i].Color = "back"
}
ps.Oponents = append(ps.Oponents, oponent)
}
}
ps.HeapHead = s.game.HeapHead
// Just show the label for the HeapHead
// so 9 - 3 is shown instead of the value
ps.HeapHead.Value = ps.HeapHead.Label
return ps, found
}