Add code to handle the HostGame event
This commit is contained in:
parent
11c671ef25
commit
8a9adb21f0
1 changed files with 53 additions and 0 deletions
|
|
@ -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}`
|
||||
})
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue