/
gamehub.go
318 lines (270 loc) · 6.45 KB
/
gamehub.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package main
import (
"fmt"
"github.com/dchest/uniuri"
"github.com/sqp/godock/libs/log"
"launchpad.net/rjson"
)
type Message struct {
Operation string
Sender string
RoomID string
Message string
MessageArray []string
MessageMap string
}
type GameHub struct {
// Registered players
players map[string]*Player
// Registered connections
connections map[*connection]bool
// Inbound messages from the connections
broadcast chan string
// Register requests from the connections
register chan *Player
// Unregister requests from the connections
unregister chan *Player
// Rooms
rooms map[string]*GameRoom
lobby *GameRoom
}
// singleton
var gamehub = GameHub{
players: make(map[string]*Player),
broadcast: make(chan string),
register: make(chan *Player),
unregister: make(chan *Player),
connections: make(map[*connection]bool),
rooms: make(map[string]*GameRoom),
}
func (h *GameHub) findConnectionForPlayer(playerId string) *connection {
p := h.players[playerId]
if p != nil {
return p.conn
}
return nil
}
func (h *GameHub) findRoomById(roomId string) *GameRoom {
r := h.rooms[roomId]
if r != nil {
return r
}
return nil
}
func (h *GameHub) handleMessage(msg string) bool {
var conn *connection
var player *Player
var handledMessage bool
var data Message
err := rjson.Unmarshal([]byte(msg), &data)
if err != nil {
fmt.Println("error:", err)
}
log.Debug(msg)
// Get sender's connection
sender := data.Sender
if sender != "" && sender != "Server" {
player = h.players[sender]
conn = player.conn
}
switch data.Operation {
case "CreateRoom":
fmt.Println("CreateRoom")
r := &GameRoom{players: make(map[string]bool)}
r.roomId = uniuri.New()
h.rooms[r.roomId] = r
fmt.Println(h.getRoomList())
// message to say room was created
// move player to room
case "ChangeNick":
msg := player.ChangeNick(data.Message)
h.sendBroadcastMessage(msg, "Lobby")
// Send message to room saying nick has changed
handledMessage = true
case "JoinRoom":
fmt.Println("JoinRoom")
// TODO: Check if player is already in game room
// Store gameroom data also in player object?
roomId := data.Message
room, err := h.rooms[roomId]
if err != false {
room.addPlayer(player)
log.Debug("Player " + player.id + " added to room " + roomId)
fmt.Println(room.players)
}
case "LeaveRoom":
fmt.Println("LeaveRoom")
// TODO: Verify player is already in game room
roomId := data.Message
room, err := h.rooms[roomId]
if err != false {
room.removePlayer(player)
log.Debug("Player " + player.id + " left room " + roomId)
fmt.Println(room.players)
}
case "StartGame":
roomId := data.RoomID
room := h.rooms[roomId]
room.game.startGame(room, h)
case "GetGameTypes":
conn.send <- h.getGameTypes()
handledMessage = true
case "GetPlayerList":
for _, v := range h.players {
fmt.Println(v)
}
case "GetRoomList":
conn.send <- h.getRoomList()
handledMessage = true
default:
// Send to specific room for handling
room := h.findRoomById(data.RoomID)
if room != nil {
fmt.Println(room)
if room.game != nil {
room.game.HandleGameMessage(msg, h)
}
}
}
fmt.Println(data.Message)
return handledMessage
}
func (h *GameHub) sendBroadcastMessage(msg Message, roomId string) {
room := h.rooms[roomId]
b, err2 := rjson.Marshal(msg)
if err2 != nil {
return
}
for k, _ := range room.players {
h.players[k].conn.send <- string(b)
}
}
func (h *GameHub) getRoomList() string {
rooms := h.rooms
roomList := make([]string, len(rooms))
i := 0
for k, _ := range rooms {
roomList[i] = k
i++
}
msg := Message{
Operation: "GetRoomList",
Sender: "Server",
RoomID: "",
MessageArray: roomList,
}
b, err := rjson.Marshal(msg)
if err != nil {
}
return string(b)
}
func (h *GameHub) getGameTypes() string {
gameTypes := []string{"BlackJack", "TicTacToe", "QuizBowl"}
msg := Message{
Operation: "GetGameTypes",
Sender: "Server",
RoomID: "",
MessageArray: gameTypes,
}
b, err := rjson.Marshal(msg)
if err != nil {
}
return string(b)
}
func (h *GameHub) createRoom(gameType string, playerId string) {
r := &GameRoom{roomId: uniuri.New()}
// Add room to game hub
h.rooms[r.roomId] = r
// Move calling player to that room
r.players[playerId] = true
}
func (h *GameHub) createDemoRooms() {
h.lobby = &GameRoom{players: make(map[string]bool)}
h.lobby.roomId = "Lobby"
h.lobby.game = nil
h.rooms[h.lobby.roomId] = h.lobby
// QuizBowl Room
quizbowl := &GameRoom{players: make(map[string]bool)}
quizbowl.roomId = "QuizBowl"
quizbowl.game = &QuizBowlGame{}
quizbowl.game.init()
h.rooms[quizbowl.roomId] = quizbowl
// Racing Room
racing := &GameRoom{players: make(map[string]bool)}
racing.roomId = "Racing"
h.rooms[racing.roomId] = racing
}
func (h *GameHub) Run() {
log.SetPrefix("GameHub")
log.SetDebug(true)
log.Info("Started GameHub")
h.createDemoRooms()
//InitTest()
h.TestQuiz()
for {
select {
// Player entered lobby.
case p := <-h.register:
h.players[p.id] = p
h.connections[p.conn] = true
h.lobby.addPlayer(p)
log.Debug("Added Player " + p.id)
// Player exited website.
case p := <-h.unregister:
delete(h.players, p.id)
delete(h.connections, p.conn)
close(p.conn.send)
log.Debug("Player " + p.id + " exited")
// Distribute broadcast messages to all connections.
case m := <-h.broadcast:
if h.handleMessage(m) != true {
for c := range h.connections {
select {
case c.send <- m:
default:
delete(h.connections, c)
close(c.send)
go c.ws.Close()
}
}
}
}
}
}
// Test Quizbowl
func (h *GameHub) TestQuiz() {
h.lobby.game = &RacingGame{}
h.lobby.game.init()
h.lobby.game.startGame(h.lobby, h)
/* room := h.rooms["QuizBowl"]
g := room.game
g.init()
go func() {
quizbowlgame := g.(*QuizBowlGame)
for _, q := range quizbowlgame.questions {
time.Sleep(15 * time.Second)
quizbowlgame.SendQuestion(room.roomId, q.QuestionId, h)
}
}()*/
}
//Sample setup of TicTacToe Board and AI
/*
func InitTest() {
ai := &TicTacToeAI{compLetter: "X"}
ai.initBoard()
ai.PrintBoard()
//ai.completeMove("X", []int{0,0})
ai.PrintBoard()
ai.compLetter = "X"
f := ai.miniMax(5, "X")
fmt.Println(f)
defer ai.completeMove("X", []int{f[1], f[2]})
ai.PrintBoard()
//moves := ai.generateMovesFromBoard("O")
//fmt.Println(moves)
// x := ai.pickRandomMove("O")
//ai.completeMove("O", x)
//ai.PrintBoard()
//fmt.Println(ai.checkForWin())
}
*/