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

178
server.js
View File

@ -1,11 +1,12 @@
const WebSocket = require('ws') const WebSocket = require('ws')
const { v4: uuidv4 } = require('uuid') const { v4: uuidv4 } = require('uuid')
const puzzles = require('./puzzles.json') const puzzles = require('./puzzles2.json')
const names = require('./assignedNames.json') const names = require('./assignedNames.json')
const crypto = require('crypto') const crypto = require('crypto')
const wss = new WebSocket.Server({ port: 8080 }) const wss = new WebSocket.Server({ port: 8080 })
const rooms = {} // Stores rooms and their clients const rooms = {} // Stores rooms and their clients
const wheel = [ const wheel = [
'lose a turn',800,350,450,700,300,600,5000, 'lose a turn',800,350,450,700,300,600,5000,
300,600,300,500,800,550,400,300,900,500,'spin again', 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) { 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`) 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) { function processPuzzle(letterArray,given) {
let puzzleArray = [] let puzzleArray = []
for (let letter of letterArray) { for (let letter of letterArray) {
if (letter == ' ') { if (letter === ' ') {
puzzleArray.push(' ') puzzleArray.push(' ')
continue continue
} }
let letterFound = false let letterFound = false
for (let g of given ) { for (let g of given ) {
if(g.toUpperCase() == letter.toUpperCase()) { if(g.toUpperCase() === letter.toUpperCase()) {
puzzleArray.push(g) puzzleArray.push(g)
letterFound = true letterFound = true
} }
@ -146,9 +147,9 @@ function checkGuess(letter,gameStateObject) {
const currentPuzzle = gameStateObject.puzzles[gameStateObject.puzzleLevel] const currentPuzzle = gameStateObject.puzzles[gameStateObject.puzzleLevel]
console.log(currentPuzzle) console.log(currentPuzzle)
if (typeof currentPuzzle.answer == 'string') { if (typeof currentPuzzle.answer === 'string') {
//check if user already guessed one of teh given letters //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...') console.log('user gave a guess on a given letter...')
return false return false
} }
@ -157,7 +158,7 @@ function checkGuess(letter,gameStateObject) {
let matches = [] let matches = []
for(const c in charArray) { for(const c in charArray) {
const char = charArray[c] const char = charArray[c]
if (letter.toUpperCase() == char.toUpperCase()) { if (letter.toUpperCase() === char.toUpperCase()) {
matches.push({id:c,letter:char}) matches.push({id:c,letter:char})
} }
} }
@ -181,11 +182,63 @@ function checkGuess(letter,gameStateObject) {
} }
} }
else if (Array.isArray(currentPuzzle.answer)) { 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]) 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) { function checkSolvePuzzleGuess(guess,ws) {
const room = rooms[ws.roomCode] const room = rooms[ws.roomCode]
console.log(room.gameState) console.log(room.gameState)
@ -195,13 +248,23 @@ function checkSolvePuzzleGuess(guess,ws) {
console.log(guess.toUpperCase(),room.gameState.puzzles[room.gameState.puzzleLevel].answer.toUpperCase()) console.log(guess.toUpperCase(),room.gameState.puzzles[room.gameState.puzzleLevel].answer.toUpperCase())
//guess is wrong change turns //guess is wrong change turns
console.log('guess is incorrect') 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) changeTurn(room.gameState,ws)
} }
else { else {
console.log('guess i correct') console.log('guess i correct')
//guessed correctly reward the user //guessed correctly reward the user
rewardUser(room.gameState,ws,true) rewardUser(room.gameState,ws,true)
loadNewPuzzle(room.gameState,ws) if (!checkWinState(room.gameState,ws)) {
console.log('winstate should be false here 214')
loadNewPuzzle(room.gameState,ws)
}
} }
} }
else { else {
@ -219,25 +282,29 @@ function checkSolvePuzzleGuess(guess,ws) {
//correct //correct
console.log('correct.',guess.toUpperCase(),answer.toUpperCase()) console.log('correct.',guess.toUpperCase(),answer.toUpperCase())
rewardUser(room.gameState,ws,true) rewardUser(room.gameState,ws,true)
loadNewPuzzle(room.gameState,ws) if (!checkWinState(room.gameState,ws)) {
console.log('winstate should be false here 236')
loadNewPuzzle(room.gameState,ws)
}
} }
} }
} }
function announceWinner(gameStateObject,ws) { function announceWinner(gameStateObject,ws) {
//find user with highest points. //find user with highest points.
//announce to the world. //announce to the world.
const room = rooms[ws.roomCode] 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) console.log(winner)
//needs to be tested on multiple winners and decide ties.
room.clients.forEach((client) => { room.clients.forEach((client) => {
client.send(JSON.stringify({ client.send(JSON.stringify({
type:'game_over', 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!!! //these functions must have both gameStateobject and websockets initialized before use!!!
function rewardUser(gameStateObject,ws,puzzleSolved = false) { function rewardUser(gameStateObject,ws,puzzleSolved = false) {
@ -251,10 +318,7 @@ function rewardUser(gameStateObject,ws,puzzleSolved = false) {
currentUserTurn.points = currentUserTurn.points*3 currentUserTurn.points = currentUserTurn.points*3
console.log(currentUserTurn.points) console.log(currentUserTurn.points)
} }
if (gameStateObject.puzzleLevel == gameStateObject.puzzles.length-1) {
announceWinner(gameStateObject,ws)
return
}
room.clients.forEach((client) => { room.clients.forEach((client) => {
client.send(JSON.stringify({ client.send(JSON.stringify({
type: 'puzzle_solved', roomCode, type: 'puzzle_solved', roomCode,
@ -263,9 +327,10 @@ function rewardUser(gameStateObject,ws,puzzleSolved = false) {
}) })
} }
function changeTurn(gameStateObject,ws) { function changeTurn(gameStateObject,ws) {
console.log('change turn hit')
const room = rooms[ws.roomCode] const room = rooms[ws.roomCode]
if (gameStateObject.turn == gameStateObject.players.length - 1) { if (gameStateObject.turn === gameStateObject.players.length - 1) {
gameStateObject.turn = 0 gameStateObject.turn = 0
} }
else gameStateObject.turn++ else gameStateObject.turn++
@ -279,6 +344,7 @@ function changeTurn(gameStateObject,ws) {
}) })
} }
function loadNewPuzzle(gameStateObject,ws) { function loadNewPuzzle(gameStateObject,ws) {
console.log('loadNewPuzzle called.')
const room = rooms[ws.roomCode] const room = rooms[ws.roomCode]
const newPuzzle = loadCurrentPuzzle(gameStateObject) const newPuzzle = loadCurrentPuzzle(gameStateObject)
room.gameState.turnState = 'spin' room.gameState.turnState = 'spin'
@ -292,7 +358,8 @@ function loadNewPuzzle(gameStateObject,ws) {
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
puzzle: removeProp(newPuzzle,'answer'), puzzle: removeProp(newPuzzle,'answer'),
turn:room.gameState.turn, 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 // //assumes ws message is sent and room code exists
// for(const c in room.clients) { // for(const c in room.clients) {
// const client = room.clients[c] // 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 // return true
// } // }
// } // }
@ -320,7 +387,7 @@ wss.on('connection', (ws) => {
const room = rooms[ws.roomCode] const room = rooms[ws.roomCode]
console.log(room) console.log(room)
console.log(room.leader.name,room.clients[0].name) 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) console.log(ws.name,ws.identifierToken)
//change names in all places. //change names in all places.
//if the leader wants to change their name account for this //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 //find the names by index using the identifier Token which i user can't easily create
//a name collision. //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) console.log(nameToChange)
if (nameToChange != -1) { if (nameToChange != -1) {
room.clients[nameToChange].name = data.newName 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 room.leader.name = data.newName
} }
//if the user is not the leader, in theory just change the name on the clients list //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') { if (data.type === 'solve_puzzle') {
console.log('solve_puzzle hit') 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) checkSolvePuzzleGuess(data.guess, ws)
} }
if (data.type === 'confirm_id') { if (data.type === 'confirm_id') {
const room = rooms[ws.roomCode] const room = rooms[ws.roomCode]
const currentUserTurn = room.gameState.players[room.gameState.turn] const currentUserTurn = room.gameState.players[room.gameState.turn]
room.gameState.turnState = 'spin' 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})) 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') { if (data.type === 'create_room') {
const roomCode = uuidv4().slice(0, 5) const roomCode = uuidv4().slice(0, 5)
@ -456,7 +539,7 @@ wss.on('connection', (ws) => {
}) })
//console.log(room.gameState) //console.log(room.gameState)
console.log('game started for:',room) 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) { if (selectedPlayer) {
console.log('hit') console.log('hit')
selectedPlayer.send(JSON.stringify({type:'your_turn'})) selectedPlayer.send(JSON.stringify({type:'your_turn'}))
@ -469,7 +552,8 @@ wss.on('connection', (ws) => {
roomCode: ws.roomCode, roomCode: ws.roomCode,
puzzle: removeProp(currentPuzzle,'answer'), puzzle: removeProp(currentPuzzle,'answer'),
turn:room.gameState.turn, 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)) { if (spinResult != ['lose a turn', 'spin again', 'Bankrupt'].indexOf(spinResult)) {
room.gameState.turnState = 'guess' room.gameState.turnState = 'guess'
room.gameState.players = room.gameState.players.map((player) => { 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) => { 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') console.log('in spin again')
room.gameState.turnState = 'spin' room.gameState.turnState = 'spin'
room.gameState.players = room.gameState.players.map((player) => { 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...?') console.log('lose a turn here ig...?')
changeTurn(room.gameState,ws) changeTurn(room.gameState,ws)
} }
room.gameState.players = room.gameState.players.map((player) => { 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) console.log('players', room.gameState.players)
room.gameState.spinResult = spinResult room.gameState.spinResult = spinResult
@ -529,8 +613,9 @@ wss.on('connection', (ws) => {
room.clients.forEach((client) => room.clients.forEach((client) =>
client.send(JSON.stringify({ client.send(JSON.stringify({
type: 'spin_result', spinResult, type: 'spin_result', spinResult,
player: ws === room.leader ? 'Leader' : 'Player', player: room.gameState.players[room.gameState.turn],
turnState: room.gameState.turnState turnState: room.gameState.turnState,
playerStats:room.gameState.players.map(({id,...rest}) => rest)
})) }))
) )
} }
@ -557,8 +642,9 @@ wss.on('connection', (ws) => {
client.send(JSON.stringify( client.send(JSON.stringify(
{ type: 'guess_result', letter, { type: 'guess_result', letter,
correct: guessResult, correct: guessResult,
player: ws === room.leader ? 'Leader' : 'Player', player: room.gameState.players[room.gameState.turn],
turnState:room.gameState.turnState turnState:room.gameState.turnState,
playerStats:room.gameState.players.map(({id,...rest}) => rest)
})) }))
}) })
@ -567,7 +653,10 @@ wss.on('connection', (ws) => {
} }
else if(guessResult === 'puzzleSolved') { else if(guessResult === 'puzzleSolved') {
rewardUser(room.gameState,ws) rewardUser(room.gameState,ws)
loadNewPuzzle(room.gameState,ws) if (!checkWinState(room.gameState,ws)) {
console.log('winstate should be false here 583')
loadNewPuzzle(room.gameState,ws)
}
} }
else { else {
//the player guessed correctly and its still their turn //the player guessed correctly and its still their turn
@ -577,10 +666,11 @@ wss.on('connection', (ws) => {
client.send(JSON.stringify( client.send(JSON.stringify(
{ type: 'guess_result', letter, { type: 'guess_result', letter,
correct: guessResult, correct: guessResult,
player: ws === room.leader ? 'Leader' : 'Player', player: room.gameState.players[room.gameState.turn],
puzzle: room.gameState.puzzles[room.gameState.puzzleLevel], puzzle: room.gameState.puzzles[room.gameState.puzzleLevel],
turn:room.gameState.turn, 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 room = rooms[ws.roomCode]
const roomCode = ws.roomCode const roomCode = ws.roomCode
room.clients = room.clients.filter((client) => client !== ws) 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) { if (room.leader === ws && room.clients.length > 0) {
console.log('closing within room leader') console.log('closing within room leader')
room.leader = room.clients[0] room.leader = room.clients[0]