import {utility} from './util.js'
const socket = io();
let clock;
let currentGame = null;
let cardFlippedOver = false;
let cardRendered = false;
// respond to the game state received from the server
socket.on('state', function(game) {
currentGame = game;
if (game.message) {
document.getElementById("message-box").innerText = game.message;
}
buildGameBasedOnState();
});
function buildGameBasedOnState() {
switch(currentGame.state) {
case "lobby":
renderLobby();
break;
case "started":
renderGame();
break;
case "ended":
renderEndSplash();
break;
default:
break;
}
}
function launchGame() {
randomlyDealCardsToPlayers();
socket.emit('startGame', { players: currentGame.players , code: currentGame.accessCode});
}
function randomlyDealCardsToPlayers() {
for (let player of currentGame.players) {
player.card = drawRandomCard();
}
}
function drawRandomCard() {
return currentGame.deck.splice(utility.getRandomInt(currentGame.deck.length) - 1, 1)[0];
}
function getLiveCount() {
let liveCount = 0;
for (let player of currentGame.players) {
if (!player.dead) {
liveCount ++;
}
}
return liveCount;
}
function renderEndSplash() {
document.getElementById("game-container").classList.add("hidden");
document.getElementById("message-box").classList.add("hidden");
currentGame.winningTeam === "village"
? document.getElementById("end-container").innerHTML ="
";
document.getElementById("lobby-container").appendChild(subHeader);
}
// Render all players that are new
let i = 1;
for (let player of currentGame.players) {
if(!document.getElementById("player-" + i)) {
const playerContainer = document.createElement("div");
player.id === sessionStorage.getItem("id") ?
playerContainer.setAttribute("class", "lobby-player highlighted")
: playerContainer.setAttribute("class", "lobby-player");
playerContainer.setAttribute("id", "player-" + i);
playerContainer.innerHTML = "
" + player.name + "
";
document.getElementById("lobby-container").appendChild(playerContainer);
document.getElementById("join-count").innerText = currentGame.players.length.toString();
}
i ++;
}
// display the launch button if the player is the host
if (sessionStorage.getItem("host")) {
if (currentGame.players.length === currentGame.size) {
document.getElementById("launch").innerHTML = "";
document.getElementById("launch").addEventListener("click", launchGame);
} else {
document.getElementById("launch").innerHTML = "";
}
} else {
document.getElementById("launch").innerHTML = "
The host will start the game.
"
}
}
// request the current state of the game from the server
window.onload = function() {
socket.emit('requestState', {code: sessionStorage.getItem("code")});
};