forked from gophergala2016/spacegophers
/
game_hub.go
59 lines (44 loc) · 1.09 KB
/
game_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
package main
import "github.com/apex/log"
// NewGameHub creates a new GameHub for a given log contenxt.
func NewGameHub(ctx log.Interface) GameHub {
return GameHub{
Log: ctx.WithField("module", "GameHub"),
games: make(map[string]Game),
register: make(chan GameRegistrationRequest),
}
}
// GameHub manages all games and users websocket connections.
type GameHub struct {
// logging interface
Log log.Interface
// games stored based on the game id
games map[string]Game
// Register requests from the users.
register chan GameRegistrationRequest
}
func (gh *GameHub) run() {
gh.Log.Debug("running")
for {
select {
case grr := <-gh.register:
ctx := gh.Log.WithFields(log.Fields{
"gameID": grr.GameID,
})
ctx.Debug("register")
game, ok := gh.games[grr.GameID]
// game not found, create it!
if !ok {
ctx.Debug("new game")
game = NewGame(gh.Log, grr.GameID)
// start the game!
go game.Run()
gh.games[grr.GameID] = game
} else {
ctx.Debug("existing game")
}
// register the user to the game
game.register <- grr.User
}
}
}