From 5a3095aa733d573b37320235fd8cff26435294a3 Mon Sep 17 00:00:00 2001 From: Meleeman01 Date: Wed, 15 Jan 2025 06:26:27 -0600 Subject: [PATCH] added checks to prevent game server from crashing --- server.js | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index e03c8ad..cd64218 100644 --- a/server.js +++ b/server.js @@ -175,6 +175,18 @@ function checkGuess(letter,gameStateObject) { } +// function checkIfClientExistsInRoom(ws,room) { +// console.log(room,ws) +// //assumes ws message is sent and room code exists +// for(const c in room.clients) { +// const client = room.clients[c] +// if (ws.identifierToken == client.identifierToken && ws.roomCode == client.roomCode) { +// return true +// } +// } +// return false +// } + checkPuzzleData(puzzles) // server.js @@ -233,8 +245,12 @@ wss.on('connection', (ws) => { started:false, puzzles:shuffleArray(puzzles), puzzleLevel:0, + turn:0, + turnState:null, + players:[] }, } + console.log(rooms[roomCode].clients[0].name) ws.roomCode = roomCode ws.send(JSON.stringify({ type: 'room_created', roomCode, isLeader: true, @@ -290,7 +306,6 @@ wss.on('connection', (ws) => { room.gameState.started = true room.gameState.turnState = 'spin' - room.gameState.players = [] room.gameState.puzzles[room.gameState.puzzleLevel] = currentPuzzle room.gameState.levelsRemaining = (room.gameState.puzzles.length - 1 - room.gameState.puzzleLevel) room.clients.forEach((client)=>{ @@ -300,7 +315,6 @@ wss.on('connection', (ws) => { points:0 }) }) - room.gameState.turn = 0 console.log(room.gameState) console.log('game started for:',room) @@ -324,7 +338,15 @@ wss.on('connection', (ws) => { const room = rooms[ws.roomCode] if (room && room.clients.includes(ws)) { // Handle spin and guess events + if (data.type === 'spin_wheel') { + if (room.gameState.turnState === null) { + ws.send(JSON.stringify({ type: 'error', message: 'the game hasn\'t started yet!' })) + return + }else if (ws.identifierToken !== room.gameState.players[room.gameState.turn].id) { + ws.send(JSON.stringify({ type: 'error', message: 'its not your turn to spin!' })) + return + } // Simulate a wheel spin result and update room state let spinResult = getRandomValue(wheel) if (spinResult == 'Bankrupt') { @@ -351,6 +373,13 @@ wss.on('connection', (ws) => { } if (data.type === 'guess_letter') { + if (room.gameState.turnState === null) { + ws.send(JSON.stringify({ type: 'error', message: 'the game hasn\'t started yet!' })) + return + }else if (ws.identifierToken !== room.gameState.players[room.gameState.turn].id) { + ws.send(JSON.stringify({ type: 'error', message: 'its not your turn to guess!' })) + return + } room.gameState.turnState = 'spin' const { letter } = data // Handle guess logic (e.g., check if the letter is in the puzzle)