fixed bug related to multi row puzzle, add clipboard, points display

This commit is contained in:
Meleeman01 2025-03-07 08:35:20 -06:00
parent f070396a3d
commit 6c8f68b8b4
2 changed files with 292 additions and 67 deletions

View File

@ -2,6 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiplayer Game</title>
<link rel="stylesheet" type="text/css" href="mflx.min.css">
<style type="text/css">
@ -80,7 +82,7 @@
}
</style>
</head>
<body>
<body class="flx center">
<!-- Dialog -->
<dialog class="nameDialog">
<div class="flx(column) space-evenly">
@ -105,7 +107,7 @@
</div>
<div>
</dialog>
<div class="main flx(column) middle center" style="max-width: 600px;">
<button id="create-room">Create Room</button>
<input id="join-code" placeholder="Enter room code">
<button id="join-room">Join Room</button>
@ -121,7 +123,7 @@
<div class="puzzleboard mb-2"></div>
<div class="category mb-5"></div>
<div class="category mb-5 is-full"></div>
<div style="display:relative;">
<span style="position: absolute; top: 0; left:50%">
@ -129,6 +131,7 @@
</span>
<canvas id="wheelCanvas" width="500" height="500"></canvas>
</div>
</div>
<script>
//================general Purpose functions=========================================//
function cryptoSecureShuffle(array) {
@ -162,10 +165,31 @@
]
nameColors = cryptoSecureShuffle(nameColors);
function assignColors(names, colors) {
console.log(names);
let result = [];
let n = 0; // Keep track of name index
let c = 0; // Keep track of color index
if (typeof names[0] !== 'string') {
//in which case the data should look like [{...},{...},{...}...]
console.log('larger data case here.')
if (names.length > colors.length) {
// Assign colors cyclically
while (n < names.length) {
result.push({ name: names[n].name, color: colors[c], score: names[n].points, wins: names[n].wins });
n++;
c = (c + 1) % colors.length; // Cycle through the colors
}
} else {
// Assign colors directly, keeping track of indices
while (n < names.length) {
result.push({ name: names[n].name, color: colors[c], score: names[n].points, wins: names[n].wins });
n++;
c++;
}
}
}
else {
//data looks like this ['asdf','asdf','asdf']
if (names.length > colors.length) {
// Assign colors cyclically
while (n < names.length) {
@ -176,14 +200,23 @@
} else {
// Assign colors directly, keeping track of indices
while (n < names.length) {
result.push({ name: names[n], color: colors[c] });
result.push({ name: names[n], color: colors[c]});
n++;
c++;
}
}
}
return result;
}
function copyToClipboard() {
navigator.clipboard.writeText("Your text here").then(() => {
console.log("Copied successfully!");
}).catch(err => {
console.error("Failed to copy:", err);
});
}
//=========================================wheel==========================================//
const wheel = [
'lose a turn', 800, 350, 450, 700, 300, 600, 5000,
@ -191,7 +224,11 @@
900, 'Bankrupt', 600, 400, 300
];
const canvas = document.getElementById('wheelCanvas');
let canvas = document.getElementById('wheelCanvas');
if(canvas.clientWidth < 600) {
canvas.width = canvas.width / 1.5;
canvas.height = canvas.height/1.5;
}
const ctx = canvas.getContext('2d');
const radius = canvas.width / 2;
let lowestEquivelantAngle = 23.4327090939438 % (2* Math.PI);
@ -217,6 +254,7 @@
const anglePerSegment = (2 * Math.PI) / wheel.length;
console.log('',anglePerSegment)
let j = 0;
wheel.forEach((value, i) => {
const startAngle = i * anglePerSegment;
const endAngle = startAngle + anglePerSegment;
@ -227,6 +265,16 @@
ctx.closePath();
ctx.fillStyle = i % 2 === 0 ? '#ffdd99' : '#ffeecc';
// if (j === nameColors.length) {
// j = 0;
// ctx.fillStyle = nameColors[j];
// }
// else {
// ctx.fillStyle = nameColors[j];
// j++;
// }
ctx.fill();
ctx.stroke();
@ -239,9 +287,9 @@
ctx.rotate(startAngle + anglePerSegment / 2 + Math.PI / 2 - 1.5);
ctx.textAlign = 'center';
ctx.fillStyle = '#000';
ctx.font = '12px Arial';
ctx.fillText(String(i+","+value), 0, 0);
ctx.font = '14px Arial';
//ctx.fillText(String(i+","+value), 0, 0); //for debug
ctx.fillText(String(value), 0, 0);
ctx.restore();
});
@ -250,7 +298,7 @@
}
// Start spinning
function startSpin(targetIndex) {
function startSpin(targetIndex,message) {
if (spinning) return;
const totalTime = 8;
let c = 1.62;
@ -279,6 +327,9 @@
if (currentFrame > totalFrames) {
spinning = false;
document.getElementById("spin-wheel").disabled = false;
document.getElementById("status").classList.remove('hidden')
drawPlayers(message);
spinSpeed = 0;
console.log(`Landed on: ${wheel[targetIndex[0]]}`);
console.log(`final frameCount: ${currentFrame} and totalFrames ${totalFrames}`);
@ -306,23 +357,56 @@
drawWheel();
//==================================end of Wheel=====================================//
function drawPlayers(message) {
console.log(message);
console.log('in draw players',message);
let players = document.querySelector('.players');
//clear the players incase any weird side effects occur
players.innerHTML = ``;
//assignColors(names, colors) {
let processedNametags = assignColors(message.clients,nameColors);
let processedNametags;
if (message?.playerStats) {
processedNametags = assignColors(message.playerStats,nameColors);
} else {
processedNametags = assignColors(message.clients,nameColors);
}
console.log(processedNametags);
const playersHtml = processedNametags.map(client => {
if(client.name != window.you) {
if (client.name === message.leaderName) {
return `<span class='mr-2 btn is-round text-with-shadow div-shadow' style='background-color:${client.color};'>⭐ ${client.name} ⭐</span>`; // Highlight the leader with stars
return `
<div class="flx(column) center middle">
<span class='mr-2 btn is-round text-with-shadow div-shadow' style='background-color:${client.color};'>⭐ ${client.name} ⭐</span>
<span class="score flx center middle mr-2 mt-1 is-round text-with-shadow div-shadow is-half" style='background-color:${client.color};'>${client?.score ? client.score : '0'}</span>
</div>
`
; // Highlight the leader with stars
} else {
return `<span class='mr-2 btn is-round text-with-shadow div-shadow' style='background-color:${client.color};'>${client.name}</span>`;
return `
<div class="flx(column) center middle">
<span class='mr-2 btn is-round text-with-shadow div-shadow' style='background-color:${client.color};'>
${client.name}</span>
<span class="score flx center middle mr-2 mt-1 is-round text-with-shadow div-shadow is-half" style='background-color:${client.color};'>${client?.score ? client.score : '0'}</span>
</div>
`;
}
}
else if (client.name === message.leaderName) {
return `<span class='mr-2 btn is-round text-with-shadow div-shadow' style='background-color:${client.color};' onclick="changeName()">⭐ ${client.name} ⭐ (you)</span>`; // Highlight the leader with stars
return `
<div class="flx(column) center middle">
<span class='mr-2 btn is-round text-with-shadow div-shadow' style='background-color:${client.color};' onclick="changeName()">⭐ ${client.name} ⭐ (you)</span>
<span class="score flx center middle mr-2 mt-1 is-round text-with-shadow div-shadow is-half" style='background-color:${client.color};'>${client?.score ? client.score : '0'}</span>
</div>
`; // Highlight the leader with stars
}
else {
return `<span class='mr-2 btn is-round text-with-shadow div-shadow' style='background-color:${client.color};' onclick="changeName()">${client.name} (you)</span>`;
return `
<div class="flx(column) center middle">
<span class='mr-2 btn is-round text-with-shadow div-shadow' style='background-color:${client.color};' onclick="changeName()">${client.name} (you)</span>
<span class="score flx center middle mr-2 mt-1 is-round text-with-shadow div-shadow is-half" style='background-color:${client.color};'>${client?.score ? client.score : '0'}</span>
</div>
`;
}
@ -333,7 +417,7 @@
function drawPuzzle(message, gridRows = 4, gridCols = 12) {
//legend null = space, "" = white space to guess, "a" is a letter already solved for you.
console.log(message);
console.log(message.puzzle.puzzle[0]);
//wheel of fortune puzzles must fit within a 12x4 grid of letter spaces
//first we draw the spaces
let puzzle = message.puzzle.puzzle;
@ -343,6 +427,41 @@
//if the first entry of the puzzle is an array and not a string display the puzzle differently
if (Array.isArray(message.puzzle.puzzle[0])) {
console.log('first entry is an array in this puzzle...');
for (let row of message.puzzle.puzzle) {
if (row.length == 0) {
resultingPuzzleBoard.push(Array(12).fill(null));
continue;
}
const nextLine = Array(12).fill(null);
const startIndex = Math.floor((12 - row.length) / 2);
for (let i = 0; i < row.length; i++) {
nextLine[startIndex + i] = row[i];
}
resultingPuzzleBoard.push(nextLine);
console.log(resultingPuzzleBoard);
}
//after we've drawn our data for our board,now its time to visualize it to the user
puzzleBoard.innerHTML = ``;
for(let i of resultingPuzzleBoard) {
for (let j in i) {
const letter = i[j];
if (letter == null || letter == ' ') {
let el = document.createElement('div');
el.classList.add('grid-item');
el.innerHTML = '&nbsp;';
// el.style.height = '50px';
// el.style.width = '50px';
// el.style.border = 'solid'
puzzleBoard.appendChild(el);
}
else if (letter != null && letter != ' ') {
let el = document.createElement('div');
el.classList.add('grid-item-2');
el.innerText = letter;
puzzleBoard.appendChild(el);
}
}
}
}
else if (typeof message.puzzle.puzzle[0] == 'string') {
console.log('first entry is a string in this puzzle...');
@ -419,6 +538,7 @@
closeDialogButton.addEventListener('click',() => {solveDialog.close()});
solveButton.addEventListener('click',() => {
socket.send(JSON.stringify({ type: "solve_puzzle", guess:solveInput.value }));
solveInput.value = '';
solveDialog.close();
});
}
@ -468,6 +588,7 @@
this.style.display = 'none';
document.getElementById("create-room").style.display = 'none';
document.getElementById('join-code').style.display = 'none';
};
document.getElementById("start-game").onclick = () => {
@ -475,10 +596,14 @@
};
document.getElementById("spin-wheel").onclick = () => {
if (spinning) return;
document.getElementById("spin-wheel").disabled = true;
socket.send(JSON.stringify({ type: "spin_wheel" }));
};
document.getElementById("guess-button").onclick = () => {
const letter = document.getElementById("guess-letter").value;
socket.send(JSON.stringify({ type: "guess_letter", letter}));
document.getElementById("guess-letter").value = ""; // Clear input
@ -545,11 +670,12 @@
}
if (message.type === "spin_result") {
document.getElementById("status").classList.add('hidden')
console.log('spin result recieved');
if (message.spinResult != 'lose a turn' || message.spinResult != 'Bankrupt' || message.spinResult != 'spin again') {
document.getElementById("status").innerText = `Spin result: ${message.spinResult} points (${message.player})`;
document.getElementById("status").innerText = `Spin result: ${message.spinResult} points (${message.player.name})`;
}
else document.getElementById("status").innerText = `Spin result: ${message.spinResult} for (${message.player})`;
else document.getElementById("status").innerText = `Spin result: ${message.spinResult} for (${message.player.name})`;
//find target index
@ -564,11 +690,11 @@
//if there is multiple entries where the spin exists pick a random index.
if(filterResultsArr.length > 1) {
console.log('if fra.length > 1',filterResultsArr[0])
startSpin(filterResultsArr[0]);
startSpin(filterResultsArr[0],message);
}
else{
console.log('else',filterResultsArr[0])
startSpin(filterResultsArr[0]);
startSpin(filterResultsArr[0],message);
}
if (window.yourTurn && message.spinResult != 'lose a turn') {
console.log('in spin_result: ',message)
@ -581,11 +707,13 @@
message.turnState = 'spin';
changeSpinGuessState(message);
}
}
if (message.type === "guess_result") {
document.getElementById("status").classList.remove('hidden')
const outcome = message.correct ? "correct" : "incorrect";
document.getElementById("status").innerText = `Guess '${message.letter}' was ${outcome} (${message.player})`;
document.getElementById("status").innerText = `Guess '${message.letter}' was ${outcome} (${message.player.name})`;
console.log(message);
if (message.puzzle) {
drawPuzzle(message);
@ -597,6 +725,10 @@
window.yourTurn = false
changeTurnState()
}
drawPlayers(message);
}
if (message.type === "incorrect_puzzle_guess") {
document.getElementById("status").innerText = `${message.message}`;
}
if (message.type === "next_turn") {
@ -629,6 +761,7 @@
}
if (message.type === "game_over") {
document.getElementById("status").innerText = message.winner;
drawPlayers(message);
}
if (message.type === "error") {

170
server.js
View File

@ -1,11 +1,12 @@
const WebSocket = require('ws')
const { v4: uuidv4 } = require('uuid')
const puzzles = require('./puzzles.json')
const puzzles = require('./puzzles2.json')
const names = require('./assignedNames.json')
const crypto = require('crypto')
const wss = new WebSocket.Server({ port: 8080 })
const rooms = {} // Stores rooms and their clients
const wheel = [
'lose a turn',800,350,450,700,300,600,5000,
300,600,300,500,800,550,400,300,900,500,'spin again',
@ -50,7 +51,7 @@ function checkPuzzleData(puzzles) {
}
}
}
else if (typeof puzzle.answer == 'string') {
else if (typeof puzzle.answer === 'string') {
if (puzzle.answer.length > 12) {
throw new Error(`${puzzle.answer} (${puzzle.answer.length} characters long) is longer than 12 characters. only twelve characters allowed per line`)
}
@ -93,13 +94,13 @@ function loadCurrentPuzzle(gameStateObject) {
function processPuzzle(letterArray,given) {
let puzzleArray = []
for (let letter of letterArray) {
if (letter == ' ') {
if (letter === ' ') {
puzzleArray.push(' ')
continue
}
let letterFound = false
for (let g of given ) {
if(g.toUpperCase() == letter.toUpperCase()) {
if(g.toUpperCase() === letter.toUpperCase()) {
puzzleArray.push(g)
letterFound = true
}
@ -146,9 +147,9 @@ function checkGuess(letter,gameStateObject) {
const currentPuzzle = gameStateObject.puzzles[gameStateObject.puzzleLevel]
console.log(currentPuzzle)
if (typeof currentPuzzle.answer == 'string') {
if (typeof currentPuzzle.answer === 'string') {
//check if user already guessed one of teh given letters
if (currentPuzzle.puzzle.find((x)=> x.toUpperCase() == letter.toUpperCase())) {
if (currentPuzzle.puzzle.find((x)=> x.toUpperCase() === letter.toUpperCase())) {
console.log('user gave a guess on a given letter...')
return false
}
@ -157,7 +158,7 @@ function checkGuess(letter,gameStateObject) {
let matches = []
for(const c in charArray) {
const char = charArray[c]
if (letter.toUpperCase() == char.toUpperCase()) {
if (letter.toUpperCase() === char.toUpperCase()) {
matches.push({id:c,letter:char})
}
}
@ -181,11 +182,63 @@ function checkGuess(letter,gameStateObject) {
}
}
else if (Array.isArray(currentPuzzle.answer)) {
//
console.log(currentPuzzle.puzzle.flat())
if (currentPuzzle.puzzle.flat().find((x)=> x.toUpperCase() === letter.toUpperCase())) {
console.log('user gave a guess on a given letter...')
return false
}
//check each row of letters for the answer
let matches = []
console.log(currentPuzzle.answer)
for (let r in currentPuzzle.answer) {
let row = currentPuzzle.answer[r]
//first create an indexed hashMap
let charArray = row.split('')
for(const c in charArray) {
const char = charArray[c]
if (letter.toUpperCase() === char.toUpperCase()) {
matches.push({id:c,row_index:r,letter:char})
}
}
}
console.log(matches)
//if there are any matches write them to the gameState Object
if (!matches.length) {
return false
} else {
for (let i in matches) {
let match = matches[i]
gameStateObject.puzzles[gameStateObject.puzzleLevel].puzzle[match.row_index][match.id] = match.letter
}
console.log(gameStateObject.puzzles[gameStateObject.puzzleLevel].answer)
//make sure to check if a win occurred
// convert the answer string into an array of characters
console.log(gameStateObject.puzzles[gameStateObject.puzzleLevel].answer.flat())
let checkAnswer = gameStateObject.puzzles[gameStateObject.puzzleLevel].answer.flat().filter((letter) => letter != ' ').join('')
let puzzleToCheck = gameStateObject.puzzles[gameStateObject.puzzleLevel].puzzle.flat().filter((letter) => letter != ' ').join('')
console.log(checkAnswer,puzzleToCheck)
if (gameStateObject.puzzles[gameStateObject.puzzleLevel].puzzle.flat().every((val,i)=> val.toUpperCase() === checkAnswer[i].toUpperCase())) {
return 'puzzleSolved'
}
console.log('matches found!!!', gameStateObject.puzzles[gameStateObject.puzzleLevel].puzzle)
return [true, matches.length]
}
}
else console.error('invalid input to checkGuess() function',currentPuzzle.puzzle[0])
}
function checkWinState(gameStateobject,ws){
if (gameStateobject.puzzleLevel === gameStateobject.puzzles.length) {
console.log('announcing winner')
announceWinner(gameStateobject,ws)
return true
}
else return false
}
function checkSolvePuzzleGuess(guess,ws) {
const room = rooms[ws.roomCode]
console.log(room.gameState)
@ -195,15 +248,25 @@ function checkSolvePuzzleGuess(guess,ws) {
console.log(guess.toUpperCase(),room.gameState.puzzles[room.gameState.puzzleLevel].answer.toUpperCase())
//guess is wrong change turns
console.log('guess is incorrect')
const currentUserTurn = room.gameState.players[room.gameState.turn]
room.clients.forEach((client) => {
client.send(JSON.stringify({
type:'incorrect_puzzle_guess',
message: `${currentUserTurn.name} guessed the puzzle incorrectly`
}))
})
changeTurn(room.gameState,ws)
}
else {
console.log('guess i correct')
//guessed correctly reward the user
rewardUser(room.gameState,ws,true)
if (!checkWinState(room.gameState,ws)) {
console.log('winstate should be false here 214')
loadNewPuzzle(room.gameState,ws)
}
}
}
else {
//its probably an array
console.log(room.gameState.puzzles[room.gameState.puzzleLevel])
@ -219,25 +282,29 @@ function checkSolvePuzzleGuess(guess,ws) {
//correct
console.log('correct.',guess.toUpperCase(),answer.toUpperCase())
rewardUser(room.gameState,ws,true)
if (!checkWinState(room.gameState,ws)) {
console.log('winstate should be false here 236')
loadNewPuzzle(room.gameState,ws)
}
}
}
}
function announceWinner(gameStateObject,ws) {
//find user with highest points.
//announce to the world.
const room = rooms[ws.roomCode]
let winner = gameStateObject.players.sort((a,b)=> a.points - b.points)
let winner = gameStateObject.players.sort((a,b)=> b.points - a.points)
console.log(winner)
//needs to be tested on multiple winners and decide ties.
room.clients.forEach((client) => {
client.send(JSON.stringify({
type:'game_over',
winner: `${winner.name} wins with ${winner.points}`
winner: `${winner[0].name} wins with ${winner[0].points} points!!!`,
playerStats: room.gameState.players
}))
})
console.log('winner',)
console.log('winner', winner)
}
//these functions must have both gameStateobject and websockets initialized before use!!!
function rewardUser(gameStateObject,ws,puzzleSolved = false) {
@ -251,10 +318,7 @@ function rewardUser(gameStateObject,ws,puzzleSolved = false) {
currentUserTurn.points = currentUserTurn.points*3
console.log(currentUserTurn.points)
}
if (gameStateObject.puzzleLevel == gameStateObject.puzzles.length-1) {
announceWinner(gameStateObject,ws)
return
}
room.clients.forEach((client) => {
client.send(JSON.stringify({
type: 'puzzle_solved', roomCode,
@ -263,9 +327,10 @@ function rewardUser(gameStateObject,ws,puzzleSolved = false) {
})
}
function changeTurn(gameStateObject,ws) {
console.log('change turn hit')
const room = rooms[ws.roomCode]
if (gameStateObject.turn == gameStateObject.players.length - 1) {
if (gameStateObject.turn === gameStateObject.players.length - 1) {
gameStateObject.turn = 0
}
else gameStateObject.turn++
@ -279,6 +344,7 @@ function changeTurn(gameStateObject,ws) {
})
}
function loadNewPuzzle(gameStateObject,ws) {
console.log('loadNewPuzzle called.')
const room = rooms[ws.roomCode]
const newPuzzle = loadCurrentPuzzle(gameStateObject)
room.gameState.turnState = 'spin'
@ -292,7 +358,8 @@ function loadNewPuzzle(gameStateObject,ws) {
// eslint-disable-next-line no-undef
puzzle: removeProp(newPuzzle,'answer'),
turn:room.gameState.turn,
turnState:room.gameState.turnState
turnState:room.gameState.turnState,
playerStats: room.gameState.players
}))
})
}
@ -301,7 +368,7 @@ function loadNewPuzzle(gameStateObject,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) {
// if (ws.identifierToken === client.identifierToken && ws.roomCode === client.roomCode) {
// return true
// }
// }
@ -320,7 +387,7 @@ wss.on('connection', (ws) => {
const room = rooms[ws.roomCode]
console.log(room)
console.log(room.leader.name,room.clients[0].name)
console.log(room.clients.filter((i)=> i.name == data.deadName))
console.log(room.clients.filter((i)=> i.name === data.deadName))
console.log(ws.name,ws.identifierToken)
//change names in all places.
//if the leader wants to change their name account for this
@ -329,12 +396,12 @@ wss.on('connection', (ws) => {
//find the names by index using the identifier Token which i user can't easily create
//a name collision.
const nameToChange = room.clients.findIndex((i)=> i.identifierToken == ws.identifierToken )
const nameToChange = room.clients.findIndex((i)=> i.identifierToken === ws.identifierToken )
console.log(nameToChange)
if (nameToChange != -1) {
room.clients[nameToChange].name = data.newName
}
if (room.leader.identifierToken == room.clients[nameToChange].identifierToken) {
if (room.leader.identifierToken === room.clients[nameToChange].identifierToken) {
room.leader.name = data.newName
}
//if the user is not the leader, in theory just change the name on the clients list
@ -359,15 +426,31 @@ wss.on('connection', (ws) => {
if (data.type === 'solve_puzzle') {
console.log('solve_puzzle hit')
const room = rooms[ws.roomCode]
if(data.guess == '') return
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
}
checkSolvePuzzleGuess(data.guess, ws)
}
if (data.type === 'confirm_id') {
const room = rooms[ws.roomCode]
const currentUserTurn = room.gameState.players[room.gameState.turn]
room.gameState.turnState = 'spin'
if (ws.name == currentUserTurn.name && ws.identifierToken == currentUserTurn.id) {
if (ws.name === currentUserTurn.name && ws.identifierToken === currentUserTurn.id) {
ws.send(JSON.stringify({ type:'next_turn_confirmed', turnState:room.gameState.turnState}))
} else ws.send(JSON.stringify({ type:'next_turn_denied'}))
}
// } else ws.send(JSON.stringify({ type:'next_turn_denied'}))
room.clients.forEach((client) => {
if (client.name !== currentUserTurn.name && ws.identifierToken === currentUserTurn.id) {
console.log(client)
client.send(JSON.stringify({ type:'next_turn_denied'}))
}
})
}
if (data.type === 'create_room') {
const roomCode = uuidv4().slice(0, 5)
@ -456,7 +539,7 @@ wss.on('connection', (ws) => {
})
//console.log(room.gameState)
console.log('game started for:',room)
let selectedPlayer = room.clients.find((x)=>x.identifierToken == room.gameState.players[room.gameState.turn].id)
let selectedPlayer = room.clients.find((x)=>x.identifierToken === room.gameState.players[room.gameState.turn].id)
if (selectedPlayer) {
console.log('hit')
selectedPlayer.send(JSON.stringify({type:'your_turn'}))
@ -469,7 +552,8 @@ wss.on('connection', (ws) => {
roomCode: ws.roomCode,
puzzle: removeProp(currentPuzzle,'answer'),
turn:room.gameState.turn,
turnState:room.gameState.turnState
turnState:room.gameState.turnState,
playerStats:room.gameState.players.map(({id,...rest}) => rest)
}))
})
@ -498,29 +582,29 @@ wss.on('connection', (ws) => {
if (spinResult != ['lose a turn', 'spin again', 'Bankrupt'].indexOf(spinResult)) {
room.gameState.turnState = 'guess'
room.gameState.players = room.gameState.players.map((player) => {
return player.id == ws.identifierToken ? {...player, points:parseInt(spinResult)} : player
return player.id === ws.identifierToken ? {...player, points:parseInt(player.points)+parseInt(spinResult)} : player
})
}
if (spinResult == 'Bankrupt') {
if (spinResult === 'Bankrupt') {
room.gameState.players = room.gameState.players.map((player) => {
return player.id == ws.identifierToken ? {...player, points:0} : player
return player.id === ws.identifierToken ? {...player, points:0} : player
})
}
if (spinResult == 'spin again') {
if (spinResult === 'spin again') {
console.log('in spin again')
room.gameState.turnState = 'spin'
room.gameState.players = room.gameState.players.map((player) => {
return player.id == ws.identifierToken ? {...player, points:player.points + 0, condition:'spin again'} : player
return player.id === ws.identifierToken ? {...player, points:player.points + 0, condition:'spin again'} : player
})
}
if (spinResult == 'lose a turn') {
if (spinResult === 'lose a turn') {
console.log('lose a turn here ig...?')
changeTurn(room.gameState,ws)
}
room.gameState.players = room.gameState.players.map((player) => {
return player.id == ws.identifierToken ? {...player, points:player.points + 0} : player
return player.id === ws.identifierToken ? {...player, points:player.points + 0} : player
})
console.log('players', room.gameState.players)
room.gameState.spinResult = spinResult
@ -529,8 +613,9 @@ wss.on('connection', (ws) => {
room.clients.forEach((client) =>
client.send(JSON.stringify({
type: 'spin_result', spinResult,
player: ws === room.leader ? 'Leader' : 'Player',
turnState: room.gameState.turnState
player: room.gameState.players[room.gameState.turn],
turnState: room.gameState.turnState,
playerStats:room.gameState.players.map(({id,...rest}) => rest)
}))
)
}
@ -557,8 +642,9 @@ wss.on('connection', (ws) => {
client.send(JSON.stringify(
{ type: 'guess_result', letter,
correct: guessResult,
player: ws === room.leader ? 'Leader' : 'Player',
turnState:room.gameState.turnState
player: room.gameState.players[room.gameState.turn],
turnState:room.gameState.turnState,
playerStats:room.gameState.players.map(({id,...rest}) => rest)
}))
})
@ -567,8 +653,11 @@ wss.on('connection', (ws) => {
}
else if(guessResult === 'puzzleSolved') {
rewardUser(room.gameState,ws)
if (!checkWinState(room.gameState,ws)) {
console.log('winstate should be false here 583')
loadNewPuzzle(room.gameState,ws)
}
}
else {
//the player guessed correctly and its still their turn
room.gameState.turnState = 'spin'
@ -577,10 +666,11 @@ wss.on('connection', (ws) => {
client.send(JSON.stringify(
{ type: 'guess_result', letter,
correct: guessResult,
player: ws === room.leader ? 'Leader' : 'Player',
player: room.gameState.players[room.gameState.turn],
puzzle: room.gameState.puzzles[room.gameState.puzzleLevel],
turn:room.gameState.turn,
turnState:room.gameState.turnState
turnState:room.gameState.turnState,
playerStats:room.gameState.players.map(({id,...rest}) => rest)
}))
)
}
@ -598,6 +688,8 @@ wss.on('connection', (ws) => {
const room = rooms[ws.roomCode]
const roomCode = ws.roomCode
room.clients = room.clients.filter((client) => client !== ws)
room.gameState.players = room.gameState.players.filter((client)=> client.id != ws.identifierToken)
//decide who's turn it is based on who leaves...
if (room.leader === ws && room.clients.length > 0) {
console.log('closing within room leader')
room.leader = room.clients[0]