diff --git a/src/events/HostGame.ts b/src/events/HostGame.ts index e69de29..f4659c9 100644 --- a/src/events/HostGame.ts +++ b/src/events/HostGame.ts @@ -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}` + }) + } +}; \ No newline at end of file