49 lines
No EOL
1.5 KiB
TypeScript
49 lines
No EOL
1.5 KiB
TypeScript
/*
|
|
Starts a game on the server, this also acts as the `JoinGame` event for the
|
|
host, except that it doesn't send any events out to other players as there
|
|
are none yet.
|
|
|
|
Emissions:
|
|
HostInformation - Data containing if the game created successfully or not
|
|
and the game code for the game if it was successful.
|
|
|
|
Client Side: After the host receives the `HostInformation` event, the Query
|
|
String parameters should be updated with the Websocket URI and the game code so
|
|
that the host is able to just send that to the other players
|
|
*/
|
|
import { Socket } from 'socket.io';
|
|
import { Game } from '../utils/Game';
|
|
import { active_games, log } from '../main';
|
|
import { generate_game_code } from '../utils/gamecode';
|
|
|
|
export const HostGame = (socket: Socket, data: HostGame) => {
|
|
try {
|
|
|
|
// Get a game code that is not in use to prevent join conflicts
|
|
let game_code = generate_game_code();
|
|
while (Object.keys(active_games).includes(game_code)) {
|
|
game_code = generate_game_code();
|
|
}
|
|
|
|
// Add the user to the game's room
|
|
socket.join(game_code);
|
|
|
|
// Create the game
|
|
let game = new Game(game_code);
|
|
game.add_player(data.username, socket.id, true);
|
|
active_games[game_code] = game;
|
|
log.info(`${data.username} created a game. (Gamecode: ${game_code})`);
|
|
|
|
// Respond to client
|
|
socket.emit(`HostInformation`, {
|
|
success: true,
|
|
game_code: game_code
|
|
});
|
|
} catch (err) {
|
|
log.prettyError(err);
|
|
socket.emit(`HostInformation`, {
|
|
success: false,
|
|
error: `${err.name}: ${err.message}`
|
|
});
|
|
}
|
|
}; |