-
Notifications
You must be signed in to change notification settings - Fork 0
/
gameRoom.go
83 lines (72 loc) · 1.51 KB
/
gameRoom.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
package main
import "strconv"
type GameRoom struct {
// Registered clients.
clients map[*Client]bool
// Inbound messages from the clients.
broadcast chan []byte
// Register requests from the clients.
register chan *Client
// Unregister requests from clients.
unregister chan *Client
key string
}
var rooms map[string]*GameRoom
func newGameRoom(key string) *GameRoom {
println("room created", key)
return &GameRoom{
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
clients: make(map[*Client]bool),
key: key,
}
}
func (gr *GameRoom) startGame() {
var count = 1
for client := range gr.clients {
select {
case client.send <- []byte("start_game:" + strconv.Itoa(count)):
count++
default:
close(client.send)
delete(gr.clients, client)
}
}
}
func (gr *GameRoom) close() {
close(gr.broadcast)
close(gr.register)
close(gr.unregister)
delete(rooms, gr.key)
println("room closed")
}
func (gr *GameRoom) run() {
for {
select {
case client := <-gr.register:
gr.clients[client] = true
if len(gr.clients) == 2 {
gr.startGame()
}
case client := <-gr.unregister:
if _, ok := gr.clients[client]; ok {
delete(gr.clients, client)
close(client.send)
}
if len(gr.clients) == 0 {
gr.close()
return
}
case message := <-gr.broadcast:
for client := range gr.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(gr.clients, client)
}
}
}
}
}