-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathroom.go
97 lines (78 loc) · 1.66 KB
/
room.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
package main
import (
"github.com/alehano/wsgame/game"
"github.com/alehano/wsgame/utils"
"log"
)
var allRooms = make(map[string]*room)
var freeRooms = make(map[string]*room)
var roomsCount int
type room struct {
name string
// Registered connections.
playerConns map[*playerConn]bool
// Update state for all conn.
updateAll chan bool
// Register requests from the connections.
join chan *playerConn
// Unregister requests from connections.
leave chan *playerConn
}
// Run the room in goroutine
func (r *room) run() {
for {
select {
case c := <-r.join:
r.playerConns[c] = true
r.updateAllPlayers()
// if room is full - delete from freeRooms
if len(r.playerConns) == 2 {
delete(freeRooms, r.name)
// pair players
var p []*game.Player
for k, _ := range r.playerConns {
p = append(p, k.Player)
}
game.PairPlayers(p[0], p[1])
}
case c := <-r.leave:
c.GiveUp()
r.updateAllPlayers()
delete(r.playerConns, c)
if len(r.playerConns) == 0 {
goto Exit
}
case <-r.updateAll:
r.updateAllPlayers()
}
}
Exit:
// delete room
delete(allRooms, r.name)
delete(freeRooms, r.name)
roomsCount -= 1
log.Print("Room closed:", r.name)
}
func (r *room) updateAllPlayers() {
for c := range r.playerConns {
c.sendState()
}
}
func NewRoom(name string) *room {
if name == "" {
name = utils.RandString(16)
}
room := &room{
name: name,
playerConns: make(map[*playerConn]bool),
updateAll: make(chan bool),
join: make(chan *playerConn),
leave: make(chan *playerConn),
}
allRooms[name] = room
freeRooms[name] = room
// run room
go room.run()
roomsCount += 1
return room
}