initial commit

This commit is contained in:
2026-02-18 13:55:52 +00:00
commit 973fd9ba9b
8 changed files with 3043 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules/

1076
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

14
package.json Normal file
View File

@@ -0,0 +1,14 @@
{
"name": "riddle-racer",
"version": "1.0.0",
"description": "Multiplayer riddle racing game",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"socket.io": "^4.7.2"
}
}

434
public/game.js Normal file
View File

@@ -0,0 +1,434 @@
/* ═══════════════════════════════════════
RIDDLE RACER client-side game logic
═══════════════════════════════════════ */
const socket = io();
const FINISH_LINE = 10;
const CAR_EMOJIS = ['🏎️', '🚗', '🚕', '🚙', '🚓', '🚑', '🚐', '🚌'];
// ── State ──────────────────────────────
let myRoomId = null;
let amHost = false;
let myFinished = false;
let carEmojiMap = {}; // playerId → car emoji
// ── Screen helpers ─────────────────────
const screens = {
home: document.getElementById('home-screen'),
lobby: document.getElementById('lobby-screen'),
game: document.getElementById('game-screen'),
results: document.getElementById('results-screen'),
};
function showScreen(name) {
Object.values(screens).forEach(s => s.classList.remove('active'));
screens[name].classList.add('active');
}
// ── DOM refs ───────────────────────────
const nameInput = document.getElementById('name-input');
const codeInput = document.getElementById('code-input');
const errorMsg = document.getElementById('error-msg');
const createBtn = document.getElementById('create-btn');
const joinBtn = document.getElementById('join-btn');
const roomCodeEl = document.getElementById('room-code');
const copyBtn = document.getElementById('copy-btn');
const playerListEl = document.getElementById('player-list');
const playerCount = document.getElementById('player-count');
const startBtn = document.getElementById('start-btn');
const waitingMsg = document.getElementById('waiting-msg');
const gameBadge = document.getElementById('game-room-badge');
const raceTrack = document.getElementById('race-track');
const riddlePanel = document.getElementById('riddle-panel');
const riddleNumEl = document.getElementById('riddle-num');
const riddleTotEl = document.getElementById('riddle-total');
const progressFill = document.getElementById('progress-fill');
const riddleQ = document.getElementById('riddle-question');
const answerInput = document.getElementById('answer-input');
const submitBtn = document.getElementById('submit-btn');
const hintBtn = document.getElementById('hint-btn');
const feedbackEl = document.getElementById('feedback');
const hintBox = document.getElementById('hint-box');
const hintText = document.getElementById('hint-text');
const finishedBanner = document.getElementById('finished-banner');
const finishedTrophy = document.getElementById('finished-trophy');
const finishedText = document.getElementById('finished-text');
const resultsList = document.getElementById('results-list');
const playAgainBtn = document.getElementById('play-again-btn');
const hostOnlyMsg = document.getElementById('host-only-msg');
// ══════════════════════════════════════════════
// HOME SCREEN
// ══════════════════════════════════════════════
// Tab switching
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
const tab = btn.dataset.tab;
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
btn.classList.add('active');
document.getElementById(`${tab}-tab`).classList.add('active');
clearError();
});
});
createBtn.addEventListener('click', () => {
const name = nameInput.value.trim();
if (!name) return showError('Please enter your racing name first.');
clearError();
createBtn.disabled = true;
socket.emit('createRoom', { name });
});
joinBtn.addEventListener('click', () => {
const name = nameInput.value.trim();
const code = codeInput.value.trim().toUpperCase();
if (!name) return showError('Please enter your racing name first.');
if (!code) return showError('Please enter the room code.');
clearError();
joinBtn.disabled = true;
socket.emit('joinRoom', { name, code });
});
nameInput.addEventListener('keydown', e => {
if (e.key === 'Enter') createBtn.click();
});
codeInput.addEventListener('keydown', e => {
if (e.key === 'Enter') joinBtn.click();
});
codeInput.addEventListener('input', () => {
codeInput.value = codeInput.value.toUpperCase();
});
function showError(msg) {
errorMsg.textContent = msg;
}
function clearError() {
errorMsg.textContent = '';
}
function resetHomeButtons() {
createBtn.disabled = false;
joinBtn.disabled = false;
}
// ══════════════════════════════════════════════
// LOBBY SCREEN
// ══════════════════════════════════════════════
copyBtn.addEventListener('click', () => {
navigator.clipboard.writeText(myRoomId).then(() => showNotif('Room code copied! 📋'));
});
startBtn.addEventListener('click', () => {
socket.emit('startGame');
});
function renderLobbyPlayers(players) {
playerCount.textContent = players.length;
playerListEl.innerHTML = players.map((p, i) => {
const isMe = p.id === socket.id;
const isHost = i === 0; // first player is host (by join order)
return `
<div class="lobby-player" style="border-left-color: ${p.color}">
<span style="color:${p.color}">${escHtml(p.name)}</span>
<span style="display:flex;gap:6px">
${isHost ? '<span class="host-badge">Host</span>' : ''}
${isMe ? '<span class="you-badge">You</span>' : ''}
</span>
</div>
`;
}).join('');
}
// ══════════════════════════════════════════════
// GAME SCREEN
// ══════════════════════════════════════════════
// Assign a car emoji to each player consistently
function assignCarEmojis(players) {
players.forEach((p, i) => {
if (!carEmojiMap[p.id]) {
carEmojiMap[p.id] = CAR_EMOJIS[i % CAR_EMOJIS.length];
}
});
}
function renderTrack(players) {
assignCarEmojis(players);
raceTrack.innerHTML = players.map(p => {
const pct = Math.min((p.position / FINISH_LINE) * 88 + 4, 92);
const carEmoji = carEmojiMap[p.id] || '🏎️';
const isMe = p.id === socket.id;
return `
<div class="track-row" data-player-id="${p.id}">
<div class="player-label" style="color:${p.color}" title="${escHtml(p.name)}">
${isMe ? '▶ ' : ''}${escHtml(p.name)}
</div>
<div class="track-bar">
<span class="car-emoji" id="car-${p.id}" style="left:${pct}%">${carEmoji}</span>
</div>
<div class="finish-col">
<span class="finish-flag">🏁</span>
${p.finishPosition ? `<span class="place-badge">${getOrdinal(p.finishPosition)}</span>` : ''}
</div>
</div>
`;
}).join('');
}
function updateTrack(players) {
assignCarEmojis(players);
players.forEach(p => {
const carEl = document.getElementById(`car-${p.id}`);
if (!carEl) return;
const pct = Math.min((p.position / FINISH_LINE) * 88 + 4, 92);
const oldLeft = parseFloat(carEl.style.left);
if (Math.abs(pct - oldLeft) > 0.1) {
carEl.style.left = `${pct}%`;
// Trigger boost animation
carEl.classList.remove('boosting');
void carEl.offsetWidth; // reflow
carEl.classList.add('boosting');
setTimeout(() => carEl.classList.remove('boosting'), 450);
}
// Update place badge
const row = document.querySelector(`.track-row[data-player-id="${p.id}"]`);
if (row) {
const finishCol = row.querySelector('.finish-col');
const existing = finishCol.querySelector('.place-badge');
if (p.finishPosition && !existing) {
finishCol.insertAdjacentHTML('beforeend',
`<span class="place-badge">${getOrdinal(p.finishPosition)}</span>`);
}
}
});
}
function showRiddle(riddle, num, total) {
riddleNumEl.textContent = num;
riddleTotEl.textContent = total;
riddleQ.textContent = riddle.question;
progressFill.style.width = `${((num - 1) / total) * 100}%`;
answerInput.value = '';
feedbackEl.textContent = '';
feedbackEl.className = 'feedback';
hintBox.style.display = 'none';
hintText.textContent = '';
answerInput.focus();
}
function setFeedback(msg, isCorrect) {
feedbackEl.textContent = msg;
feedbackEl.className = `feedback ${isCorrect ? 'correct' : 'wrong'}`;
if (!isCorrect) {
// Shake the input
answerInput.style.borderColor = 'var(--accent-red)';
setTimeout(() => answerInput.style.borderColor = '', 700);
}
}
submitBtn.addEventListener('click', submitAnswer);
answerInput.addEventListener('keydown', e => {
if (e.key === 'Enter') submitAnswer();
});
function submitAnswer() {
if (myFinished) return;
const answer = answerInput.value.trim();
if (!answer) return;
socket.emit('submitAnswer', { answer });
submitBtn.disabled = true;
setTimeout(() => { submitBtn.disabled = false; }, 300);
}
hintBtn.addEventListener('click', () => {
socket.emit('getHint');
});
// ══════════════════════════════════════════════
// RESULTS SCREEN
// ══════════════════════════════════════════════
playAgainBtn.addEventListener('click', () => {
if (amHost) {
socket.emit('playAgain');
} else {
showNotif('Only the host can restart the race!');
}
});
function renderResults(results) {
const medals = ['🥇', '🥈', '🥉'];
resultsList.innerHTML = results.map((r, i) => `
<div class="result-item">
${i < 3
? `<span class="result-medal">${medals[i]}</span>`
: `<span class="result-place">${r.place}.</span>`
}
<span class="result-name" style="color:${r.color}">${escHtml(r.name)}</span>
</div>
`).join('');
if (amHost) {
playAgainBtn.style.display = 'block';
hostOnlyMsg.style.display = 'none';
} else {
playAgainBtn.style.display = 'none';
hostOnlyMsg.style.display = 'block';
}
}
// ══════════════════════════════════════════════
// SOCKET EVENTS
// ══════════════════════════════════════════════
socket.on('roomCreated', ({ roomId }) => {
myRoomId = roomId;
amHost = true;
resetHomeButtons();
});
socket.on('joinedRoom', ({ roomId }) => {
myRoomId = roomId;
amHost = false;
resetHomeButtons();
});
socket.on('joinError', msg => {
showError(msg);
resetHomeButtons();
});
socket.on('lobbyState', ({ players, isHost, roomId }) => {
myRoomId = roomId;
amHost = isHost;
myFinished = false;
carEmojiMap = {};
roomCodeEl.textContent = roomId;
startBtn.style.display = isHost ? 'block' : 'none';
waitingMsg.style.display = isHost ? 'none' : 'block';
renderLobbyPlayers(players);
showScreen('lobby');
});
socket.on('playerUpdate', ({ players, message, newHost }) => {
if (newHost && newHost === socket.id) {
amHost = true;
startBtn.style.display = 'block';
waitingMsg.style.display = 'none';
}
renderLobbyPlayers(players);
if (message) showNotif(message);
});
socket.on('gameStarted', ({ players, riddle, riddleNum, total }) => {
myFinished = false;
gameBadge.textContent = myRoomId;
// Reset game UI
riddlePanel.style.display = 'block';
finishedBanner.style.display = 'none';
assignCarEmojis(players);
renderTrack(players);
showRiddle(riddle, riddleNum, total);
showScreen('game');
});
socket.on('positionUpdate', ({ players }) => {
updateTrack(players);
});
socket.on('answerResult', ({ correct, finished, finishPosition, riddle, riddleNum, total }) => {
if (!correct) {
setFeedback('✗ Wrong! Try again.', false);
return;
}
if (finished) {
myFinished = true;
progressFill.style.width = '100%';
riddlePanel.style.display = 'none';
finishedBanner.style.display = 'flex';
const trophies = ['🏆', '🥈', '🥉', '🎖️'];
finishedTrophy.textContent = trophies[Math.min(finishPosition - 1, trophies.length - 1)] || '🎖️';
finishedText.textContent = `You finished ${getOrdinal(finishPosition)}!`;
} else {
setFeedback('✓ Correct! Keep going!', true);
setTimeout(() => {
if (!myFinished) showRiddle(riddle, riddleNum, total);
}, 600);
}
});
socket.on('playerFinished', ({ name, place }) => {
showNotif(`🏁 ${escHtml(name)} finished ${getOrdinal(place)}!`, true);
});
socket.on('hint', ({ hint }) => {
hintText.textContent = hint;
hintBox.style.display = 'block';
});
socket.on('gameOver', ({ results }) => {
renderResults(results);
showScreen('results');
});
socket.on('returnToLobby', ({ players }) => {
myFinished = false;
carEmojiMap = {};
startBtn.style.display = amHost ? 'block' : 'none';
waitingMsg.style.display = amHost ? 'none' : 'block';
renderLobbyPlayers(players);
showScreen('lobby');
});
socket.on('disconnect', () => {
showNotif('Connection lost. Refresh to reconnect.');
});
socket.on('connect_error', () => {
showError('Could not connect to server.');
});
// ══════════════════════════════════════════════
// UTILITIES
// ══════════════════════════════════════════════
function showNotif(msg, isFinish = false) {
const container = document.getElementById('notif-container');
const el = document.createElement('div');
el.className = `notif${isFinish ? ' finish-notif' : ''}`;
el.textContent = msg;
container.appendChild(el);
setTimeout(() => el.remove(), 3200);
}
function getOrdinal(n) {
const s = ['th', 'st', 'nd', 'rd'];
const v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
function escHtml(str) {
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}

169
public/index.html Normal file
View File

@@ -0,0 +1,169 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Riddle Racer 🏎️</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- ═══════════════════════════════════════════
HOME SCREEN
═══════════════════════════════════════════ -->
<div id="home-screen" class="screen active">
<div class="home-wrapper">
<div class="home-logo">
<div class="logo-cars">🏎️ 🚗 🚙</div>
<h1>Riddle Racer</h1>
<p class="tagline">Answer riddles. Move your car. Win the race!</p>
</div>
<div class="card">
<label class="input-label">Your Racing Name</label>
<input type="text" id="name-input" placeholder="e.g. SpeedDemon99" maxlength="20" autocomplete="off" />
<div class="tabs">
<button class="tab-btn active" data-tab="create">Create Room</button>
<button class="tab-btn" data-tab="join">Join Room</button>
</div>
<div id="create-tab" class="tab-content active">
<p class="tab-desc">Start a new race and invite friends with your room code.</p>
<button id="create-btn" class="btn btn-red">🚀 Create Race Room</button>
</div>
<div id="join-tab" class="tab-content">
<p class="tab-desc">Enter the room code your friend shared with you.</p>
<input type="text" id="code-input" placeholder="Room code (e.g. ABC123)" maxlength="6"
autocomplete="off" style="text-transform:uppercase; letter-spacing: 4px; font-size: 1.2rem;" />
<button id="join-btn" class="btn btn-blue">🚗 Join Race</button>
</div>
<div id="error-msg" class="error-msg"></div>
</div>
<p class="home-footer">Up to 8 players &bull; Answer 10 riddles to cross the finish line</p>
</div>
</div>
<!-- ═══════════════════════════════════════════
LOBBY SCREEN
═══════════════════════════════════════════ -->
<div id="lobby-screen" class="screen">
<div class="lobby-wrapper">
<div class="lobby-header">
<h1>🏎️ Riddle Racer</h1>
<div class="room-code-box">
<span class="room-code-label">Room Code</span>
<span id="room-code" class="room-code-val"></span>
<button id="copy-btn" class="btn-icon" title="Copy code">📋</button>
</div>
</div>
<div class="card">
<h3>Racers in the Lobby <span id="player-count" class="count-badge">0</span></h3>
<div id="player-list" class="player-list"></div>
<div class="lobby-actions">
<button id="start-btn" class="btn btn-green" style="display:none">🏁 Start the Race!</button>
<p id="waiting-msg" class="waiting-text" style="display:none">
⏳ Waiting for the host to start the race...
</p>
<p class="lobby-hint">Share the room code so friends can join!</p>
</div>
</div>
<div class="race-rules">
<div class="rule">🧩 Answer riddles correctly to move forward</div>
<div class="rule">🏎️ First to answer 10 riddles wins!</div>
<div class="rule">🏁 Race continues until everyone finishes</div>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════
GAME SCREEN
═══════════════════════════════════════════ -->
<div id="game-screen" class="screen">
<div class="game-wrapper">
<div class="game-topbar">
<span class="topbar-title">🏎️ Riddle Racer</span>
<span id="game-room-badge" class="room-badge"></span>
</div>
<!-- Race Track -->
<div class="track-section">
<div id="race-track" class="race-track"></div>
</div>
<!-- Riddle Panel (hidden when player finishes) -->
<div id="riddle-panel" class="riddle-panel">
<div class="riddle-header">
<span class="riddle-counter">🧩 Riddle <span id="riddle-num">1</span> of <span id="riddle-total">10</span></span>
<div class="progress-outer">
<div id="progress-fill" class="progress-fill" style="width:0%"></div>
</div>
</div>
<p id="riddle-question" class="riddle-question"></p>
<div class="answer-row">
<input type="text" id="answer-input" class="answer-input"
placeholder="Type your answer here..." autocomplete="off" />
<button id="submit-btn" class="btn btn-green submit-btn">Submit ➤</button>
</div>
<div class="riddle-footer">
<button id="hint-btn" class="btn btn-hint">💡 Hint</button>
<span id="feedback" class="feedback"></span>
</div>
<div id="hint-box" class="hint-box" style="display:none">
<span class="hint-label">💡 Hint:</span>
<span id="hint-text"></span>
</div>
</div>
<!-- Shown when this player finishes -->
<div id="finished-banner" class="finished-banner" style="display:none">
<div class="finished-inner">
<div class="finished-trophy" id="finished-trophy"></div>
<p id="finished-text"></p>
<p class="finished-sub">Watching others finish... 🍿</p>
</div>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════
RESULTS SCREEN
═══════════════════════════════════════════ -->
<div id="results-screen" class="screen">
<div class="results-wrapper">
<div class="results-header">
<div class="results-flags">🏁 🏁 🏁</div>
<h1>Race Complete!</h1>
<p class="results-sub">Final Standings</p>
</div>
<div id="results-list" class="results-list"></div>
<div class="results-actions">
<button id="play-again-btn" class="btn btn-red" style="display:none">🔄 Race Again!</button>
<p id="host-only-msg" class="waiting-text" style="display:none">
Waiting for the host to start a new race...
</p>
</div>
</div>
</div>
<!-- Notification container -->
<div id="notif-container"></div>
<script src="/socket.io/socket.io.js"></script>
<script src="game.js"></script>
</body>
</html>

871
public/style.css Normal file
View File

@@ -0,0 +1,871 @@
/* ═══════════════════════════════════════
BASE & RESET
═══════════════════════════════════════ */
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
:root {
--bg: #0f1117;
--surface: #1a1d2e;
--surface2: #232740;
--track-green: #0d3320;
--track-line: #1a5c3a;
--accent-yellow: #f5c518;
--accent-red: #e74c3c;
--accent-blue: #3498db;
--accent-green: #2ecc71;
--text: #eef0f7;
--text-muted: #8891a8;
--radius: 14px;
--shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
}
html, body {
height: 100%;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
overflow-x: hidden;
}
/* ═══════════════════════════════════════
SCREENS
═══════════════════════════════════════ */
.screen {
display: none;
min-height: 100vh;
}
.screen.active {
display: flex;
}
/* ═══════════════════════════════════════
SHARED COMPONENTS
═══════════════════════════════════════ */
.card {
background: var(--surface);
border-radius: var(--radius);
padding: 28px 32px;
box-shadow: var(--shadow);
border: 1px solid rgba(255, 255, 255, 0.06);
}
.btn {
display: inline-block;
padding: 13px 22px;
border: none;
border-radius: 10px;
font-size: 1rem;
font-weight: 700;
cursor: pointer;
transition: transform 0.1s, filter 0.15s;
letter-spacing: 0.3px;
text-align: center;
}
.btn:hover {
filter: brightness(1.12);
transform: translateY(-1px);
}
.btn:active {
transform: translateY(0);
filter: brightness(0.95);
}
.btn-red { background: var(--accent-red); color: #fff; }
.btn-blue { background: var(--accent-blue); color: #fff; }
.btn-green { background: var(--accent-green); color: #fff; }
.btn-hint { background: var(--surface2); color: var(--accent-yellow); border: 1px solid var(--accent-yellow); font-size: 0.9rem; padding: 9px 16px; }
.btn-icon {
background: none;
border: none;
font-size: 1.2rem;
cursor: pointer;
padding: 4px 8px;
border-radius: 8px;
transition: background 0.15s;
}
.btn-icon:hover {
background: rgba(255,255,255,0.1);
}
input[type="text"] {
display: block;
width: 100%;
padding: 13px 16px;
background: var(--surface2);
border: 2px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
color: var(--text);
font-size: 1rem;
margin-bottom: 14px;
transition: border-color 0.2s;
}
input[type="text"]:focus {
outline: none;
border-color: var(--accent-yellow);
}
input[type="text"]::placeholder {
color: var(--text-muted);
}
.error-msg {
color: var(--accent-red);
font-size: 0.9rem;
min-height: 22px;
text-align: center;
margin-top: 8px;
font-weight: 600;
}
.waiting-text {
color: var(--text-muted);
text-align: center;
font-size: 0.95rem;
}
/* ═══════════════════════════════════════
HOME SCREEN
═══════════════════════════════════════ */
#home-screen {
align-items: center;
justify-content: center;
padding: 20px;
background:
radial-gradient(ellipse at 20% 50%, rgba(231,76,60,0.15) 0%, transparent 60%),
radial-gradient(ellipse at 80% 50%, rgba(52,152,219,0.15) 0%, transparent 60%),
var(--bg);
}
.home-wrapper {
width: 100%;
max-width: 420px;
}
.home-logo {
text-align: center;
margin-bottom: 28px;
}
.logo-cars {
font-size: 2.8rem;
margin-bottom: 8px;
animation: carsSlide 3s ease-in-out infinite alternate;
}
@keyframes carsSlide {
from { letter-spacing: 2px; }
to { letter-spacing: 12px; }
}
.home-logo h1 {
font-size: 2.8rem;
font-weight: 900;
color: var(--accent-yellow);
text-shadow: 0 0 30px rgba(245, 197, 24, 0.5);
letter-spacing: -0.5px;
}
.tagline {
color: var(--text-muted);
margin-top: 6px;
font-size: 1rem;
}
.input-label {
display: block;
font-size: 0.85rem;
font-weight: 600;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.8px;
margin-bottom: 6px;
}
/* Tabs */
.tabs {
display: flex;
background: var(--surface2);
border-radius: 10px;
padding: 4px;
margin-bottom: 20px;
}
.tab-btn {
flex: 1;
padding: 10px;
border: none;
background: none;
border-radius: 8px;
color: var(--text-muted);
font-size: 0.95rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.tab-btn.active {
background: var(--surface);
color: var(--text);
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.tab-desc {
font-size: 0.88rem;
color: var(--text-muted);
margin-bottom: 14px;
line-height: 1.4;
}
.home-footer {
text-align: center;
color: var(--text-muted);
font-size: 0.82rem;
margin-top: 20px;
}
/* ═══════════════════════════════════════
LOBBY SCREEN
═══════════════════════════════════════ */
#lobby-screen {
align-items: center;
justify-content: center;
padding: 20px;
}
.lobby-wrapper {
width: 100%;
max-width: 480px;
}
.lobby-header {
text-align: center;
margin-bottom: 24px;
}
.lobby-header h1 {
font-size: 2rem;
color: var(--accent-yellow);
margin-bottom: 12px;
}
.room-code-box {
display: inline-flex;
align-items: center;
gap: 10px;
background: var(--surface2);
border-radius: 12px;
padding: 10px 20px;
border: 1px solid rgba(245, 197, 24, 0.3);
}
.room-code-label {
font-size: 0.8rem;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 1px;
}
.room-code-val {
font-size: 1.6rem;
font-weight: 900;
color: var(--accent-yellow);
letter-spacing: 6px;
font-family: monospace;
}
.lobby-wrapper .card h3 {
font-size: 1.05rem;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.8px;
margin-bottom: 16px;
display: flex;
align-items: center;
gap: 10px;
}
.count-badge {
background: var(--accent-yellow);
color: #111;
font-size: 0.8rem;
padding: 2px 9px;
border-radius: 20px;
font-weight: 800;
}
.player-list {
display: flex;
flex-direction: column;
gap: 10px;
min-height: 60px;
margin-bottom: 20px;
}
.lobby-player {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
background: var(--surface2);
border-radius: 10px;
border-left: 4px solid;
font-weight: 600;
animation: slideIn 0.25s ease;
}
@keyframes slideIn {
from { opacity: 0; transform: translateY(-8px); }
to { opacity: 1; transform: translateY(0); }
}
.you-badge {
background: var(--accent-yellow);
color: #111;
font-size: 0.72rem;
font-weight: 800;
padding: 2px 8px;
border-radius: 10px;
text-transform: uppercase;
}
.host-badge {
background: var(--accent-red);
color: #fff;
font-size: 0.72rem;
font-weight: 800;
padding: 2px 8px;
border-radius: 10px;
}
.lobby-actions {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
margin-bottom: 14px;
}
#start-btn {
width: 100%;
font-size: 1.1rem;
padding: 15px;
}
.lobby-hint {
font-size: 0.82rem;
color: var(--text-muted);
text-align: center;
}
.race-rules {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 20px;
}
.rule {
background: var(--surface);
border-radius: 10px;
padding: 10px 16px;
font-size: 0.88rem;
color: var(--text-muted);
border: 1px solid rgba(255,255,255,0.05);
}
/* ═══════════════════════════════════════
GAME SCREEN
═══════════════════════════════════════ */
#game-screen {
flex-direction: column;
padding: 0;
}
.game-wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
max-width: 900px;
margin: 0 auto;
width: 100%;
padding: 0 16px 20px;
}
.game-topbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 0 10px;
border-bottom: 1px solid rgba(255,255,255,0.07);
margin-bottom: 16px;
}
.topbar-title {
font-size: 1.1rem;
font-weight: 800;
color: var(--accent-yellow);
}
.room-badge {
background: var(--surface2);
border: 1px solid rgba(245,197,24,0.3);
color: var(--accent-yellow);
font-family: monospace;
font-size: 0.85rem;
font-weight: 700;
padding: 4px 12px;
border-radius: 20px;
letter-spacing: 3px;
}
/* ── Race Track ── */
.track-section {
background: var(--track-green);
border-radius: 14px;
padding: 16px 20px;
margin-bottom: 16px;
border: 1px solid rgba(46, 204, 113, 0.2);
box-shadow: inset 0 2px 12px rgba(0,0,0,0.3);
}
.race-track {
display: flex;
flex-direction: column;
gap: 12px;
}
.track-row {
display: flex;
align-items: center;
gap: 10px;
}
.player-label {
width: 110px;
min-width: 110px;
font-size: 0.85rem;
font-weight: 700;
text-align: right;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #fff;
}
.track-bar {
flex: 1;
height: 42px;
background: var(--track-line);
border-radius: 21px;
position: relative;
border: 2px solid rgba(46,204,113,0.3);
overflow: visible;
}
/* Dashed center line */
.track-bar::before {
content: '';
position: absolute;
top: 50%;
left: 5%;
right: 5%;
height: 2px;
background: repeating-linear-gradient(
90deg,
rgba(255,255,255,0.15) 0px,
rgba(255,255,255,0.15) 12px,
transparent 12px,
transparent 24px
);
transform: translateY(-50%);
pointer-events: none;
}
.car-emoji {
position: absolute;
top: 50%;
left: 4%;
transform: translateY(-50%);
font-size: 1.6rem;
transition: left 0.7s cubic-bezier(0.25, 0.46, 0.45, 0.94);
z-index: 5;
line-height: 1;
filter: drop-shadow(0 3px 6px rgba(0,0,0,0.5));
will-change: left;
}
.car-emoji.boosting {
animation: carBoost 0.4s ease;
}
@keyframes carBoost {
0% { filter: drop-shadow(0 3px 6px rgba(0,0,0,0.5)); transform: translateY(-50%) scale(1); }
40% { filter: drop-shadow(0 0 14px rgba(245,197,24,0.9)); transform: translateY(-50%) scale(1.35); }
100% { filter: drop-shadow(0 3px 6px rgba(0,0,0,0.5)); transform: translateY(-50%) scale(1); }
}
.finish-col {
display: flex;
align-items: center;
gap: 6px;
min-width: 44px;
}
.finish-flag {
font-size: 1.4rem;
}
.place-badge {
background: var(--accent-yellow);
color: #111;
font-size: 0.72rem;
font-weight: 900;
padding: 2px 7px;
border-radius: 10px;
white-space: nowrap;
}
/* ── Riddle Panel ── */
.riddle-panel {
background: var(--surface);
border-radius: var(--radius);
padding: 24px 28px;
border: 1px solid rgba(255,255,255,0.06);
flex: 1;
}
.riddle-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 18px;
flex-wrap: wrap;
}
.riddle-counter {
font-size: 0.85rem;
font-weight: 700;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.5px;
white-space: nowrap;
}
.progress-outer {
flex: 1;
height: 8px;
background: var(--surface2);
border-radius: 4px;
overflow: hidden;
min-width: 60px;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, var(--accent-green), var(--accent-yellow));
border-radius: 4px;
transition: width 0.5s ease;
}
.riddle-question {
font-size: 1.15rem;
line-height: 1.65;
color: var(--accent-yellow);
margin-bottom: 22px;
font-style: italic;
}
.answer-row {
display: flex;
gap: 10px;
margin-bottom: 14px;
}
.answer-input {
flex: 1;
margin-bottom: 0 !important;
font-size: 1.05rem;
}
.submit-btn {
white-space: nowrap;
flex-shrink: 0;
}
.riddle-footer {
display: flex;
align-items: center;
gap: 14px;
flex-wrap: wrap;
}
.feedback {
font-size: 0.95rem;
font-weight: 700;
min-height: 22px;
transition: opacity 0.3s;
}
.feedback.correct { color: var(--accent-green); }
.feedback.wrong { color: var(--accent-red); }
.hint-box {
margin-top: 14px;
background: rgba(245, 197, 24, 0.08);
border: 1px solid rgba(245, 197, 24, 0.3);
border-radius: 10px;
padding: 12px 16px;
font-size: 0.92rem;
color: var(--text);
line-height: 1.5;
animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
.hint-label {
font-weight: 700;
color: var(--accent-yellow);
margin-right: 6px;
}
/* ── Finished Banner ── */
.finished-banner {
background: var(--surface);
border-radius: var(--radius);
padding: 28px;
text-align: center;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
border: 2px solid rgba(245,197,24,0.3);
}
.finished-inner {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
.finished-trophy {
font-size: 4rem;
animation: trophyBounce 1s ease infinite alternate;
}
@keyframes trophyBounce {
from { transform: translateY(0); }
to { transform: translateY(-8px); }
}
#finished-text {
font-size: 1.5rem;
font-weight: 900;
color: var(--accent-yellow);
}
.finished-sub {
color: var(--text-muted);
font-size: 0.9rem;
}
/* ═══════════════════════════════════════
RESULTS SCREEN
═══════════════════════════════════════ */
#results-screen {
align-items: center;
justify-content: center;
padding: 20px;
background:
radial-gradient(ellipse at 50% 0%, rgba(245,197,24,0.18) 0%, transparent 60%),
var(--bg);
}
.results-wrapper {
width: 100%;
max-width: 500px;
}
.results-header {
text-align: center;
margin-bottom: 28px;
}
.results-flags {
font-size: 2rem;
margin-bottom: 8px;
animation: wave 1.5s ease-in-out infinite;
}
@keyframes wave {
0%, 100% { transform: rotate(-5deg); }
50% { transform: rotate(5deg); }
}
.results-header h1 {
font-size: 2.4rem;
font-weight: 900;
color: var(--accent-yellow);
}
.results-sub {
color: var(--text-muted);
font-size: 1rem;
margin-top: 6px;
}
.results-list {
display: flex;
flex-direction: column;
gap: 12px;
margin-bottom: 28px;
}
.result-item {
display: flex;
align-items: center;
gap: 16px;
background: var(--surface);
border-radius: var(--radius);
padding: 16px 22px;
border: 1px solid rgba(255,255,255,0.06);
animation: slideIn 0.35s ease both;
}
.result-item:nth-child(1) { border-left: 4px solid #ffd700; animation-delay: 0.05s; }
.result-item:nth-child(2) { border-left: 4px solid #c0c0c0; animation-delay: 0.15s; }
.result-item:nth-child(3) { border-left: 4px solid #cd7f32; animation-delay: 0.25s; }
.result-item:nth-child(n+4) { animation-delay: 0.35s; }
.result-medal {
font-size: 2.2rem;
width: 50px;
text-align: center;
flex-shrink: 0;
}
.result-place {
font-size: 1.6rem;
font-weight: 900;
width: 50px;
text-align: center;
color: var(--text-muted);
flex-shrink: 0;
}
.result-name {
flex: 1;
font-size: 1.15rem;
font-weight: 700;
}
.results-actions {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
}
#play-again-btn {
width: 100%;
max-width: 280px;
padding: 15px;
font-size: 1.05rem;
}
/* ═══════════════════════════════════════
NOTIFICATIONS
═══════════════════════════════════════ */
#notif-container {
position: fixed;
top: 16px;
right: 16px;
display: flex;
flex-direction: column;
gap: 10px;
z-index: 9999;
pointer-events: none;
}
.notif {
background: var(--surface);
border: 1px solid rgba(245, 197, 24, 0.4);
border-radius: 12px;
padding: 13px 20px;
font-size: 0.92rem;
font-weight: 600;
max-width: 300px;
animation: notifIn 0.3s ease, notifOut 0.4s ease 2.6s forwards;
box-shadow: 0 4px 20px rgba(0,0,0,0.4);
}
.notif.finish-notif {
border-color: var(--accent-green);
background: rgba(46, 204, 113, 0.12);
}
@keyframes notifIn {
from { opacity: 0; transform: translateX(40px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes notifOut {
to { opacity: 0; transform: translateX(40px); }
}
/* ═══════════════════════════════════════
RESPONSIVE
═══════════════════════════════════════ */
@media (max-width: 600px) {
.player-label {
width: 80px;
min-width: 80px;
font-size: 0.78rem;
}
.riddle-panel {
padding: 18px 16px;
}
.answer-row {
flex-direction: column;
}
.submit-btn {
width: 100%;
}
.card {
padding: 20px 18px;
}
.home-logo h1 {
font-size: 2.2rem;
}
}

177
riddles.js Normal file
View File

@@ -0,0 +1,177 @@
module.exports = [
{
question: "I have cities, but no houses live there. I have mountains, but no trees grow there. I have water, but no fish swim there. I have roads, but no cars drive there. What am I?",
answers: ["map", "a map"],
hint: "You use me to navigate and find your way around."
},
{
question: "The more you take, the more you leave behind. What am I?",
answers: ["footsteps", "steps", "footprints", "footprint"],
hint: "Think about what you leave on the ground when you walk."
},
{
question: "What has hands but cannot clap?",
answers: ["clock", "a clock", "watch", "a watch"],
hint: "It tells you something important every day."
},
{
question: "What has to be broken before you can use it?",
answers: ["egg", "an egg"],
hint: "You might have it scrambled or sunny-side up for breakfast."
},
{
question: "I speak without a mouth and hear without ears. I have no body, but I come alive with wind. What am I?",
answers: ["echo", "an echo"],
hint: "Shout in a canyon or large empty room and you will meet me."
},
{
question: "What can travel around the world while staying in a corner?",
answers: ["stamp", "a stamp", "postage stamp"],
hint: "You stick me on an envelope before mailing it."
},
{
question: "What has one eye but cannot see?",
answers: ["needle", "a needle", "sewing needle"],
hint: "Thread passes through my eye."
},
{
question: "What gets wetter as it dries?",
answers: ["towel", "a towel"],
hint: "You use me after a shower or bath."
},
{
question: "I have a head and a tail, but no body. What am I?",
answers: ["coin", "a coin"],
hint: "You might flip me to make a decision."
},
{
question: "What has legs but cannot walk?",
answers: ["table", "a table", "chair", "a chair", "desk", "a desk"],
hint: "You eat your meals at one of these."
},
{
question: "I am light as a feather, yet the strongest person cannot hold me for more than five minutes. What am I?",
answers: ["breath", "your breath", "breathing", "air"],
hint: "You need me to survive every second of every day."
},
{
question: "What has many keys but cannot open a single lock?",
answers: ["piano", "a piano", "keyboard", "a keyboard"],
hint: "You press my keys to make music."
},
{
question: "What goes up but never comes down?",
answers: ["age", "your age"],
hint: "Everyone has it, and it only ever increases."
},
{
question: "I am always in front of you but can never be seen. What am I?",
answers: ["future", "the future"],
hint: "It is what has not happened yet."
},
{
question: "What has teeth but cannot bite?",
answers: ["comb", "a comb", "saw", "a saw", "zipper", "a zipper", "gear", "a gear"],
hint: "You drag me through your hair to style it."
},
{
question: "What runs but never walks, has a mouth but never talks, has a head but never weeps, has a bed but never sleeps?",
answers: ["river", "a river"],
hint: "Water flows through me toward the sea."
},
{
question: "What comes once in a minute, twice in a moment, but never in a thousand years?",
answers: ["m", "the letter m", "letter m"],
hint: "Look very carefully at the letters in the words of this riddle."
},
{
question: "What building has the most stories?",
answers: ["library", "a library"],
hint: "You borrow books for free from here."
},
{
question: "What word is always spelled incorrectly?",
answers: ["incorrectly"],
hint: "The answer is hiding inside the riddle itself."
},
{
question: "What can you hold in your right hand but never in your left hand?",
answers: ["left hand", "your left hand", "left elbow", "your left elbow"],
hint: "Think physically — what is literally impossible to hold in your right hand?"
},
{
question: "I can fly without wings. I can cry without eyes. Wherever I go, darkness follows me. What am I?",
answers: ["cloud", "a cloud", "rain cloud"],
hint: "Look up at the sky on a stormy day."
},
{
question: "What is full of holes but still holds water?",
answers: ["sponge", "a sponge"],
hint: "You might use me to wash dishes or a car."
},
{
question: "What has words but never speaks?",
answers: ["book", "a book"],
hint: "You read me for stories, knowledge, or entertainment."
},
{
question: "If you drop me I am sure to crack, but smile at me and I will always smile back. What am I?",
answers: ["mirror", "a mirror"],
hint: "You look at your reflection in me."
},
{
question: "What invention lets you look right through a wall?",
answers: ["window", "a window"],
hint: "Homes and buildings have me in every room."
},
{
question: "I am tall when I am young, and short when I am old. What am I?",
answers: ["candle", "a candle"],
hint: "I melt as I give off light and warmth."
},
{
question: "What is so fragile that saying its name breaks it?",
answers: ["silence"],
hint: "It is the complete absence of sound."
},
{
question: "The more there is, the less you see. What am I?",
answers: ["darkness", "dark", "fog"],
hint: "It appears when light disappears."
},
{
question: "I have no life, but I can die. What am I?",
answers: ["battery", "a battery"],
hint: "You recharge me or replace me in your phone or remote."
},
{
question: "What goes through towns and over hills, but never moves?",
answers: ["road", "a road", "street", "a street"],
hint: "Cars and trucks drive on me every day."
},
{
question: "What has a neck but no head?",
answers: ["bottle", "a bottle"],
hint: "You pour liquids into and out of me."
},
{
question: "What can you catch but cannot throw?",
answers: ["cold", "a cold", "the flu", "flu"],
hint: "You might get me from someone who sneezes near you."
},
{
question: "What has 13 hearts but no other organs?",
answers: ["deck of cards", "a deck of cards", "deck", "cards"],
hint: "You play poker and solitaire with me."
},
{
question: "I have cities, mountains, and water, but no living things. You can hold the entire world in your hands with me. What am I?",
answers: ["globe", "a globe"],
hint: "I am a round model of the Earth."
},
{
question: "What has a ring but no finger?",
answers: ["telephone", "a telephone", "phone", "a phone"],
hint: "You pick me up and answer when someone calls."
}
];

300
server.js Normal file
View File

@@ -0,0 +1,300 @@
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');
const riddles = require('./riddles');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.static(path.join(__dirname, 'public')));
const FINISH_LINE = 10;
const COLORS = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c', '#e67e22', '#e91e63'];
const rooms = {};
function genRoomId() {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
let id = '';
for (let i = 0; i < 6; i++) id += chars[Math.floor(Math.random() * chars.length)];
return id;
}
function shuffle(arr) {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function getOrdinal(n) {
const s = ['th', 'st', 'nd', 'rd'];
const v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
function normalizeAnswer(ans) {
return ans.toLowerCase().trim().replace(/^(a |an |the )/, '').replace(/[^a-z0-9\s]/g, '').replace(/\s+/g, ' ');
}
function checkAnswer(playerAns, riddleIndex) {
const riddle = riddles[riddleIndex];
const norm = normalizeAnswer(playerAns);
return riddle.answers.some(a => normalizeAnswer(a) === norm);
}
function publicPlayers(room) {
return Object.entries(room.players).map(([id, p]) => ({
id,
name: p.name,
position: p.position,
color: p.color,
finished: p.finished,
finishPosition: p.finishPosition
}));
}
io.on('connection', (socket) => {
let roomId = null;
socket.on('createRoom', ({ name }) => {
if (!name || name.trim().length === 0) return;
roomId = genRoomId();
// Make sure room ID is unique
while (rooms[roomId]) roomId = genRoomId();
const color = COLORS[0];
rooms[roomId] = {
host: socket.id,
state: 'lobby',
finishCount: 0,
players: {
[socket.id]: {
name: name.trim().slice(0, 20),
color,
position: 0,
queue: shuffle(Array.from({ length: riddles.length }, (_, i) => i)),
queuePos: 0,
finished: false,
finishPosition: null
}
}
};
socket.join(roomId);
socket.emit('roomCreated', { roomId });
socket.emit('lobbyState', {
players: publicPlayers(rooms[roomId]),
isHost: true,
roomId
});
});
socket.on('joinRoom', ({ name, code }) => {
if (!name || name.trim().length === 0) return socket.emit('joinError', 'Please enter your name.');
const upperCode = (code || '').trim().toUpperCase();
const room = rooms[upperCode];
if (!room) return socket.emit('joinError', 'Room not found. Check the code and try again.');
if (room.state !== 'lobby') return socket.emit('joinError', 'That race already started. Wait for the next one!');
if (Object.keys(room.players).length >= 8) return socket.emit('joinError', 'Room is full (max 8 racers).');
const usedColors = new Set(Object.values(room.players).map(p => p.color));
const color = COLORS.find(c => !usedColors.has(c)) || COLORS[Object.keys(room.players).length % COLORS.length];
room.players[socket.id] = {
name: name.trim().slice(0, 20),
color,
position: 0,
queue: shuffle(Array.from({ length: riddles.length }, (_, i) => i)),
queuePos: 0,
finished: false,
finishPosition: null
};
roomId = upperCode;
socket.join(upperCode);
socket.emit('joinedRoom', { roomId: upperCode });
socket.emit('lobbyState', {
players: publicPlayers(room),
isHost: false,
roomId: upperCode
});
// Tell everyone else a new racer joined
socket.to(upperCode).emit('playerUpdate', {
players: publicPlayers(room),
message: `${room.players[socket.id].name} joined the race!`
});
});
socket.on('startGame', () => {
if (!roomId) return;
const room = rooms[roomId];
if (!room || room.host !== socket.id || room.state !== 'lobby') return;
if (Object.keys(room.players).length < 1) return;
room.state = 'playing';
// Send each player their first riddle individually
Object.entries(room.players).forEach(([pid, player]) => {
const riddleIdx = player.queue[player.queuePos];
io.to(pid).emit('gameStarted', {
players: publicPlayers(room),
riddle: {
question: riddles[riddleIdx].question,
hint: riddles[riddleIdx].hint
},
riddleNum: 1,
total: FINISH_LINE
});
});
});
socket.on('submitAnswer', ({ answer }) => {
if (!roomId) return;
const room = rooms[roomId];
if (!room || room.state !== 'playing') return;
const player = room.players[socket.id];
if (!player || player.finished) return;
if (!answer || answer.trim().length === 0) return;
const riddleIdx = player.queue[player.queuePos];
if (!checkAnswer(answer, riddleIdx)) {
return socket.emit('answerResult', { correct: false });
}
// Correct answer!
player.position++;
player.queuePos++;
if (player.position >= FINISH_LINE) {
room.finishCount++;
player.finished = true;
player.finishPosition = room.finishCount;
// Update track for all
io.to(roomId).emit('positionUpdate', { players: publicPlayers(room) });
// Announce finish to all
io.to(roomId).emit('playerFinished', {
name: player.name,
place: player.finishPosition
});
// Tell this player they're done
socket.emit('answerResult', {
correct: true,
finished: true,
finishPosition: player.finishPosition
});
// Check if everyone is done
if (Object.values(room.players).every(p => p.finished)) {
room.state = 'finished';
const results = Object.values(room.players)
.sort((a, b) => a.finishPosition - b.finishPosition)
.map(p => ({ name: p.name, color: p.color, place: p.finishPosition }));
setTimeout(() => io.to(roomId).emit('gameOver', { results }), 1500);
}
} else {
const nextRiddleIdx = player.queue[player.queuePos];
const nextRiddle = riddles[nextRiddleIdx];
// Update track for all
io.to(roomId).emit('positionUpdate', { players: publicPlayers(room) });
// Send next riddle to this player
socket.emit('answerResult', {
correct: true,
finished: false,
riddle: {
question: nextRiddle.question,
hint: nextRiddle.hint
},
riddleNum: player.position + 1,
total: FINISH_LINE
});
}
});
socket.on('getHint', () => {
if (!roomId) return;
const room = rooms[roomId];
if (!room || room.state !== 'playing') return;
const player = room.players[socket.id];
if (!player || player.finished) return;
const riddle = riddles[player.queue[player.queuePos]];
socket.emit('hint', { hint: riddle.hint });
});
socket.on('playAgain', () => {
if (!roomId) return;
const room = rooms[roomId];
if (!room || room.host !== socket.id) return;
room.state = 'lobby';
room.finishCount = 0;
Object.values(room.players).forEach(p => {
p.position = 0;
p.queue = shuffle(Array.from({ length: riddles.length }, (_, i) => i));
p.queuePos = 0;
p.finished = false;
p.finishPosition = null;
});
io.to(roomId).emit('returnToLobby', { players: publicPlayers(room) });
});
socket.on('disconnect', () => {
if (!roomId || !rooms[roomId]) return;
const room = rooms[roomId];
const player = room.players[socket.id];
if (!player) return;
const name = player.name;
const wasHost = room.host === socket.id;
delete room.players[socket.id];
if (Object.keys(room.players).length === 0) {
delete rooms[roomId];
return;
}
if (wasHost) {
room.host = Object.keys(room.players)[0];
}
io.to(roomId).emit('playerUpdate', {
players: publicPlayers(room),
message: `${name} left the race.`,
newHost: wasHost ? room.host : null
});
// If game was in progress and all remaining players finished, end it
if (room.state === 'playing') {
const allDone = Object.values(room.players).every(p => p.finished);
if (allDone && Object.keys(room.players).length > 0) {
room.state = 'finished';
const results = Object.values(room.players)
.sort((a, b) => a.finishPosition - b.finishPosition)
.map(p => ({ name: p.name, color: p.color, place: p.finishPosition }));
io.to(roomId).emit('gameOver', { results });
}
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`\n🏎️ Riddle Racer is running!`);
console.log(` Open http://localhost:${PORT} in your browser\n`);
});