Spaces:
Sleeping
Sleeping
| const express = require('express'); | |
| const http = require('http'); | |
| const { Server } = require('socket.io'); | |
| const path = require('path'); | |
| const wordLists = require('./words'); | |
| const app = express(); | |
| const server = http.createServer(app); | |
| const io = new Server(server, { cors: { origin: '*' } }); | |
| const PORT = process.env.PORT || 7860; | |
| app.use(express.static(path.join(__dirname, 'public'))); | |
| // /game now served by index.html (single page app) | |
| app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'public', 'index.html'))); | |
| // ─── In-memory game state ─────────────────────────────────────────────────── | |
| const rooms = {}; | |
| function genCode() { | |
| let code; | |
| do { code = Math.random().toString(36).substring(2, 8).toUpperCase(); } while (rooms[code]); | |
| return code; | |
| } | |
| function getWords(settings, count = 3) { | |
| let pool = []; | |
| if (settings.wordMode === 'custom' && settings.customWords.length >= count) { | |
| pool = [...settings.customWords]; | |
| } else if (settings.wordMode === 'mixed') { | |
| const cats = settings.categories || Object.keys(wordLists); | |
| cats.forEach(c => { if (wordLists[c]) pool = pool.concat(wordLists[c]); }); | |
| pool = pool.concat(settings.customWords || []); | |
| } else { | |
| const cats = settings.categories || Object.keys(wordLists); | |
| cats.forEach(c => { if (wordLists[c]) pool = pool.concat(wordLists[c]); }); | |
| } | |
| pool = [...new Set(pool)]; | |
| const choices = []; | |
| while (choices.length < count && pool.length > 0) { | |
| const i = Math.floor(Math.random() * pool.length); | |
| choices.push(pool.splice(i, 1)[0]); | |
| } | |
| return choices; | |
| } | |
| function hintMask(word, revealed) { | |
| return word.split('').map((c, i) => c === ' ' ? ' ' : revealed.includes(i) ? c : '_').join(''); | |
| } | |
| function levenshtein(a, b) { | |
| const dp = Array.from({ length: a.length + 1 }, (_, i) => | |
| Array.from({ length: b.length + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0)); | |
| for (let i = 1; i <= a.length; i++) | |
| for (let j = 1; j <= b.length; j++) | |
| dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] : 1 + Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]); | |
| return dp[a.length][b.length]; | |
| } | |
| function createRoom(settings = {}) { | |
| const id = genCode(); | |
| rooms[id] = { | |
| id, | |
| host: null, | |
| players: [], | |
| spectators: [], | |
| state: 'waiting', | |
| settings: { | |
| maxPlayers: 10, | |
| rounds: 3, | |
| drawTime: 80, | |
| wordChoices: 3, | |
| customWords: [], | |
| wordMode: 'normal', | |
| categories: Object.keys(wordLists), | |
| teamMode: false, | |
| suddenDeath: false, | |
| quickDraw: false, | |
| hintsEnabled: true, | |
| ...settings | |
| }, | |
| currentRound: 0, | |
| drawerOrder: [], | |
| currentDrawerIndex: 0, | |
| currentWord: null, | |
| wordChoices: [], | |
| drawStrokes: [], | |
| timer: null, | |
| chooseTimer: null, | |
| hintTimer1: null, | |
| hintTimer2: null, | |
| timeLeft: 0, | |
| totalTime: 80, | |
| hintsRevealed: [], | |
| roundStartTime: null, | |
| roundScores: [], | |
| usedWords: [], | |
| teams: { red: [], blue: [] }, | |
| scoreHistory: [], // [{round, scores:[{id,score}]}] for graph | |
| }; | |
| return id; | |
| } | |
| function addPlayer(room, sid, name, avatar) { | |
| const player = { | |
| id: sid, | |
| name: (name || 'Player').substring(0, 20), | |
| score: 0, | |
| avatar: avatar || { color: `hsl(${Math.floor(Math.random()*360)},70%,60%)`, icon: '😀' }, | |
| team: null, | |
| streak: 0, | |
| powerUps: { revealLetter: 1, timeWarp: 1, bomb: 1 }, | |
| achievements: [], | |
| isDrawing: false, | |
| hasGuessed: false, | |
| guessTime: null, | |
| isSpectator: false, | |
| wordsDrawn: 0, | |
| }; | |
| room.players.push(player); | |
| return player; | |
| } | |
| function getPlayer(room, sid) { | |
| return room.players.find(p => p.id === sid) || room.spectators.find(p => p.id === sid); | |
| } | |
| function clearAllTimers(room) { | |
| if (room.timer) { clearInterval(room.timer); room.timer = null; } | |
| if (room.chooseTimer) { clearTimeout(room.chooseTimer); room.chooseTimer = null; } | |
| if (room.hintTimer1) { clearTimeout(room.hintTimer1); room.hintTimer1 = null; } | |
| if (room.hintTimer2) { clearTimeout(room.hintTimer2); room.hintTimer2 = null; } | |
| } | |
| function shuffle(arr) { | |
| for (let i = arr.length - 1; i > 0; i--) { | |
| const j = Math.floor(Math.random() * (i + 1)); | |
| [arr[i], arr[j]] = [arr[j], arr[i]]; | |
| } | |
| return arr; | |
| } | |
| function getRoomData(room) { | |
| return { | |
| id: room.id, | |
| host: room.host, | |
| state: room.state, | |
| settings: room.settings, | |
| players: room.players, | |
| spectators: room.spectators, | |
| currentRound: room.currentRound, | |
| totalRounds: room.settings.rounds, | |
| teams: room.teams, | |
| }; | |
| } | |
| function broadcastPlayers(room) { | |
| io.to(room.id).emit('playerUpdate', { players: room.players }); | |
| } | |
| // ─── Game Flow ─────────────────────────────────────────────────────────────── | |
| function startGame(room) { | |
| if (room.players.length === 0) return; | |
| room.state = 'playing'; | |
| room.currentRound = 1; | |
| room.scoreHistory = []; | |
| room.usedWords = []; | |
| room.players.forEach(p => { | |
| p.score = 0; p.streak = 0; p.achievements = []; | |
| p.powerUps = { revealLetter: 1, timeWarp: 1, bomb: 1 }; | |
| }); | |
| if (room.settings.teamMode) assignTeams(room); | |
| room.drawerOrder = shuffle(room.players.map(p => p.id)); | |
| room.currentDrawerIndex = 0; | |
| startRound(room); | |
| } | |
| function assignTeams(room) { | |
| room.teams = { red: [], blue: [] }; | |
| room.players.forEach((p, i) => { | |
| p.team = i % 2 === 0 ? 'red' : 'blue'; | |
| room.teams[p.team].push(p.id); | |
| }); | |
| } | |
| function startRound(room) { | |
| clearAllTimers(room); | |
| room.players.forEach(p => { p.hasGuessed = false; p.isDrawing = false; p.guessTime = null; }); | |
| room.drawStrokes = []; | |
| room.hintsRevealed = []; | |
| room.roundScores = []; | |
| room.currentWord = null; | |
| // Find drawer, skip if missing | |
| let drawerFound = false; | |
| while (!drawerFound && room.currentDrawerIndex < room.drawerOrder.length) { | |
| const drawerId = room.drawerOrder[room.currentDrawerIndex]; | |
| const drawer = room.players.find(p => p.id === drawerId); | |
| if (drawer) { drawer.isDrawing = true; drawerFound = true; } | |
| else room.currentDrawerIndex++; | |
| } | |
| if (!drawerFound) { nextTurn(room); return; } | |
| const drawer = room.players.find(p => p.isDrawing); | |
| const choices = getWords(room.settings, room.settings.wordChoices); | |
| room.wordChoices = choices; | |
| room.state = 'choosing'; | |
| io.to(room.id).emit('roundStart', { | |
| round: room.currentRound, | |
| totalRounds: room.settings.rounds, | |
| drawer: { id: drawer.id, name: drawer.name, avatar: drawer.avatar }, | |
| players: room.players, | |
| }); | |
| io.to(drawer.id).emit('chooseWord', { choices }); | |
| room.chooseTimer = setTimeout(() => { | |
| if (room.state === 'choosing') { | |
| wordChosen(room, choices[Math.floor(Math.random() * choices.length)]); | |
| } | |
| }, 15000); | |
| } | |
| function wordChosen(room, word) { | |
| clearAllTimers(room); | |
| room.currentWord = word; | |
| room.usedWords.push(word); | |
| room.state = 'drawing'; | |
| const drawTime = room.settings.quickDraw ? 20 : room.settings.drawTime; | |
| room.timeLeft = drawTime; | |
| room.totalTime = drawTime; | |
| room.roundStartTime = Date.now(); | |
| const drawer = room.players.find(p => p.isDrawing); | |
| const mask = hintMask(word, []); | |
| const lengths = word.split(' ').map(w => w.length); | |
| io.to(drawer.id).emit('wordChosen', { word, hint: mask, lengths, isDrawer: true }); | |
| socket_to_room_except(room.id, drawer.id, 'wordChosen', { word: null, hint: mask, lengths, isDrawer: false }); | |
| // Auto hints | |
| if (room.settings.hintsEnabled) { | |
| room.hintTimer1 = setTimeout(() => { if (room.state === 'drawing') revealHint(room); }, drawTime * 500); | |
| room.hintTimer2 = setTimeout(() => { if (room.state === 'drawing') revealHint(room); }, drawTime * 750); | |
| } | |
| // Countdown | |
| room.timer = setInterval(() => { | |
| room.timeLeft--; | |
| io.to(room.id).emit('timerUpdate', { timeLeft: room.timeLeft, totalTime: room.totalTime }); | |
| if (room.timeLeft <= 0) endRound(room); | |
| }, 1000); | |
| } | |
| function socket_to_room_except(roomId, exceptId, event, data) { | |
| io.to(roomId).except(exceptId).emit(event, data); | |
| } | |
| function revealHint(room) { | |
| const word = room.currentWord; | |
| if (!word) return; | |
| const unrevealed = []; | |
| word.split('').forEach((c, i) => { if (c !== ' ' && !room.hintsRevealed.includes(i)) unrevealed.push(i); }); | |
| if (unrevealed.length === 0) return; | |
| const n = Math.max(1, Math.floor(unrevealed.length * 0.3)); | |
| const picks = shuffle([...unrevealed]).slice(0, n); | |
| room.hintsRevealed.push(...picks); | |
| const drawer = room.players.find(p => p.isDrawing); | |
| const hint = hintMask(word, room.hintsRevealed); | |
| socket_to_room_except(room.id, drawer?.id || '', 'hintUpdate', { hint, revealed: room.hintsRevealed }); | |
| } | |
| function checkGuess(room, sid, text) { | |
| if (!room.currentWord || room.state !== 'drawing') return 'ignore'; | |
| const player = room.players.find(p => p.id === sid); | |
| if (!player || player.hasGuessed || player.isDrawing) return 'ignore'; | |
| const guess = text.trim().toLowerCase(); | |
| const answer = room.currentWord.toLowerCase(); | |
| if (guess === answer) { | |
| const elapsed = (Date.now() - room.roundStartTime) / 1000; | |
| const timeRatio = Math.max(0, 1 - elapsed / room.totalTime); | |
| const baseScore = 200; | |
| const timeBonus = Math.round(timeRatio * 300); | |
| const firstBonus = room.roundScores.length === 0 ? 50 : 0; | |
| const streakBonus = player.streak * 25; | |
| const total = baseScore + timeBonus + firstBonus + streakBonus; | |
| player.hasGuessed = true; | |
| player.guessTime = elapsed; | |
| player.score += total; | |
| player.streak++; | |
| player.wordsDrawn; | |
| const drawer = room.players.find(p => p.isDrawing); | |
| if (drawer) { | |
| const drawerGain = Math.round(50 + (room.roundScores.length === 0 ? 0 : 10)); | |
| drawer.score += drawerGain; | |
| } | |
| room.roundScores.push({ id: sid, score: total, time: elapsed }); | |
| checkAchievements(room, player); | |
| const nonDrawers = room.players.filter(p => !p.isDrawing && !p.isSpectator); | |
| if (nonDrawers.every(p => p.hasGuessed)) setTimeout(() => endRound(room), 1500); | |
| return { correct: true, score: total, streak: player.streak, firstBonus }; | |
| } | |
| const dist = levenshtein(guess, answer); | |
| if (dist <= 2 && guess.length > 2) return 'close'; | |
| if (room.settings.suddenDeath) { | |
| player.score = Math.max(0, player.score - 15); | |
| broadcastPlayers(room); | |
| } | |
| return 'wrong'; | |
| } | |
| function checkAchievements(room, player) { | |
| const unlocked = []; | |
| const add = (id, name, desc) => { | |
| if (!player.achievements.includes(id)) { | |
| player.achievements.push(id); | |
| unlocked.push({ id, name, desc }); | |
| } | |
| }; | |
| if (player.guessTime < 8) add('speed_demon', '⚡ Speed Demon', 'Guessed in under 8 seconds!'); | |
| if (player.streak >= 3) add('on_fire', '🔥 On Fire', '3 correct guesses in a row!'); | |
| if (player.streak >= 5) add('unstoppable', '💎 Unstoppable', '5 in a row!'); | |
| if (room.roundScores.length === 1) add('first_blood', '🩸 First Blood', 'First to guess the word!'); | |
| if (room.hintsRevealed.length === 0 && player.guessTime < room.totalTime * 0.5) | |
| add('no_hints', '🕵️ Sherlock', 'Guessed with zero hints revealed!'); | |
| if (unlocked.length > 0) io.to(player.id).emit('achievementUnlocked', unlocked); | |
| } | |
| function endRound(room) { | |
| clearAllTimers(room); | |
| if (room.state === 'intermission' || room.state === 'ended') return; | |
| room.state = 'intermission'; | |
| const drawer = room.players.find(p => p.isDrawing); | |
| // Picasso achievement | |
| const nonDrawers = room.players.filter(p => !p.isDrawing && !p.isSpectator); | |
| if (drawer && nonDrawers.length > 0 && nonDrawers.every(p => p.hasGuessed)) { | |
| if (!drawer.achievements.includes('picasso')) { | |
| drawer.achievements.push('picasso'); | |
| io.to(drawer.id).emit('achievementUnlocked', [{ id: 'picasso', name: '🎨 Picasso', desc: 'Everyone guessed your drawing!' }]); | |
| } | |
| drawer.score += 100; // bonus | |
| } | |
| // Record score history | |
| room.scoreHistory.push({ | |
| round: room.currentRound, | |
| drawerTurn: room.currentDrawerIndex, | |
| scores: room.players.map(p => ({ id: p.id, name: p.name, score: p.score })) | |
| }); | |
| io.to(room.id).emit('roundEnd', { | |
| word: room.currentWord, | |
| scores: room.players.map(p => ({ | |
| id: p.id, name: p.name, score: p.score, avatar: p.avatar, | |
| roundGain: room.roundScores.find(r => r.id === p.id)?.score || 0, | |
| guessTime: p.guessTime, | |
| })), | |
| drawStrokes: room.drawStrokes, | |
| drawer: drawer ? { id: drawer.id, name: drawer.name } : null, | |
| scoreHistory: room.scoreHistory, | |
| }); | |
| room.timer = setTimeout(() => { | |
| if (!rooms[room.id]) return; | |
| nextTurn(room); | |
| }, 7000); | |
| } | |
| function nextTurn(room) { | |
| clearAllTimers(room); | |
| room.currentDrawerIndex++; | |
| if (room.currentDrawerIndex >= room.drawerOrder.length) { | |
| room.currentRound++; | |
| if (room.currentRound > room.settings.rounds) { endGame(room); return; } | |
| room.drawerOrder = shuffle(room.players.map(p => p.id)); | |
| room.currentDrawerIndex = 0; | |
| } | |
| if (room.players.length < 1) { | |
| room.state = 'waiting'; | |
| io.to(room.id).emit('gameAborted', { reason: 'Not enough players' }); | |
| return; | |
| } | |
| startRound(room); | |
| } | |
| function endGame(room) { | |
| clearAllTimers(room); | |
| room.state = 'ended'; | |
| const sorted = [...room.players].sort((a, b) => b.score - a.score); | |
| // Victory achievement | |
| if (sorted[0]) { | |
| const winner = sorted[0]; | |
| if (!winner.achievements.includes('champion')) { | |
| winner.achievements.push('champion'); | |
| io.to(winner.id).emit('achievementUnlocked', [{ id: 'champion', name: '👑 Champion', desc: 'You won the game!' }]); | |
| } | |
| } | |
| io.to(room.id).emit('gameEnd', { | |
| players: sorted.map((p, i) => ({ | |
| id: p.id, name: p.name, score: p.score, | |
| rank: i + 1, achievements: p.achievements, avatar: p.avatar, streak: p.streak | |
| })), | |
| scoreHistory: room.scoreHistory, | |
| }); | |
| setTimeout(() => { if (rooms[room.id]) delete rooms[room.id]; }, 60000); | |
| } | |
| // ─── Socket.IO ─────────────────────────────────────────────────────────────── | |
| io.on('connection', (socket) => { | |
| socket.on('createRoom', ({ name, avatar, settings }) => { | |
| const id = createRoom(settings || {}); | |
| const room = rooms[id]; | |
| room.host = socket.id; | |
| const player = addPlayer(room, socket.id, name, avatar); | |
| socket.join(id); | |
| socket.roomId = id; | |
| socket.emit('roomCreated', { roomId: id, player, room: getRoomData(room) }); | |
| }); | |
| socket.on('joinRoom', ({ roomId, name, avatar, asSpectator }) => { | |
| const code = (roomId || '').toUpperCase().trim(); | |
| const room = rooms[code]; | |
| if (!room) { socket.emit('joinError', { message: 'Room not found. Check the code!' }); return; } | |
| if (room.players.length >= room.settings.maxPlayers) { | |
| socket.emit('joinError', { message: 'Room is full! (max ' + room.settings.maxPlayers + ')' }); return; | |
| } | |
| socket.join(code); | |
| socket.roomId = code; | |
| let player; | |
| if (asSpectator) { | |
| player = addPlayer(room, socket.id, name, avatar); | |
| player.isSpectator = true; | |
| room.players = room.players.filter(p => p.id !== socket.id); | |
| room.spectators.push(player); | |
| } else { | |
| player = addPlayer(room, socket.id, name, avatar); | |
| // If joining mid-game, mark as late joiner (they wait for next round to draw) | |
| if (room.state !== 'waiting') { | |
| player.lateJoin = true; | |
| } | |
| } | |
| socket.emit('roomJoined', { player, room: getRoomData(room) }); | |
| socket.to(code).emit('playerJoined', { player, players: room.players, spectators: room.spectators }); | |
| }); | |
| socket.on('joinRandom', ({ name, avatar }) => { | |
| // Find a waiting matchmaking room (including ones in grace period with 0 players) | |
| let room = Object.values(rooms).find(r => | |
| r.state === 'waiting' && | |
| r.isMatchmaking === true && | |
| r.players.length < r.settings.maxPlayers | |
| ); | |
| const isNewRoom = !room; | |
| if (!room) { | |
| const id = createRoom(); | |
| room = rooms[id]; | |
| room.isMatchmaking = true; | |
| room.host = socket.id; | |
| room.mmStartTime = Date.now(); // track when matchmaking started | |
| } | |
| // Cancel grace-period deletion timer if rejoining | |
| if (room._graceTimer) { | |
| clearTimeout(room._graceTimer); | |
| delete room._graceTimer; | |
| } | |
| const player = addPlayer(room, socket.id, name, avatar); | |
| socket.join(room.id); | |
| socket.roomId = room.id; | |
| if (room.players.length === 1) room.host = socket.id; | |
| socket.emit('roomJoined', { player, room: getRoomData(room) }); | |
| socket.to(room.id).emit('playerJoined', { player, players: room.players }); | |
| if (room.players.length >= 2) { | |
| // ── 2+ players: cancel solo timer, start 10s multiplayer countdown ── | |
| if (room.matchmakingTimer) { clearTimeout(room.matchmakingTimer); room.matchmakingTimer = null; } | |
| if (room.matchmakingCountdown) { clearInterval(room.matchmakingCountdown); room.matchmakingCountdown = null; } | |
| let secs = 10; | |
| io.to(room.id).emit('matchmakingUpdate', { players: room.players.length, needed: 2, countdown: secs, waiting: false }); | |
| room.matchmakingCountdown = setInterval(() => { | |
| secs--; | |
| io.to(room.id).emit('matchmakingUpdate', { players: room.players.length, needed: 2, countdown: secs, waiting: false }); | |
| if (secs <= 0) { clearInterval(room.matchmakingCountdown); room.matchmakingCountdown = null; } | |
| }, 1000); | |
| room.matchmakingTimer = setTimeout(() => { | |
| if (!rooms[room.id] || room.state !== 'waiting') return; | |
| room.isMatchmaking = false; | |
| startGame(room); | |
| }, 10000); | |
| } else { | |
| // ── 1 player: only start timers if NOT already running (prevents reset on reconnect) ── | |
| if (!room.matchmakingTimer) { | |
| room.mmStartTime = Date.now(); | |
| const SOLO_WAIT = 30000; | |
| // Send initial countdown | |
| io.to(room.id).emit('matchmakingUpdate', { players: 1, needed: 2, countdown: 30, waiting: true }); | |
| room.matchmakingCountdown = setInterval(() => { | |
| if (!rooms[room.id]) { clearInterval(room.matchmakingCountdown); return; } | |
| const elapsed = Date.now() - room.mmStartTime; | |
| const remaining = Math.max(0, Math.ceil((SOLO_WAIT - elapsed) / 1000)); | |
| io.to(room.id).emit('matchmakingUpdate', { | |
| players: room.players.length, | |
| needed: 2, | |
| countdown: remaining, | |
| waiting: room.players.length < 2 | |
| }); | |
| if (remaining <= 0) { clearInterval(room.matchmakingCountdown); room.matchmakingCountdown = null; } | |
| }, 1000); | |
| room.matchmakingTimer = setTimeout(() => { | |
| if (!rooms[room.id] || room.state !== 'waiting') return; | |
| if (room.players.length === 0) { delete rooms[room.id]; return; } // nobody reconnected | |
| room.isMatchmaking = false; | |
| room.settings.rounds = 3; | |
| startGame(room); | |
| }, SOLO_WAIT); | |
| } else { | |
| // Timer already running — just send current remaining time to this (re)joining socket | |
| const elapsed = Date.now() - (room.mmStartTime || Date.now()); | |
| const remaining = Math.max(0, Math.ceil((30000 - elapsed) / 1000)); | |
| socket.emit('matchmakingUpdate', { players: room.players.length, needed: 2, countdown: remaining, waiting: true }); | |
| } | |
| } | |
| }); | |
| // CRITICAL: When page reloads after game starts, new socket must rejoin room | |
| socket.on('rejoinGame', ({ roomId, name, avatar }) => { | |
| const code = (roomId || '').toUpperCase().trim(); | |
| const room = rooms[code]; | |
| if (!room) { socket.emit('rejoinError', { message: 'Room expired or not found' }); return; } | |
| socket.join(code); | |
| socket.roomId = code; | |
| // Check if player with same name already exists (reconnect) | |
| let player = room.players.find(p => p.name === name); | |
| if (player) { | |
| // Update their socket id to the new one | |
| const oldId = player.id; | |
| player.id = socket.id; | |
| // Update host if needed | |
| if (room.host === oldId) room.host = socket.id; | |
| // Update drawerOrder | |
| const di = room.drawerOrder.indexOf(oldId); | |
| if (di !== -1) room.drawerOrder[di] = socket.id; | |
| } else { | |
| // New player joining mid-game | |
| if (room.players.length >= room.settings.maxPlayers) { | |
| socket.emit('rejoinError', { message: 'Room is full!' }); return; | |
| } | |
| player = addPlayer(room, socket.id, name, avatar); | |
| player.lateJoin = true; | |
| } | |
| // Send current game state so they can sync up | |
| const drawer = room.players.find(p => p.isDrawing); | |
| socket.emit('gameRejoined', { | |
| player, | |
| room: getRoomData(room), | |
| state: room.state, | |
| round: room.currentRound, | |
| totalRounds: room.settings.rounds, | |
| drawer: drawer ? { id: drawer.id, name: drawer.name, avatar: drawer.avatar } : null, | |
| players: room.players, | |
| hint: room.currentWord ? hintMask(room.currentWord, room.hintsRevealed) : null, | |
| timeLeft: room.timeLeft, | |
| totalTime: room.totalTime, | |
| drawStrokes: room.drawStrokes, | |
| isDrawer: drawer?.id === socket.id, | |
| word: drawer?.id === socket.id ? room.currentWord : null, | |
| }); | |
| // Tell others this player is back | |
| socket.to(code).emit('playerJoined', { player, players: room.players }); | |
| }); | |
| socket.on('startGame', () => { | |
| const room = rooms[socket.roomId]; | |
| if (!room) return; | |
| if (room.host !== socket.id) { socket.emit('gameError', { message: 'Only the host can start' }); return; } | |
| if (room.players.length < 2) { socket.emit('gameError', { message: 'Need at least 2 players' }); return; } | |
| startGame(room); | |
| }); | |
| socket.on('chooseWord', ({ word }) => { | |
| const room = rooms[socket.roomId]; | |
| if (!room || room.state !== 'choosing') return; | |
| const player = room.players.find(p => p.id === socket.id); | |
| if (!player?.isDrawing || !room.wordChoices.includes(word)) return; | |
| wordChosen(room, word); | |
| }); | |
| socket.on('draw', (data) => { | |
| const room = rooms[socket.roomId]; | |
| if (!room || room.state !== 'drawing') return; | |
| const player = room.players.find(p => p.id === socket.id); | |
| if (!player?.isDrawing) return; | |
| const stamped = { ...data, t: Date.now() - (room.roundStartTime || Date.now()) }; | |
| room.drawStrokes.push(stamped); | |
| socket.to(socket.roomId).emit('draw', data); | |
| }); | |
| socket.on('clearCanvas', () => { | |
| const room = rooms[socket.roomId]; | |
| if (!room || room.state !== 'drawing') return; | |
| const player = room.players.find(p => p.id === socket.id); | |
| if (!player?.isDrawing) return; | |
| room.drawStrokes = [{ type: 'clear', t: 0 }]; | |
| io.to(socket.roomId).emit('clearCanvas'); | |
| }); | |
| socket.on('guess', ({ text }) => { | |
| const room = rooms[socket.roomId]; | |
| if (!room || !text) return; | |
| const player = getPlayer(room, socket.id); | |
| if (!player) return; | |
| // Block drawer from revealing word in chat | |
| if (player.isDrawing) { | |
| socket.emit('chatMessage', { system: true, text: '🤫 You cannot chat while drawing!', type: 'warn' }); | |
| return; | |
| } | |
| const result = checkGuess(room, socket.id, text); | |
| if (result === 'ignore') return; | |
| if (result?.correct) { | |
| socket.emit('correctGuess', { score: result.score, streak: result.streak, firstBonus: result.firstBonus }); | |
| io.to(socket.roomId).emit('chatMessage', { | |
| system: true, | |
| text: `🎉 ${player.name} guessed it! (+${result.score}pts${result.streak > 1 ? ` 🔥x${result.streak}` : ''})`, | |
| type: 'correct' | |
| }); | |
| broadcastPlayers(room); | |
| } else if (result === 'close') { | |
| socket.emit('chatMessage', { system: true, text: `🌡️ So close! Keep trying...`, type: 'close' }); | |
| io.to(socket.roomId).emit('chatMessage', { sender: player.name, text: '...', playerId: socket.id, type: 'guess' }); | |
| } else { | |
| io.to(socket.roomId).emit('chatMessage', { sender: player.name, text, playerId: socket.id, type: 'guess' }); | |
| } | |
| }); | |
| socket.on('chatMessage', ({ text }) => { | |
| const room = rooms[socket.roomId]; | |
| if (!room || !text) return; | |
| const player = getPlayer(room, socket.id); | |
| if (!player) return; | |
| // Only allow chat in non-drawing state or for spectators | |
| if (room.state === 'drawing' && !player.isSpectator) { | |
| // This goes through guess flow - ignore raw chat | |
| return; | |
| } | |
| io.to(socket.roomId).emit('chatMessage', { sender: player.name, text: text.substring(0, 120), playerId: socket.id, type: 'chat' }); | |
| }); | |
| socket.on('usePowerUp', ({ type }) => { | |
| const room = rooms[socket.roomId]; | |
| if (!room || room.state !== 'drawing') return; | |
| const player = room.players.find(p => p.id === socket.id); | |
| if (!player || player.isDrawing || !player.powerUps[type] || player.powerUps[type] <= 0) return; | |
| player.powerUps[type]--; | |
| if (type === 'revealLetter') { | |
| revealHint(room); | |
| io.to(socket.roomId).emit('chatMessage', { system: true, text: `🔍 ${player.name} revealed a letter!`, type: 'powerup' }); | |
| } else if (type === 'timeWarp') { | |
| room.timeLeft = Math.min(room.timeLeft + 15, room.totalTime); | |
| io.to(socket.roomId).emit('timerUpdate', { timeLeft: room.timeLeft, totalTime: room.totalTime }); | |
| io.to(socket.roomId).emit('chatMessage', { system: true, text: `⏰ ${player.name} warped time! +15s`, type: 'powerup' }); | |
| } else if (type === 'bomb') { | |
| room.drawStrokes = [{ type: 'clear', t: Date.now() - room.roundStartTime }]; | |
| io.to(socket.roomId).emit('clearCanvas'); | |
| io.to(socket.roomId).emit('chatMessage', { system: true, text: `💣 ${player.name} dropped a BOMB! Canvas cleared!`, type: 'powerup' }); | |
| } | |
| socket.emit('powerUpUsed', { type, remaining: player.powerUps }); | |
| }); | |
| socket.on('reaction', ({ emoji }) => { | |
| const room = rooms[socket.roomId]; | |
| if (!room) return; | |
| const player = getPlayer(room, socket.id); | |
| io.to(socket.roomId).emit('reaction', { emoji, name: player?.name || 'Someone' }); | |
| }); | |
| socket.on('updateSettings', (settings) => { | |
| const room = rooms[socket.roomId]; | |
| if (!room || room.host !== socket.id || room.state !== 'waiting') return; | |
| Object.assign(room.settings, settings); | |
| io.to(socket.roomId).emit('settingsUpdated', room.settings); | |
| }); | |
| socket.on('kickPlayer', ({ playerId }) => { | |
| const room = rooms[socket.roomId]; | |
| if (!room || room.host !== socket.id) return; | |
| const target = io.sockets.sockets.get(playerId); | |
| if (target) { | |
| target.emit('kicked', { reason: 'You were kicked by the host' }); | |
| target.leave(socket.roomId); | |
| } | |
| room.players = room.players.filter(p => p.id !== playerId); | |
| io.to(socket.roomId).emit('playerLeft', { playerId, players: room.players }); | |
| }); | |
| socket.on('requestReplay', () => { | |
| // Allow replay of last round strokes - sent on roundEnd already | |
| }); | |
| socket.on('disconnect', () => { | |
| const room = rooms[socket.roomId]; | |
| if (!room) return; | |
| const wasDrawing = room.players.find(p => p.id === socket.id)?.isDrawing; | |
| room.players = room.players.filter(p => p.id !== socket.id); | |
| room.spectators = room.spectators.filter(p => p.id !== socket.id); | |
| if (room.players.length === 0 && room.spectators.length === 0) { | |
| if (room.isMatchmaking && room.matchmakingTimer) { | |
| // Keep room + matchmaking timers alive; give mobile 15s to reconnect | |
| room._graceTimer = setTimeout(() => { | |
| const r = rooms[socket.roomId]; | |
| if (r && r.players.length === 0) { | |
| if (r.matchmakingTimer) clearTimeout(r.matchmakingTimer); | |
| if (r.matchmakingCountdown) clearInterval(r.matchmakingCountdown); | |
| clearAllTimers(r); | |
| delete rooms[socket.roomId]; | |
| } | |
| }, 15000); | |
| } else { | |
| clearAllTimers(room); | |
| if (room.matchmakingTimer) clearTimeout(room.matchmakingTimer); | |
| if (room.matchmakingCountdown) clearInterval(room.matchmakingCountdown); | |
| delete rooms[socket.roomId]; | |
| } | |
| return; | |
| } | |
| if (room.host === socket.id && room.players.length > 0) { | |
| room.host = room.players[0].id; | |
| io.to(room.host).emit('youAreHost'); | |
| } | |
| io.to(socket.roomId).emit('playerLeft', { playerId: socket.id, players: room.players }); | |
| if (wasDrawing && (room.state === 'drawing' || room.state === 'choosing')) { | |
| endRound(room); | |
| } | |
| if (room.players.length < 1 && room.state !== 'waiting' && room.state !== 'ended') { | |
| clearAllTimers(room); | |
| room.state = 'waiting'; | |
| io.to(socket.roomId).emit('gameAborted', { reason: 'Not enough players to continue' }); | |
| } | |
| }); | |
| }); | |
| server.listen(PORT, '0.0.0.0', () => { | |
| console.log(`🎨 Drawable running at http://localhost:${PORT}`); | |
| }); | |