Implement a primitive join lobby method
This commit is contained in:
parent
5da30d572f
commit
88b07fdf1d
1 changed files with 81 additions and 0 deletions
81
server/src/events/lobby/players/join.ts
Normal file
81
server/src/events/lobby/players/join.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { colours, IJoinLobby, spaceships, Status } from "common";
|
||||
import { WebsocketEvent } from "@/types/WebsocketEvent";
|
||||
import { Player } from "@/objects/Player";
|
||||
import { games, log } from "@/main";
|
||||
|
||||
const data: WebsocketEvent = {
|
||||
name: "req:lobby.players.join",
|
||||
handler(_, socket, data: IJoinLobby) {
|
||||
try {
|
||||
log.debug(`Attempting to join a game`);
|
||||
|
||||
let gID = data.game_code;
|
||||
let name = data.name;
|
||||
|
||||
let game = games.get(gID);
|
||||
|
||||
|
||||
// Ensure the user provided a game code that could be found
|
||||
if (!game) {
|
||||
socket.emit(`res:lobby.players.join`, {
|
||||
status: Status.NotFound,
|
||||
message: `Game could not be found with that game code`,
|
||||
});
|
||||
return;
|
||||
};
|
||||
|
||||
let sameName = game.players.find(p => p.name == name);
|
||||
if (sameName) {
|
||||
socket.emit(`res:lobby.players.join`, {
|
||||
status: Status.Forbidden,
|
||||
message: `That name is already taken in the lobby, choose another name!`,
|
||||
});
|
||||
return;
|
||||
};
|
||||
|
||||
// Ensure the game is currently in the lobby state
|
||||
if (game.status !== `lobby`) {
|
||||
socket.emit(`res:lobby.players.join`, {
|
||||
status: Status.Forbidden,
|
||||
message: `Can't join a game that is in-progress.`,
|
||||
});
|
||||
return;
|
||||
};
|
||||
|
||||
let usedColours = game.players.map(p => p.colour);
|
||||
let newPlayerColour = null;
|
||||
do {
|
||||
newPlayerColour = colours[Math.floor(Math.random() * colours.length)];
|
||||
} while (usedColours.includes(newPlayerColour));
|
||||
|
||||
let player = new Player(socket, {
|
||||
name,
|
||||
colour: newPlayerColour,
|
||||
ship: spaceships[0],
|
||||
host: false,
|
||||
});
|
||||
|
||||
game.players.push(player);
|
||||
game.log.info(`${name} joined the game`);
|
||||
socket.join(game.id);
|
||||
|
||||
let playerData = game.players.map(p => p.json());
|
||||
socket.emit(`res:lobby.players.join`, {
|
||||
status: Status.Success,
|
||||
game_code: game.id,
|
||||
players: playerData,
|
||||
});
|
||||
socket.to(game.id).emit(`res:lobby.info`, {
|
||||
status: Status.Success,
|
||||
players: playerData,
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
socket.emit(`res:error`, {
|
||||
status: Status.UnknownError,
|
||||
message: err.message,
|
||||
});
|
||||
};
|
||||
},
|
||||
};
|
||||
export default data;
|
||||
Loading…
Add table
Add a link
Reference in a new issue