Add code to handle the HostGame event

This commit is contained in:
Oliver-Akins 2020-09-28 23:05:43 -06:00
parent 11c671ef25
commit 8a9adb21f0

View file

@ -0,0 +1,53 @@
/*
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.
This will also emit the `HostInformation` event to the host client, which will
allow us to send them information about what the game code is
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 * as db from '../utils/db';
import { Socket } from 'socket.io';
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 (db.exists(game_code)) {
game_code = generate_game_code();
}
// Init the database
db.create(game_code);
let db_init: database = {
state: `lobby`,
host: data.username,
players: {},
game_code: game_code
};
db_init.players[data.username] = { host: true, hitler: false, president: false, chancellor: false };
db.write(game_code, db_init, `\t`);
console.log(`${data.username} created a game. (Gamecode: ${game_code})`);
// Respond to client
socket.emit(`HostInformation`, {
success: true,
game_code: game_code,
players: [data.username]
});
} catch (err) {
// Let client know an error occured
socket.emit(`HostInformation`, {
success: false,
error: `${err.name}: ${err.message}`
})
}
};