-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.go
81 lines (75 loc) · 1.63 KB
/
hub.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
package main
import (
"encoding/json"
"fmt"
"sync"
"github.com/gorilla/websocket"
)
type Hub struct {
rooms map[*Room]bool
register chan *websocket.Conn
waitingRoom struct {
sync.Mutex
room *Room
waiting bool
}
delete chan *Room
}
type gameMessage struct {
Event string `json:"event"`
Data interface{} `json:"data"`
}
func newHub() *Hub {
return &Hub{
register: make(chan *websocket.Conn, 100),
rooms: make(map[*Room]bool),
delete: make(chan *Room, 20),
}
}
func (h *Hub) run() {
for {
select {
case conn := <-h.register:
client := &Client{hub: h, conn: conn, send: make(chan []byte, 256)}
h.waitingRoom.Lock()
if h.waitingRoom.waiting {
h.waitingRoom.waiting = false
room := h.waitingRoom.room
room.players[client] = true
client.room = room
go client.writePump()
go client.readPump()
i := 1
for client := range room.players {
msg := &gameMessage{Event: "turn", Data: i}
val, err := json.Marshal(msg)
if err != nil {
// TODO could improve further if a player does not get there turn they could hold the game hostage
fmt.Print(err.Error())
} else {
client.send <- val
}
i++
}
} else {
h.waitingRoom.waiting = true
room := newRoom(h)
h.waitingRoom.room = room
client.room = room
room.players[client] = true
go room.run()
h.rooms[room] = true
go client.writePump()
go client.readPump()
}
h.waitingRoom.Unlock()
case room := <-h.delete:
h.waitingRoom.Lock()
for p := range room.players {
p.conn.Close()
}
delete(h.rooms, room)
h.waitingRoom.Unlock()
}
}
}