-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameManager.ts
447 lines (390 loc) · 13.7 KB
/
GameManager.ts
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import { BasePlayerData, Game } from './Game';
import { Holdem, HOLDEM_GAME_CONFIG } from './modules/Holdem';
import { Hilar, HILAR_GAME_CONFIG } from './modules/Hilar';
import { Duel, DUEL_GAME_CONFIG } from './modules/Duel';
import { Chat, CHAT_GAME_CONFIG } from './modules/Chat';
import { logger } from '../../utils/logger';
import { JoinCodeGenerator } from './JoinCodeGenerator';
import { SocketClient } from '../live/SocketClient';
import { SocketServer } from '../live/SocketServer';
// The available games to play (must be hard-coded to avoid janky for-loop file imports)
export const availableGames = [
HOLDEM_GAME_CONFIG.friendlyName,
HILAR_GAME_CONFIG.friendlyName,
DUEL_GAME_CONFIG.friendlyName,
CHAT_GAME_CONFIG.friendlyName,
];
// The time players have between creating a game and starting it before the room is closed
const GAME_JOIN_TIMEOUT = 10 * 60 * 1000; // ms
// The time after which, if the server has received no new messages from a game's players, the game will be shut down
const GAME_KEEPALIVE_TIMEOUT = 30 * 60 * 1000;
// The information received by prospective players (those who have not yet joined the game)
export interface OutsiderGameData {
joinCode: string;
numJoined: number;
maxPlayers: number;
friendlyName: string;
creatorDisplayName: string;
}
export class GameManager {
// Map of join codes to games
activeGames: Map<string, Game<BasePlayerData>> = new Map();
joinCodeGenerator: JoinCodeGenerator = new JoinCodeGenerator();
constructor() {}
/**
* Attempts to join a game
* @param joinCode The join code of the game to join
* @param player The player attempting to join the game
* @param isHost Whether the player joining is the host
* @returns Whether the player successfully joined
*/
async joinGame(joinCode: string, player: SocketClient, isHost?: boolean): Promise<boolean> {
// If the player is already in a game
if (this.playerInGame(player.user._id.toString())) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'JOIN',
message: 'Cannot join game; player is already in game',
});
return false;
}
const game = this.activeGames.get(joinCode);
// If the game doesn't exist
if (!game) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'JOIN',
message: `Game '${joinCode}' does not exist`,
});
return false;
}
// If the game is full
if (game.players.size >= game.gameConfig.maxPlayers) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'JOIN',
message: 'Game is full',
});
return false;
}
// If the game has already started and the player can't join after it starts
if (game.hasBegun && !game.gameConfig.canJoinAfterBegin) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'JOIN',
message: `Game has already begun and doesn't permit joining after it starts`,
});
return false;
}
// No errors, join the game
game.addPlayer(player.user._id.toString(), player.user.username);
// If the game has already started
if (game.hasBegun) {
// Add the event listeners for the new player
game.addHandlers(player.user._id.toString(), player);
}
player.socket.emit('gameInfo', {
gameId: game.gameConfig.gameId,
joinCode: game.joinCode,
isHost: isHost || false,
hasBegun: game.hasBegun,
});
game.broadcastPlayers();
return true;
}
/**
* Attempt to reconnect a player to a game they're currently in
*/
async attemptRejoin(player: SocketClient): Promise<boolean> {
const game = this.getPlayerGame(player.user._id.toString());
// If the game doesn't exist, do nothing
if (!game) return false;
// Add the event listeners to the new socket
game.addHandlers(player.user._id.toString(), player);
// Send the game info to the player
player.socket.emit('gameInfo', {
gameId: game.gameConfig.gameId,
joinCode: game.joinCode,
isHost: game.creatorId === player.user._id.toString(),
hasBegun: game.hasBegun,
});
// Send the game players to the player
game.sendPlayersTo(player.user._id.toString());
return true;
}
/**
* Attempts to begin a game
* @param player The player attempting to begin the game
* @returns Whether the game started
*/
async beginGame(player: SocketClient): Promise<boolean> {
const game = this.getPlayerGame(player.user._id.toString());
// If the game doesn't exist
if (!game) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'BEGIN',
message: 'Game does not exist or player is not in a game',
});
return false;
}
// If the player is not the creator
if (game.creatorId !== player.user._id.toString()) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'BEGIN',
message: 'Player attempting to begin game is not creator',
});
return false;
}
// If the game is too small
if (game.players.size < game.gameConfig.minPlayers) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'BEGIN',
message: 'Game is too small',
});
return false;
}
game.beginGame();
return true;
}
/**
* Attempts to create a game
* @param gameId The ID of the game
* @param creator The user trying to create the game
* @param server The SocketServer the game will associate with
* @returns Whether the game was created successfully
*/
async createGame(gameId: string, creator: SocketClient, server: SocketServer): Promise<boolean> {
// If the player is already in a game
if (this.playerInGame(creator.user._id.toString())) {
// Send the player an error message
creator.socket.emit('gameError', {
module: 'JOIN',
message: 'Cannot join game; player is already in game',
});
return false;
}
const joinCode = this.joinCodeGenerator.generateCode();
let game;
// Select the game from the available games
if (gameId === 'HOLDEM') {
game = new Holdem(joinCode, creator.user._id.toString(), (id: string) => server.clients.get(id), () => this.endGame(joinCode));
}
else if (gameId === 'HILAR') {
game = new Hilar(joinCode, creator.user._id.toString(), (id: string) => server.clients.get(id), () => this.endGame(joinCode));
}
else if (gameId === 'DUEL') {
game = new Duel(joinCode, creator.user._id.toString(), (id: string) => server.clients.get(id), () => this.endGame(joinCode));
}
else if (gameId === 'CHAT') {
game = new Chat(joinCode, creator.user._id.toString(), (id: string) => server.clients.get(id), () => this.endGame(joinCode));
}
else {
creator.socket.emit('gameError', {
message: 'You did not select a valid game.',
});
return false;
}
// // Send the game data to the creator (removed b/c duplicate)
// creator.socket.emit('gameInfo', {
// gameId,
// joinCode,
// isHost: true,
// });
// Add the game to the active games list
this.activeGames.set(joinCode, game);
// Add the player to the game
this.joinGame(joinCode, creator, true);
// Set the join timeout to avoid
setTimeout(() => {
// If the game has already begun, do nothing
if (game.hasBegun) return;
// Don't start the game
game.sendAll('gameError', {
message: `Game timed out: admin didn't start the game before the ${GAME_JOIN_TIMEOUT / (60 * 1000)} minute time limit expired.`,
});
// Log to the debug log that the game failed
logger.debug(`Game ${game.joinCode} (type ${game.gameConfig.gameId}) failed due to timeout.`)
// Cancel the game
this.endGame(joinCode);
return;
// // If there aren't enough players
// if (game.players.size < game.gameConfig.minPlayers) {
// // Don't start the game
// game.sendAll('gameError', {
// message: `Not enough players in the game at timeout. Need ${game.gameConfig.minPlayers}, have ${game.players.size}.`,
// });
// // Log to the debug log that the game failed
// logger.debug(`Game ${game.joinCode} (type ${game.gameConfig.gameId}) failed due to timeout.`)
// // Cancel the game
// this.destroyGame(joinCode);
// return;
// }
// // Start the game with the current number of players
// game.beginGame();
}, GAME_JOIN_TIMEOUT);
return true;
}
/**
* Destroys a game
* @param joinCode The join code of the game to destroy
*/
endGame(joinCode: string) {
logger.debug(`Deleted game ${joinCode}.`);
// Attempt to fetch the game
const game = this.activeGames.get(joinCode);
// If it doesn't exist, do nothing
if (!game) return;
// Send the game closure message
game.sendAll('gameEnd', {
message: 'The game has ended.',
});
// Delete the game
this.activeGames.delete(game.joinCode);
}
/**
* Voluntarily terminates a game
* @returns Whether the game was successfully terminated or not
*/
async terminateGame(player: SocketClient): Promise<boolean> {
const game = this.getPlayerGame(player.user._id.toString());
// If the game doesn't exist
if (!game) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'TERMINATE',
message: 'Game does not exist or player is not in a game',
});
return false;
}
// If the player is not the creator
if (game.creatorId !== player.user._id.toString()) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'TERMINATE',
message: 'Player attempting to terminate game is not creator',
});
return false;
}
// Send the terminate message
game.sendAll('gameEnd', {
message: 'The host has terminated the game.',
});
// Delete the game
this.activeGames.delete(game.joinCode);
return true;
}
/**
* Voluntarily leaves a game
* @returns Whether the user left the game
*/
async leaveGame(player: SocketClient): Promise<boolean> {
const game = this.getPlayerGame(player.user._id.toString());
// If the game doesn't exist
if (!game) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'LEAVE',
message: 'Game does not exist or player is not in a game',
});
return false;
}
// If the game is not able to be left
if (!game.gameConfig.canLeaveAfterBegin) {
// Send the player an error message
player.socket.emit('gameError', {
module: 'LEAVE',
message: 'Game does not allow leaving early!',
});
return false;
}
// Remove the player from the game
game.removePlayer(player.user._id.toString());
// If there are no players left in the game
if (game.players.size === 0) {
// End the game
logger.debug(`Will delete game ${game.joinCode} because it has no players.`);
this.endGame(game.joinCode);
} else {
// Otherwise, update the game's players
game.broadcastPlayers();
}
// Tell the client they left the game
player.socket.emit('gameLeave', {
message: `You have left this game.`
});
return true;
}
/**
* Gets the game a player is currently in
* @param userId The userId of the player
* @returns The game the player is in or null if no game found
*/
getPlayerGame(userId: string): Game<BasePlayerData> | null {
for (const g of this.activeGames.values()) {
if (g.players.has(userId)) return g;
}
return null;
}
/**
* Checks if a player is already in an active game
* @param userId The userId of the player to check
* @returns Whether the player is currently in a game
*/
playerInGame(userId: string): boolean {
for (const game of this.activeGames.values()) {
if (game.players.has(userId)) return true;
}
return false;
}
/**
* Gets a list of games containing one or more players from a list of userIds
* @param userIds The list of users to check
* @returns OutsiderGameData for each matching game
*/
getGamesWithPlayers(userIds: string[]): OutsiderGameData[] {
const result: OutsiderGameData[] = [];
// For each game
for (const game of this.activeGames) {
let add = false;
// For each user
for (const player of userIds) {
// If the user is in the game, add it to the list and don't bother checking the rest
if (game[1].players.has(player)) {
add = true;
break;
}
}
if (add) {
// Add the game
result.push({
joinCode: game[0],
numJoined: game[1].players.size,
maxPlayers: game[1].gameConfig.maxPlayers,
friendlyName: game[1].gameConfig.friendlyName,
creatorDisplayName: game[1].players.get(game[1].creatorId)?.displayName || `Unknown Player`,
});
}
}
return result;
}
/**
* Terminates all games that haven't had a message in GAME_KEEPALIVE_TIMEOUT ms
*/
purge(): number {
let numPurged = 0;
// For each game
for (const [code, game] of this.activeGames) {
// If its last message was more than GAME_KEEPALIVE_TIMEOUT ms ago
if (Date.now() - game.lastMessage > GAME_KEEPALIVE_TIMEOUT) {
logger.debug(`Will delete game ${code} because it has been more than ${GAME_KEEPALIVE_TIMEOUT} ms since its last message.`);
// Terminate the game
this.endGame(code);
numPurged++;
}
}
return numPurged;
}
}