Implement the JoinGame event

This commit is contained in:
Oliver-Akins 2020-10-02 16:52:47 -06:00
parent e45a1a4b89
commit bdc7bccfcc

View file

@ -9,7 +9,56 @@ Emissions:
players and that they were added to the game either successfully or not players and that they were added to the game either successfully or not
*/ */
import { Socket } from 'socket.io'; import { Socket } from 'socket.io';
import { active_games, log } from '../main';
export const JoinGame = (socket: Socket, data: JoinGame) => { export const JoinGame = (socket: Socket, data: JoinGame) => {
console.log(`User: ${data.username} (${data.game_code})`); try {
console.log(`Joining a game`); // Check if it's an active game
if (!Object.keys(active_games).includes(data.game_code)) {
log.debug(`Can't find an active game with code: ${data.game_code}`);
socket.emit(`GameJoined`, {
success: false,
message: `Could not find an active game with that game code.`
});
return;
};
let game = active_games[data.game_code];
if (game.status !== `lobby`) {
log.debug(`Cannot join the game ${game.code}. (state=${game.status})`)
socket.emit(`GameJoined`, {
success: false,
message: `That game cannot be joined because it is not in the lobby.`,
});
return;
}
// Ensure username is not already taken
if (Object.keys(game.players).includes(data.username)) {
socket.emit(`GameJoined`, {
success: false,
message: `That username is already taken, please try another.`,
});
return;
};
game.add_player(data.username);
// Alert player who joined
socket.emit(`GameJoined`, {
success: true,
players: game.players,
})
// Alert existing players about new player
socket.broadcast.emit(`NewPlayer`, {
game_code: data.game_code,
player: data.username,
});
} catch (err) {
socket.emit(`GameJoined`, {
success: false,
message: `${err.name}: ${err.message}`,
})
}
}; };