From 2debf7be358d423ce9dde34681424beeec6d3be8 Mon Sep 17 00:00:00 2001 From: Alec Date: Fri, 3 Dec 2021 04:23:15 -0500 Subject: [PATCH] simpler routing, fix socket reconnection bug, expand mod view --- client/config/globals.js | 1 + client/modules/GameStateRenderer.js | 31 +++++++- client/modules/Templates.js | 32 ++++++-- client/modules/Timer.js | 8 +- client/modules/Toast.js | 22 ++++-- client/scripts/game.js | 36 ++++++--- client/styles/game.css | 100 ++++++++++++++++++++++-- client/views/create.html | 20 ++--- client/views/home.html | 6 +- server/main.js | 15 ++-- server/modules/GameManager.js | 13 +++- server/modules/GameStateCurator.js | 8 +- server/modules/ServerTimer.js | 10 +-- server/routes/favicon-router.js | 18 ----- server/routes/router.js | 2 +- server/routes/static-router.js | 115 ---------------------------- 16 files changed, 237 insertions(+), 200 deletions(-) delete mode 100644 server/routes/favicon-router.js delete mode 100644 server/routes/static-router.js diff --git a/client/config/globals.js b/client/config/globals.js index f667864..17ebd04 100644 --- a/client/config/globals.js +++ b/client/config/globals.js @@ -1,6 +1,7 @@ export const globals = { USER_SIGNATURE_LENGTH: 25, CLOCK_TICK_INTERVAL_MILLIS: 10, + TOAST_DURATION_DEFAULT: 6, ACCESS_CODE_LENGTH: 6, PLAYER_ID_COOKIE_KEY: 'play-werewolf-anon-id', ACCESS_CODE_CHAR_POOL: 'abcdefghijklmnopqrstuvwxyz0123456789', diff --git a/client/modules/GameStateRenderer.js b/client/modules/GameStateRenderer.js index 1f30dfd..c545ac7 100644 --- a/client/modules/GameStateRenderer.js +++ b/client/modules/GameStateRenderer.js @@ -1,5 +1,6 @@ import { globals } from "../config/globals.js"; import { toast } from "./Toast.js"; +import {templates} from "./Templates.js"; export class GameStateRenderer { constructor(gameState) { @@ -87,7 +88,10 @@ export class GameStateRenderer { } renderModeratorView() { - + let div = document.createElement("div"); + div.innerHTML = templates.END_GAME_PROMPT; + document.body.appendChild(div); + renderModeratorPlayers(this.gameState.people); } } @@ -120,3 +124,28 @@ function removeExistingTitle() { existingTitle.remove(); } } + +function renderModeratorPlayers(people) { + people.sort(); + let teamGood = people.filter((person) => person.alignment === globals.ALIGNMENT.GOOD); + let teamEvil = people.filter((person) => person.alignment === globals.ALIGNMENT.EVIL); + renderGroupOfPlayersFromTeam(teamEvil, globals.ALIGNMENT.EVIL); + renderGroupOfPlayersFromTeam(teamGood, globals.ALIGNMENT.GOOD); + document.getElementById("players-alive-label").innerText = + 'Players: ' + people.filter((person) => !person.out).length + ' / ' + people.length + ' Alive'; + +} + +function renderGroupOfPlayersFromTeam(players, alignment) { + for (let player of players) { + let container = document.createElement("div"); + container.classList.add('moderator-player'); + container.innerHTML = templates.MODERATOR_PLAYER; + container.querySelector('.moderator-player-name').innerText = player.name; + let roleElement = container.querySelector('.moderator-player-role') + roleElement.innerText = player.gameRole; + roleElement.classList.add(alignment); + + document.getElementById("player-list-moderator-team-" + alignment).appendChild(container); + } +} diff --git a/client/modules/Templates.js b/client/modules/Templates.js index 00c6e73..44418d1 100644 --- a/client/modules/Templates.js +++ b/client/modules/Templates.js @@ -21,6 +21,10 @@ export const templates = { "
" + "" + "
", + END_GAME_PROMPT: + "
" + + "" + + "
", GAME: "
" + "
" + @@ -48,15 +52,29 @@ export const templates = { "" + "
" + "
" + - "
" + - + "
" + "
" + + "
" + + "" + + "
" + + "
" + + "" + + "
" + + "
" + + "" + + "
" + + "
" + + "
" + + "" + + "
" + "
" + "
" + + "
", + MODERATOR_PLAYER: "
" + - "" + - "
" + + "
" + + "
" + "
" + - "" + - "
" + - "" + "
" + + "" + + "
" } diff --git a/client/modules/Timer.js b/client/modules/Timer.js index 67926be..8d581b7 100644 --- a/client/modules/Timer.js +++ b/client/modules/Timer.js @@ -34,11 +34,11 @@ function stepFn (expected, interval, start, totalTime) { } const delta = now - expected; expected += interval; - let displayTime = (totalTime - (expected - start)) < 60000 - ? returnHumanReadableTime(totalTime - (expected - start), true) - : returnHumanReadableTime(totalTime - (expected - start)); + let displayTime = (totalTime - (now - start)) < 60000 + ? returnHumanReadableTime(totalTime - (now - start), true) + : returnHumanReadableTime(totalTime - (now - start)); postMessage({ - timeRemainingInMilliseconds: totalTime - (expected - start), + timeRemainingInMilliseconds: totalTime - (now - start), displayTime: displayTime }); Singleton.setNewTimeoutReference(setTimeout(() => { diff --git a/client/modules/Toast.js b/client/modules/Toast.js index 04def60..f6366dd 100644 --- a/client/modules/Toast.js +++ b/client/modules/Toast.js @@ -1,34 +1,40 @@ -export const toast = (message, type, positionAtTop = true, dispelAutomatically=true) => { +import {globals} from "../config/globals.js"; + +export const toast = (message, type, positionAtTop = true, dispelAutomatically=true, duration=null) => { if (message && type) { - buildAndInsertMessageElement(message, type, positionAtTop, dispelAutomatically); + buildAndInsertMessageElement(message, type, positionAtTop, dispelAutomatically, duration); } }; -function buildAndInsertMessageElement (message, type, positionAtTop, dispelAutomatically) { +function buildAndInsertMessageElement (message, type, positionAtTop, dispelAutomatically, duration) { cancelCurrentToast(); - let backgroundColor; - const position = positionAtTop ? 'top:3rem;' : 'bottom: 35px;'; + let backgroundColor, border; + const position = positionAtTop ? 'top:2rem;' : 'bottom: 35px;'; switch (type) { case 'warning': backgroundColor = '#fff5b1'; + border = '3px solid #c7c28a'; break; case 'error': backgroundColor = '#fdaeb7'; + border = '3px solid #c78a8a'; break; case 'success': backgroundColor = '#bef5cb'; + border = '3px solid #8ac78a;' break; } + let durationInSeconds = duration ? duration + 's' : globals.TOAST_DURATION_DEFAULT + 's'; let animation = ''; if (dispelAutomatically) { - animation = 'animation:fade-in-slide-down-then-exit 6s ease normal forwards'; + animation = 'animation:fade-in-slide-down-then-exit ' + durationInSeconds + ' ease normal forwards'; } else { - animation = 'animation:fade-in-slide-down 6s ease normal forwards'; + animation = 'animation:fade-in-slide-down ' + durationInSeconds + ' ease normal forwards'; } const messageEl = document.createElement("div"); messageEl.setAttribute("id", "current-info-message"); - messageEl.setAttribute("style", 'background-color:' + backgroundColor + ';' + position + animation); + messageEl.setAttribute("style", 'background-color:' + backgroundColor + ';' + 'border:' + border + ';' + position + animation); messageEl.setAttribute("class", 'info-message'); messageEl.innerText = message; document.body.prepend(messageEl); diff --git a/client/scripts/game.js b/client/scripts/game.js index 7c10cd1..e82bf2d 100644 --- a/client/scripts/game.js +++ b/client/scripts/game.js @@ -6,14 +6,17 @@ import {cancelCurrentToast, toast} from "../modules/Toast.js"; import {GameTimerManager} from "../modules/GameTimerManager.js"; export const game = () => { - let timerWorker = new Worker('../modules/Timer.js'); + let timerWorker; const socket = io('/in-game'); socket.on('disconnect', () => { - timerWorker.terminate(); + if (timerWorker) { + timerWorker.terminate(); + } toast('Disconnected. Attempting reconnect...', 'error', true, false); }); socket.on('connect', () => { socket.emit(globals.COMMANDS.GET_ENVIRONMENT, function(returnedEnvironment) { + timerWorker = new Worker('../modules/Timer.js'); prepareGamePage(returnedEnvironment, socket, timerWorker); }); }) @@ -26,9 +29,9 @@ function prepareGamePage(environment, socket, timerWorker) { if (/^[a-zA-Z0-9]+$/.test(accessCode) && accessCode.length === globals.ACCESS_CODE_LENGTH) { socket.emit(globals.COMMANDS.FETCH_GAME_STATE, accessCode, userId, function (gameState) { if (gameState === null) { - window.location = '/not-found' + window.location = '/not-found?reason=' + encodeURIComponent('game-not-found'); } else { - toast('You are connected.', 'success', true); + toast('You are connected.', 'success', true, true, 3); console.log(gameState); userId = gameState.client.id; UserUtility.setAnonymousUserId(userId, environment); @@ -43,7 +46,7 @@ function prepareGamePage(environment, socket, timerWorker) { } }); } else { - window.location = '/not-found'; + window.location = '/not-found?reason=' + encodeURIComponent('invalid-access-code'); } } @@ -64,16 +67,25 @@ function processGameState (gameState, userId, socket, gameStateRenderer) { } break; case globals.STATUS.IN_PROGRESS: - document.querySelector("#start-game-prompt")?.remove(); gameStateRenderer.gameState = gameState; gameStateRenderer.renderGameHeader(); - if (gameState.client.userType === globals.USER_TYPES.PLAYER || gameState.client.userType === globals.USER_TYPES.TEMPORARY_MODERATOR) { - document.getElementById("game-state-container").innerHTML = templates.GAME; - gameStateRenderer.renderPlayerRole(); - } else if (gameState.client.userType === globals.USER_TYPES.MODERATOR) { - document.getElementById("game-state-container").innerHTML = templates.MODERATOR_GAME_VIEW; - gameStateRenderer.renderModeratorView(); + switch (gameState.client.userType) { + case globals.USER_TYPES.PLAYER: + document.getElementById("game-state-container").innerHTML = templates.GAME; + gameStateRenderer.renderPlayerRole(); + break; + case globals.USER_TYPES.MODERATOR: + document.querySelector("#start-game-prompt")?.remove(); + document.getElementById("game-state-container").innerHTML = templates.MODERATOR_GAME_VIEW; + gameStateRenderer.renderModeratorView(); + break; + case globals.USER_TYPES.TEMPORARY_MODERATOR: + document.querySelector("#start-game-prompt")?.remove(); + break; + default: + break; } + socket.emit(globals.COMMANDS.GET_TIME_REMAINING, gameState.accessCode); break; default: diff --git a/client/styles/game.css b/client/styles/game.css index 7c91678..096b4ba 100644 --- a/client/styles/game.css +++ b/client/styles/game.css @@ -134,8 +134,9 @@ h1 { } #game-timer { - padding: 1px; - background-color: #3c3c3c; + padding: 10px; + margin-top: 5px; + background-color: #262626; color: whitesmoke; border-radius: 3px; font-size: 35px; @@ -228,7 +229,7 @@ label[for='moderator'] { font-size: 30px; } -#start-game-prompt { +#start-game-prompt, #end-game-prompt { display: flex; align-items: center; justify-content: center; @@ -252,10 +253,9 @@ label[for='moderator'] { background-color: #333243; } -#start-game-button { +#start-game-button, #end-game-button { font-family: 'signika-negative', sans-serif !important; padding: 10px; - background-color: #1c8a36; border-radius: 3px; color: whitesmoke; font-size: 30px; @@ -265,14 +265,28 @@ label[for='moderator'] { text-shadow: 0 3px 4px rgb(0 0 0 / 85%); } +#start-game-button { + background-color: #1c8a36; +} + +#end-game-button { + background-color: #8a1c1c; +} + #start-game-button:hover { background-color: #326243; border: 2px solid #1c8a36; } +#end-game-button:hover { + background-color: #623232; + border: 2px solid #8a1c1c; +} + #play-pause { display: flex; align-items: center; + margin-left: 1em; } #play-pause img { @@ -301,6 +315,7 @@ label[for='moderator'] { flex-wrap: wrap; align-items: center; justify-content: space-evenly; + flex-direction: column; } .timer-container-moderator { @@ -308,6 +323,81 @@ label[for='moderator'] { flex-wrap: wrap; align-items: center; justify-content: center; + margin-bottom: 1em; +} + +.moderator-player { + border-left: 2px solid gray; + display: flex; + color: #d7d7d7; + background-color: black; + align-items: center; + padding: 0 5px; + justify-content: space-between; + margin: 0.5em 0; +} + +.moderator-player-name { + width: 10em; + overflow: hidden; + white-space: nowrap; + font-weight: bold; + font-size: 18px; + text-overflow: ellipsis; +} + +.kill-player-button, .make-mod-button { + font-family: 'signika-negative', sans-serif !important; + padding: 5px; + border-radius: 3px; + color: whitesmoke; + font-size: 16px; + cursor: pointer; + border: 2px solid transparent; + transition: background-color, border 0.3s ease-out; + text-shadow: 0 3px 4px rgb(0 0 0 / 55%); + margin: 5px 0 5px 25px; + min-width: 6em; +} + +.make-mod-button { + background-color: #3f5256; + font-size: 18px; + padding: 10px; +} + +.good-players { + background-color: #1c1a36; +} + +.evil-players { + background-color: #361a1a; +} + +.kill-player-button { + background-color: #3f5256; +} + +#player-list-moderator > div { + padding: 2px 10px; + border-radius: 3px; + margin-bottom: 1em; +} + +#players-alive-label { + display: block; + margin-bottom: 10px; + font-size: 25px; +} + +@media(max-width: 685px) { + #end-game-button { + font-size: 25px; + } + + #end-game-prompt { + height: 85px; + } } @keyframes pulse { diff --git a/client/views/create.html b/client/views/create.html index 1250225..c6f2c0b 100644 --- a/client/views/create.html +++ b/client/views/create.html @@ -13,16 +13,16 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/server/main.js b/server/main.js index 5ae182f..0638610 100644 --- a/server/main.js +++ b/server/main.js @@ -90,12 +90,17 @@ app.use('/favicon.ico', (req, res) => { }); const router = require('./routes/router'); -const faviconRouter = require('./routes/favicon-router'); -const staticRouter = require('./routes/static-router'); - app.use('', router); -app.use('', staticRouter); -app.use('', faviconRouter); + +app.use('/images', express.static(path.join(__dirname, '../client/images'))); +app.use('/scripts', express.static(path.join(__dirname, '../client/scripts'))); +app.use('/styles', express.static(path.join(__dirname, '../client/styles'))); +app.use('/styles/third-party', express.static(path.join(__dirname, '../client/styles/third_party'))); +app.use('/modules/third-party', express.static(path.join(__dirname, '../client/modules/third_party'))) +app.use('/modules', express.static(path.join(__dirname, '../client/modules'))) +app.use('/model', express.static(path.join(__dirname, '../client/model'))) +app.use('/config', express.static(path.join(__dirname, '../client/config'))) +app.use('/webfonts', express.static(path.join(__dirname, '../client/webfonts'))); app.use(function (req, res) { res.sendFile(path.join(__dirname, '../client/views/404.html')); diff --git a/server/modules/GameManager.js b/server/modules/GameManager.js index 9d30c5c..6729059 100644 --- a/server/modules/GameManager.js +++ b/server/modules/GameManager.js @@ -244,7 +244,16 @@ function handleRequestForGameState(namespace, logger, gameRunner, accessCode, pe matchingPerson.socketId = socket.id; ackFn(GameStateCurator.getGameStateFromPerspectiveOfPerson(game, matchingPerson, gameRunner, socket, logger)); } else { - rejectClientRequestForGameState(ackFn); + logger.trace('this person is already associated with a socket connection'); + let alreadyConnectedSocket = namespace.connected[matchingPerson.socketId]; + if (alreadyConnectedSocket && alreadyConnectedSocket.leave) { + alreadyConnectedSocket.leave(accessCode, ()=> { + logger.trace('kicked existing connection out of room ' + accessCode); + socket.join(accessCode); + matchingPerson.socketId = socket.id; + ackFn(GameStateCurator.getGameStateFromPerspectiveOfPerson(game, matchingPerson, gameRunner, socket, logger)); + }) + } } } } else { @@ -271,11 +280,13 @@ function handleRequestForGameState(namespace, logger, gameRunner, accessCode, pe ); } else { rejectClientRequestForGameState(ackFn); + logger.trace('this game is full'); } } } } else { rejectClientRequestForGameState(ackFn); + logger.trace('the game' + accessCode + ' was not found'); } } diff --git a/server/modules/GameStateCurator.js b/server/modules/GameStateCurator.js index ad2543a..059c00b 100644 --- a/server/modules/GameStateCurator.js +++ b/server/modules/GameStateCurator.js @@ -71,7 +71,8 @@ function mapPeopleForModerator(people, client) { userType: person.userType, gameRole: person.gameRole, gameRoleDescription: person.gameRoleDescription, - alignment: person.alignment + alignment: person.alignment, + out: person.out })); } @@ -82,12 +83,13 @@ function mapPeopleForTempModerator(people, client) { }) .map((person) => ({ name: person.name, - userType: person.userType + userType: person.userType, + out: person.out })); } function mapPerson(person) { - return { name: person.name, userType: person.userType }; + return { name: person.name, userType: person.userType, out: person.out }; } module.exports = GameStateCurator; diff --git a/server/modules/ServerTimer.js b/server/modules/ServerTimer.js index 32a9049..603a93d 100644 --- a/server/modules/ServerTimer.js +++ b/server/modules/ServerTimer.js @@ -1,14 +1,14 @@ function stepFn (serverTimerInstance, expected) { - const now = Date.now(); + const now = Date.now(); // serverTimerInstance.currentTimeInMillis = serverTimerInstance.totalTime - (now - serverTimerInstance.start); - if (now - serverTimerInstance.start >= serverTimerInstance.totalTime) { - clearTimeout(serverTimerInstance.ticking); + if (now - serverTimerInstance.start >= serverTimerInstance.totalTime) { // check if the time has elapsed serverTimerInstance.logger.debug( 'ELAPSED: ' + (now - serverTimerInstance.start) + 'ms (~' + (Math.abs(serverTimerInstance.totalTime - (now - serverTimerInstance.start)) / serverTimerInstance.totalTime).toFixed(3) + '% error).' ); serverTimerInstance.timesUpResolver(); // this is a reference to the callback defined in the construction of the promise in runTimer() + clearTimeout(serverTimerInstance.ticking); return; } const delta = now - expected; @@ -64,10 +64,6 @@ class ServerTimer { clearTimeout(this.ticking); } let now = Date.now(); - this.logger.debug( - 'ELAPSED (PAUSE): ' + (now - this.start) + 'ms (~' - + (Math.abs(this.totalTime - (now - this.start)) / this.totalTime).toFixed(3) + '% error).' - ); } resumeTimer() { diff --git a/server/routes/favicon-router.js b/server/routes/favicon-router.js deleted file mode 100644 index bb101f0..0000000 --- a/server/routes/favicon-router.js +++ /dev/null @@ -1,18 +0,0 @@ -const express = require('express'); -const faviconRouter = express.Router(); -const path = require('path'); -const checkIfFileExists = require("./util"); - -faviconRouter.use('/client/favicon_package/*', (req, res) => { - let filePath = path.join(__dirname, ('../../' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.png' || extension === '.ico' || extension === '.svg' || extension === 'xml')) { - res.sendFile(filePath); - } else { - res.sendStatus(404); - } - }); -}); - -module.exports = faviconRouter; diff --git a/server/routes/router.js b/server/routes/router.js index c878d9f..37da71a 100644 --- a/server/routes/router.js +++ b/server/routes/router.js @@ -1,5 +1,5 @@ const express = require('express'); -const router = express.Router(); +const router = express.Router({ strict: true }); const path = require('path'); router.get('/', function (request, response) { diff --git a/server/routes/static-router.js b/server/routes/static-router.js deleted file mode 100644 index 0f99a98..0000000 --- a/server/routes/static-router.js +++ /dev/null @@ -1,115 +0,0 @@ -const express = require('express'); -const staticRouter = express.Router(); -const path = require('path'); -const checkIfFileExists = require("./util"); - -staticRouter.use('/styles/**', (req, res) => { - let filePath = path.join(__dirname, ('../../client/' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.css' || extension === '.min.css')) { - res.sendFile(filePath); - } else { - res.sendStatus(404); - } - }); -}); - -staticRouter.use('/client/webfonts/*', (req, res) => { - let filePath = path.join(__dirname, ('../' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.ttf' || extension === '.woff2')) { - res.sendFile(filePath); - } else { - res.sendStatus(404); - } - }); -}); - -staticRouter.use('/images/*', (req, res) => { - let filePath = path.join(__dirname, ('../../client/' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.svg' || extension === '.png' || extension === '.jpg' || extension === '.gif')) { - res.sendFile(filePath); - } else { - res.sendStatus(404); - } - }); -}); - -staticRouter.use('/scripts/*', (req, res) => { - let filePath = path.join(__dirname, ('../../client/' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.js')) { - res.sendFile(filePath); - } else { - res.sendStatus(404); - } - }); -}); - -staticRouter.use('/webfonts/*', (req, res) => { - let filePath = path.join(__dirname, ('../../client/' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.woff2')) { - res.sendFile(filePath); - } else { - res.sendStatus(404); - } - }); -}); - -staticRouter.use('/views/*', (req, res) => { - let filePath = path.join(__dirname, ('../../client/' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.html')) { - res.sendFile(filePath); - } else { - res.sendFile('../views/404.html'); - } - }); -}); - - -staticRouter.use('/config/*', (req, res) => { - let filePath = path.join(__dirname, ('../../client/' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.js')) { - res.sendFile(filePath); - } else { - res.sendFile('../views/404.html'); - } - }); -}); - -staticRouter.use('/modules/**', (req, res) => { - let filePath = path.join(__dirname, ('../../client/' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.js' || extension === '.min.js')) { - res.sendFile(filePath); - } else { - res.sendFile('../views/404.html'); - } - }); -}); - -staticRouter.use('/model/**', (req, res) => { - let filePath = path.join(__dirname, ('../../client/' + req.baseUrl)); - let extension = path.extname(filePath); - checkIfFileExists(filePath).then((fileExists) => { - if (fileExists && (extension === '.js')) { - res.sendFile(filePath); - } else { - res.sendFile('../views/404.html'); - } - }); -}); - -module.exports = staticRouter;