diff --git a/src/events/JoinGame.ts b/src/events/JoinGame.ts index 5895d7c..456e32f 100644 --- a/src/events/JoinGame.ts +++ b/src/events/JoinGame.ts @@ -25,21 +25,40 @@ export const JoinGame = (io: Server, socket: Socket, data: JoinGame) => { let game = active_games[data.game_code]; - if (game.status !== `lobby`) { - log.warn(`Cannot join the game ${game.code}. (state=${game.status})`); + + // Ensure username is not already taken + if (game.players[data.username] != null && game.status === `lobby`) { + log.info(`${data.username} tried joining game ${game.code} but the name is already taken.`); socket.emit(`GameJoined`, { success: false, - message: `That game cannot be joined because it is not in the lobby.`, + message: `That username is already taken, please try another.`, }); return; }; - // Ensure username is not already taken - if (Object.keys(game.players).includes(data.username)) { - log.warn(`${data.username} tried joining game ${game.code} but the name is already taken.`); + + // Check if the user can join the game + if (game.status !== `lobby`) { + + // Re-joining a game + if (game.players[data.username] != null) { + log.info(`${data.username} rejoined game ${game.code}`); + + // Update all the info that we save about the player + game.update_socket(data.username, socket.id); + socket.join(game.code); + socket.emit(`GameJoined`, { + success: true, + rejoin: true, + uuid: game.players[data.username].id, + }); + return; + }; + + log.info(`${data.username} could not join game ${game.code}(status=${game.status})`); socket.emit(`GameJoined`, { success: false, - message: `That username is already taken, please try another.`, + message: `Cannot join a game that isn't in the lobby.`, }); return; }; @@ -60,6 +79,7 @@ export const JoinGame = (io: Server, socket: Socket, data: JoinGame) => { // Alert player who joined socket.emit(`GameJoined`, { success: true, + rejoin: false, uuid: uuid, });