WheelOfFortune/index.html

342 lines
12 KiB
HTML
Raw Normal View History

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Multiplayer Game</title>
<link rel="stylesheet" type="text/css" href="mflx.min.css">
<style type="text/css">
.text-with-shadow {
text-shadow: -1px -1px 1px #000, 1px -1px 1px #000,
-1px 1px 1px #000, 1px 1px 1px #000; color: white;
}
</style>
</head>
<body>
<button id="create-room">Create Room</button>
<input id="join-code" placeholder="Enter room code">
<button id="join-room">Join Room</button>
<div class="flx(wrap) players"></div>
<div id="status"></div>
<button id="start-game" style="display: none;">Start Game</button>
<button id="spin-wheel" style="display: none;">Spin Wheel</button>
<input id="guess-letter" placeholder="Guess a letter" style="display: none;">
<button id="guess-button" style="display: none;">Guess</button>
<div style="display:relative;">
<span style="position: absolute; top: 0; left:50%">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>arrow-down-bold</title><path d="M9,4H15V12H19.84L12,19.84L4.16,12H9V4Z" /></svg>
</span>
<canvas id="wheelCanvas" width="500" height="500"></canvas>
</div>
<script>
//================general Purpose functions=========================================//
function cryptoSecureShuffle(array) {
const shuffledArray = [...array]; // Create a copy to avoid mutating the original array
const n = shuffledArray.length;
// Fisher-Yates shuffle
for (let i = n - 1; i > 0; i--) {
// Generate a cryptographically secure random index
let randIndex;
do {
// Generate a random value in the range [0, 2^32)
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer);
randIndex = randomBuffer[0] >>> 0; // Convert to a non-negative integer
} while (randIndex >= Math.floor(2 ** 32 / (i + 1)) * (i + 1)); // Avoid bias
// Compute the unbiased index
randIndex %= (i + 1);
// Swap the elements
[shuffledArray[i], shuffledArray[randIndex]] = [shuffledArray[randIndex], shuffledArray[i]];
}
return shuffledArray;
}
//====================making Name Tags/ assigning colors to names================//
let nameColors = [
'#ff0000','#ff8700','#ffd300','#deff0a','#a1ff0a',
'#0aff99','#0aefff','#147df5','#580aff','#be0aff'
]
nameColors = cryptoSecureShuffle(nameColors);
function assignColors(names, colors) {
let result = [];
let n = 0; // Keep track of name index
let c = 0; // Keep track of color index
if (names.length > colors.length) {
// Assign colors cyclically
while (n < names.length) {
result.push({ name: names[n], color: colors[c] });
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], color: colors[c] });
n++;
c++;
}
}
return result;
}
//=========================================wheel==========================================//
const wheel = [
'lose a turn', 800, 350, 450, 700, 300, 600, 5000,
300, 600, 300, 500, 800, 550, 400, 300, 900, 500, 'spin again',
900, 'Bankrupt', 600, 400, 300
];
const wheelSpinSpeedData = {
'0':0.2523,//lose a turn
'1':.2497,//800
'2':.2471,//350
'3':.2445,//450
'4':.2418,//450
'5':.2392,//300
'6':.2366,//600
'7':.2339,//5000
'8':.2313,//300
'9':.2287,//600
'10':.2261,//300
'11':.2235,//500
'12':.2208,//800
'13':.2182,//550
'14':.2156,//400
'15':.213,//300
'16':.2104,//900
'17':.2078,//500
'18':.2052,//spin again
'19':.2026,//900
'20':.1999,//Bankrupt
'21':.1973,//600
'22':.1947,//400
'23':.1921//300
};
const canvas = document.getElementById('wheelCanvas');
const ctx = canvas.getContext('2d');
const radius = canvas.width / 2;
let rotation = 0 - (.283*6); //sets the zero index on top
let spinning = false;
let spinSpeed = 0;
let img = new Image();
img.src = "arrow-down-bold.png";
img.onload = function() {
ctx.drawImage(img, 200, -50, 100,100);
}
// Draw the wheel
function drawWheel(drawResult = false) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(radius, radius);
ctx.rotate(rotation);
const anglePerSegment = (2 * Math.PI) / wheel.length;
wheel.forEach((value, i) => {
const startAngle = i * anglePerSegment;
const endAngle = startAngle + anglePerSegment;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.arc(0, 0, radius, startAngle, endAngle);
ctx.closePath();
ctx.fillStyle = i % 2 === 0 ? '#ffdd99' : '#ffeecc';
ctx.fill();
ctx.stroke();
// Add text
ctx.save();
ctx.translate(
Math.cos(startAngle + anglePerSegment / 2) * radius * 0.7,
Math.sin(startAngle + anglePerSegment / 2) * radius * 0.7
);
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.restore();
});
ctx.restore();
ctx.drawImage(img, 200, -50, 100,100);
}
// Start spinning
function startSpin(targetIndex) {
console.log('targetIndex: ',targetIndex);
let resultingSpeed = wheelSpinSpeedData[targetIndex];
console.log('resultingSpeed: ', resultingSpeed);
if (spinning) return;
rotation = 0 - (.283*6)
spinning = true;
const totalSpins = Math.floor(Math.random() * 3) + 3; // 3-6 full spins
const anglePerSegment = (2 * Math.PI) / wheel.length;
const targetAngle = targetIndex * anglePerSegment;
console.log(anglePerSegment);
let currentRotation = rotation; // Start from the current rotation
spinSpeed = wheelSpinSpeedData[targetIndex]; // Initial speed
function animate() {
if ( spinSpeed < 0.001) {
spinning = false;
console.log(`Landed on: ${wheel[targetIndex]}`);
return;
}
// console.log('currentRotation: ',currentRotation);
// console.log('spinSpeed: ', spinSpeed);
currentRotation += spinSpeed;
spinSpeed *= 0.99; // Gradual slowdown
rotation = currentRotation ;
drawWheel();
requestAnimationFrame(animate);
}
animate();
}
// Simulate WebSocket server response
// function simulateServerResponse() {
// const targetIndex = Math.floor(Math.random() * wheel.length); // Random result
// startSpin(targetIndex);
// }
// Initial draw
drawWheel();
// Trigger spin after 2 seconds
//setTimeout(simulateServerResponse, 2000);
//==================================end of Wheel=====================================//
function drawPlayers(message) {
let players = document.querySelector('.players');
//assignColors(names, colors) {
let processedNametags = assignColors(message.clients,nameColors);
const playersHtml = processedNametags.map(client => {
if (client.name === message.leaderName) {
return `<span class='mr-2 btn is-round text-with-shadow' style='background-color:${client.color};'>⭐ ${client.name} ⭐</span>`; // Highlight the leader with stars
} else {
return `<span class='mr-2 btn is-round text-with-shadow' style='background-color:${client.color};'>${client.name}</span>`;
}
}).join(""); // Combine all elements into a single string
players.innerHTML = playersHtml;
}
const socket = new WebSocket("ws://localhost:8080");
document.getElementById("create-room").onclick = () => {
socket.send(JSON.stringify({ type: "create_room" }));
};
document.getElementById("join-room").onclick = () => {
const roomCode = document.getElementById("join-code").value;
socket.send(JSON.stringify({ type: "join_room", roomCode }));
};
document.getElementById("start-game").onclick = () => {
socket.send(JSON.stringify({ type: "start_game" }));
};
document.getElementById("spin-wheel").onclick = () => {
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
};
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.type === "room_created") {
document.getElementById("status").innerText = `Room created! Code: ${message.roomCode}`;
drawPlayers(message);
if (message.isLeader) {
document.getElementById("start-game").style.display = "inline";
}
}
if (message.type === "joined_room") {
drawPlayers(message);
const status = message.isLeader ? "You are the party leader!" : "You joined the room!";
// document.querySelector('.players').innerHtml += `<span>${}<span>`
document.getElementById("status").innerText = `Room Code: ${message.roomCode} - ${status}`;
if (message.isLeader) {
document.getElementById("start-game").style.display = "inline";
document.getElementById("spin-wheel").style.display = "inline";
document.getElementById("guess-letter").style.display = "inline";
document.getElementById("guess-button").style.display = "inline";
}
}
if (message.type === "game_started") {
document.getElementById("status").innerText = "The game has started!";
document.getElementById("start-game").style.display = "none";
document.getElementById("start-game").style.display = "inline";
document.getElementById("spin-wheel").style.display = "inline";
document.getElementById("guess-letter").style.display = "inline";
document.getElementById("guess-button").style.display = "inline";
}
if (message.type === "spin_result") {
console.log('spin result recieved');
document.getElementById("status").innerText = `Spin result: ${message.spinResult} points (${message.player})`;
//find target index
let targetIndexArr = wheel.entries();
let filterResultsArr = [];
for(let x of targetIndexArr){
if (x[1] == message.spinResult) {
filterResultsArr.push(x);
}
}
console.log(filterResultsArr[0][0]);
//if there is multiple entries where the spin exists pick a random index.
if(filterResultsArr.length > 1) {
startSpin(filterResultsArr[Math.floor(Math.random() * filterResultsArr.length)][0]);
}
else{
startSpin(filterResultsArr[0]);
}
}
if (message.type === "guess_result") {
const outcome = message.correct ? "correct" : "incorrect";
document.getElementById("status").innerText = `Guess '${message.letter}' was ${outcome} (${message.player})`;
}
if (message.type === "new_leader") {
drawPlayers(message);
document.getElementById("status").innerText = "You are now the party leader!";
}
if (message.type === "error") {
alert(message.message);
}
};
</script>
</body>
</html>