-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
76 lines (60 loc) · 1.34 KB
/
handler.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
package kroki
import (
"log"
"math/rand"
"github.com/gorilla/websocket"
)
type Message struct {
Event string `json:"e,omitempty"`
Payload interface{} `json:"p,omitempty"`
}
func (s Server) readLoop(conn *websocket.Conn) {
s.numClients.Inc()
defer s.numClients.Dec()
var game *Game
player := Player{conn: conn, connID: rand.Int()}
for {
var msg Message
if err := conn.ReadJSON(&msg); err != nil {
if !websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
log.Println("Error reading message:", err)
}
return
}
log.Printf("message: %#v", msg)
switch msg.Event {
case "setName":
player.Name = msg.Payload.(string)
case "setPlayerID":
player.ID = msg.Payload.(string)
case "joinGame":
game = s.handleJoinGame(msg)
game.Join(&player)
defer game.Leave(&player)
game.Broadcast()
case "press":
id := int(msg.Payload.(float64))
game.Teeth[id] = true
if id == game.BadTooth {
game.WhoLost = player.ID
}
game.Broadcast()
case "restart":
game.Restart()
game.Broadcast()
default:
log.Printf("unknown event: %v", msg)
}
}
}
func (s Server) handleJoinGame(msg Message) *Game {
var gid string
if msg.Payload != nil {
gid = msg.Payload.(string)
}
game, err := s.games.GetOrCreate(gid)
if err != nil {
log.Panicln(err)
}
return game
}