Port Shelem layout/engine, add history, fix card flashing and count desync

Layout & engine borrowed from Shelem: waiting-room menu with seat swap and
force-start, game menu with bar-to-bottom, escalating turn reminder, three
hand modes defaulting to fan on touch, card-count badges instead of card
backs, leave buttons inside phase overlays, version footer with tap-to-update.

Seats now run clockwise from the viewer (left = +1, across = +2, right = +3)
so play flows anti-clockwise on screen as the server advances it; the pass
exchange was flipped to match, otherwise "pass left" delivered to the right.

Game history: finished games are saved with a per-hand breakdown, readable
from the profile and shown on the end-of-hand and end-of-game screens.

Card flashing: the service worker precaches all 52 faces, each face is decoded
once into a template image, and the renderers reconcile against existing DOM
instead of rebuilding it, so card nodes and their images survive a re-render.

Card-count integrity: a seat can no longer put two cards into one trick, and
the server snapshots each trick start and rewinds to the last sound state if
the four hands ever drift apart.

Leaderboard: ranked by win rate with a 5-game minimum; below-threshold players
are listed unranked. Moon shots are now recorded instead of always zero, and
stat reads no longer create and persist a row per user on every request.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
goyban
2026-08-30 14:13:46 +00:00
parent e499e89027
commit dc051cbe45
9 changed files with 2935 additions and 2205 deletions
+367 -52
View File
@@ -10,6 +10,17 @@ const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const app = express();
app.disable('x-powered-by'); // don't advertise the tech stack
// Safe security headers (no CSP here — the inline SW registration script and
// socket.io would both need 'unsafe-inline'/wss exceptions)
app.use((_req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'no-referrer');
next();
});
const httpServer = http.createServer(app);
// HTTPS with self-signed cert for local network / PWA mic access
@@ -40,9 +51,10 @@ const SHARED_USERS_FILE = process.env.SHARED_USERS_FILE || '';
const DATA_DIR = path.join(__dirname, 'data');
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
const USERS_FILE = path.join(DATA_DIR, 'users.json');
const STATS_FILE = path.join(DATA_DIR, 'stats.json');
const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
const USERS_FILE = path.join(DATA_DIR, 'users.json');
const STATS_FILE = path.join(DATA_DIR, 'stats.json');
const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
const HISTORY_FILE = path.join(DATA_DIR, 'history.json');
function readJSON(file, def) {
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return def; }
@@ -56,10 +68,22 @@ function writeJSON(file, data) {
let users = readJSON(USERS_FILE, []);
let stats = readJSON(STATS_FILE, []);
let config = readJSON(CONFIG_FILE, { signupsOpen: true });
// Finished games, newest last. Each participant can replay the round-by-round
// breakdown from their profile.
let history = readJSON(HISTORY_FILE, []);
function saveUsers() { writeJSON(USERS_FILE, users); }
function saveStats() { writeJSON(STATS_FILE, stats); }
function saveConfig() { writeJSON(CONFIG_FILE, config); }
function saveUsers() { writeJSON(USERS_FILE, users); }
function saveStats() { writeJSON(STATS_FILE, stats); }
function saveConfig() { writeJSON(CONFIG_FILE, config); }
function saveHistory() { writeJSON(HISTORY_FILE, history); }
// Keep the history file from growing without bound.
const MAX_HISTORY = 2000;
function pushHistory(record) {
history.push(record);
if (history.length > MAX_HISTORY) history = history.slice(-MAX_HISTORY);
saveHistory();
}
function isAdmin(user) {
return ADMIN_USERNAME && user && user.username === ADMIN_USERNAME;
@@ -138,10 +162,20 @@ function findUser(username) {
return null;
}
const EMPTY_STATS = { games_played: 0, games_won: 0, moon_shots: 0, total_score: 0 };
// Read-only lookup. Never creates or persists a row — the leaderboard walks
// every known user, and creating-on-read there meant one full stats.json write
// per user on every page load, plus a file steadily filling with empty rows.
function readStats(userId) {
return stats.find(s => s.userId === userId) || { userId, ...EMPTY_STATS };
}
// Write path: materialises the row so addStats has something to accumulate into.
function getStats(userId) {
let s = stats.find(s => s.userId === userId);
if (!s) {
s = { userId, games_played: 0, games_won: 0, moon_shots: 0, total_score: 0 };
s = { userId, ...EMPTY_STATS };
stats.push(s);
saveStats();
}
@@ -178,8 +212,21 @@ app.use(express.static(path.join(__dirname, 'public'), {
}));
// ─── Auth API ─────────────────────────────────────────────────
const APP_VERSION = require('./package.json').version;
app.get('/api/config', (_req, res) => {
res.json({ turnstileSiteKey: TURNSTILE_SITE_KEY || null, signupsOpen: config.signupsOpen });
res.json({
turnstileSiteKey: TURNSTILE_SITE_KEY || null,
signupsOpen: config.signupsOpen,
version: APP_VERSION,
minRankedGames: MIN_RANKED_GAMES,
});
});
// Validate the stored auth token; the client calls this at startup so a stale
// or corrupted token doesn't leave it running as a "logged in" ghost.
app.get('/api/me', requireAuth, (req, res) => {
res.json({ id: req.user.id, username: req.user.username });
});
app.post('/api/register/initiate', async (req, res) => {
@@ -302,16 +349,52 @@ app.get('/api/profile/:username', (req, res) => {
const user = findUser(req.params.username);
if (!user) return res.status(404).json({ error: 'User not found' });
const effectiveId = user._fromShared ? `hokm_${user.id}` : user.id;
const s = getStats(effectiveId);
const s = readStats(effectiveId);
const played = s.games_played || 0;
res.json({
username: user.username,
games_played: s.games_played || 0,
games_played: played,
games_won: s.games_won || 0,
moon_shots: s.moon_shots || 0,
total_score: s.total_score || 0,
win_rate: played > 0 ? +(((s.games_won || 0) / played) * 100).toFixed(1) : 0,
avg_score: played > 0 ? +((s.total_score || 0) / played).toFixed(1) : 0,
isAdmin: ADMIN_USERNAME !== '' && user.username === ADMIN_USERNAME,
signupsOpen: config.signupsOpen,
});
});
// Every finished game this player took part in, newest first, with the full
// round-by-round breakdown so the client can render it without another call.
app.get('/api/history/:username', (req, res) => {
const user = findUser(req.params.username);
if (!user) return res.status(404).json({ error: 'User not found' });
const effectiveId = user._fromShared ? `hokm_${user.id}` : user.id;
const games = history
.filter(g => g.players?.some(p => p.uid === effectiveId))
.sort((a, b) => b.endedAt - a.endedAt)
.map(g => {
const me = g.players.find(p => p.uid === effectiveId);
const mySeat = me ? me.seat : -1;
return {
id: g.id,
endedAt: g.endedAt,
playerNames: g.playerNames,
finalScores: g.finalScores,
winners: g.winners,
winScore: g.winScore,
mySeat,
myScore: mySeat >= 0 ? g.finalScores[mySeat] : null,
won: mySeat >= 0 && g.winners.includes(mySeat),
rounds: g.rounds,
};
});
res.json(games);
});
// Finished games a player needs before they appear in the ranking proper.
const MIN_RANKED_GAMES = 5;
app.get('/api/leaderboard', (_req, res) => {
const allUsers = [...users];
if (SHARED_USERS_FILE) {
@@ -326,26 +409,43 @@ app.get('/api/leaderboard', (_req, res) => {
}
const rows = allUsers.map(u => {
const eid = u._fromShared ? `hokm_${u.id}` : u.id;
const s = getStats(eid);
const s = readStats(eid);
const played = s.games_played || 0;
const won = s.games_won || 0;
return {
username: u.username,
games_played: played,
games_won: s.games_won || 0,
games_won: won,
moon_shots: s.moon_shots || 0,
total_score: s.total_score || 0,
score_per_game: played > 0 ? +(( s.total_score || 0) / played).toFixed(2) : null,
win_rate: played > 0 ? +((won / played) * 100).toFixed(1) : null,
score_per_game: played > 0 ? +(( s.total_score || 0) / played).toFixed(1) : null,
};
})
.filter(r => r.games_played > 0)
// Lower score per game = better player — sort ascending
.sort((a, b) => {
if (a.score_per_game === null) return 1;
if (b.score_per_game === null) return -1;
return a.score_per_game - b.score_per_game || b.games_played - a.games_played;
})
.slice(0, 30);
res.json(rows);
.filter(r => r.games_played > 0);
// Win rate is the primary ranking; average score per game breaks ties, and
// there lower is better because Hearts scores are penalties.
const byWinRate = (a, b) =>
(b.win_rate - a.win_rate) ||
(a.score_per_game - b.score_per_game) ||
(b.games_played - a.games_played);
// A single lucky game shouldn't top the board, so a player needs
// MIN_RANKED_GAMES finished games before they get a rank. Everyone below that
// is still listed, unranked, so a new player can see their progress.
const ranked = rows.filter(r => r.games_played >= MIN_RANKED_GAMES)
.sort(byWinRate)
.slice(0, 30)
.map(r => ({ ...r, ranked: true, gamesToRank: 0 }));
const provisional = rows.filter(r => r.games_played < MIN_RANKED_GAMES)
.sort((a, b) => b.games_played - a.games_played || byWinRate(a, b))
.slice(0, 10)
.map(r => ({ ...r, ranked: false,
gamesToRank: MIN_RANKED_GAMES - r.games_played }));
res.json([...ranked, ...provisional]);
});
app.get('/api/rooms', (_req, res) => {
@@ -429,6 +529,9 @@ function newRoom(id) {
moonShooter: -1,
handDeltas: null,
winScore: 100,
roundHistory: [], // per-hand record for the breakdown + history
moonsBySeat: [0, 0, 0, 0], // moon shots this game, for the stats table
trickSnapshot: null, // last known-good state (see checkHandIntegrity)
spectators: new Set(),
isPublic: false,
createdAt: Date.now(),
@@ -472,6 +575,7 @@ function publicInfo(room, seat = -1) {
moonShooter: room.moonShooter,
handDeltas: room.handDeltas,
gameWinner: room.gameWinner,
roundHistory: room.roundHistory,
spectatorCount: room.spectators.size,
isPublic: room.isPublic,
aiControlledSeats: [...room.aiControlledSeats],
@@ -513,21 +617,29 @@ function broadcastAiControl(room, seat, active) {
function scheduleAfkTimer(room) {
clearAfkTimer(room);
if (room.state !== 'PLAYING') return;
const seat = room.currentTurn;
if (room.bots[seat]) return;
if (seat < 0 || room.bots[seat] || !room.seats[seat]) return;
if (room.aiControlledSeats.has(seat)) {
// Already AI-controlled — keep the game moving on a short timer
room.afkTimer = setTimeout(() => {
if (room.state !== 'PLAYING' || room.currentTurn !== seat) return;
if (!room.aiControlledSeats.has(seat)) return;
const card = botChooseCard(room, seat);
if (card) onCardPlayed(room, seat, card);
}, 10000);
} else {
room.afkSeat = seat;
room.afkTimer = setTimeout(() => {
if (room.state !== 'PLAYING') return;
broadcast(room, 'afkWarning', { seat, name: room.names[seat] });
}, 60000);
return;
}
// Normal seat: only flag it as AFK once the minute is actually up, so a
// takeover vote can't be cast against a player who is still thinking.
room.afkTimer = setTimeout(() => {
if (room.state !== 'PLAYING' || room.currentTurn !== seat) return;
room.afkSeat = seat;
room.afkVotes.clear();
broadcast(room, 'afkWarning', { seat, name: room.names[seat] });
}, 60000);
}
// ─── Dealing ──────────────────────────────────────────────────
@@ -611,18 +723,85 @@ function exchangePassCards(room) {
if (idx !== -1) room.hands[p].splice(idx, 1);
}
}
// Add to receivers
// Add to receivers. Seats are laid out clockwise from the viewer, matching
// the table: your left neighbour is seat+1, across is seat+2, right is seat+3.
// (Play runs anti-clockwise, seat → seat+3, i.e. bottom → right → top → left.)
for (let from = 0; from < 4; from++) {
// "left" = visual left (area-left = seat+3); "right" = visual right (area-right = seat+1)
const to = dir === 'left' ? (from + 3) % 4
const to = dir === 'left' ? (from + 1) % 4
: dir === 'across' ? (from + 2) % 4
: (from + 1) % 4; // right
: (from + 3) % 4; // right
for (const c of sending[from]) room.hands[to].push(c);
room.hands[to].sort(sortCards);
}
room.passCards = [null, null, null, null];
}
// ─── Hand integrity: every player must hold the same card count ───
// A player who somehow gets two cards out in one trick ends the hand early for
// everyone (they run dry while the others still hold cards). Playing is guarded
// against that at several points; this is the safety net that catches whatever
// slips through, by rewinding to the last state that was known to be sound.
function handsBalanced(room) {
const n = room.hands[0].length;
return room.hands.every(h => h.length === n);
}
// Save the state at the start of a trick, but only when it is actually sound —
// so the snapshot is always the last *correct* state we can fall back to.
function snapshotTrickStart(room) {
if (!handsBalanced(room)) return;
room.trickSnapshot = {
tricksPlayed: room.tricksPlayed,
hands: room.hands.map(h => h.slice()),
handPoints: room.handPoints.slice(),
heartsBroken: room.heartsBroken,
trickLead: room.trickLead,
currentTurn: room.trickLead,
lastTrick: room.lastTrick ? room.lastTrick.slice() : null,
lastTrickWinner: room.lastTrickWinner,
};
}
function restoreTrickSnapshot(room) {
const snap = room.trickSnapshot;
if (!snap) return false;
room.tricksPlayed = snap.tricksPlayed;
room.hands = snap.hands.map(h => h.slice());
room.handPoints = snap.handPoints.slice();
room.heartsBroken = snap.heartsBroken;
room.trickLead = snap.trickLead;
room.currentTurn = snap.currentTurn;
room.lastTrick = snap.lastTrick ? snap.lastTrick.slice() : null;
room.lastTrickWinner = snap.lastTrickWinner;
room.trick = [];
return true;
}
// Returns true when the hand is sound. When it isn't, rewinds the room to the
// start of the last good trick, tells everyone, and returns false — the caller
// must abandon whatever it was about to do next.
function checkHandIntegrity(room, where) {
const expected = 13 - room.tricksPlayed;
if (handsBalanced(room) && room.hands[0].length === expected) return true;
console.warn(`[${room.id}] card-count desync at ${where}: ` +
`hands ${room.hands.map(h => h.length).join('/')}, expected ${expected} each`);
if (!restoreTrickSnapshot(room)) {
console.error(`[${room.id}] no sound snapshot to restore — hand left as-is`);
return true; // nothing better to do than let the hand run out
}
clearAfkTimer(room);
if (room.trickTimer) { clearTimeout(room.trickTimer); room.trickTimer = null; }
broadcast(room, 'stateReverted', { trick: room.tricksPlayed + 1 });
broadcastState(room, 'roomInfo');
scheduleBotPlay(room);
scheduleAfkTimer(room);
return false;
}
// ─── Game flow ────────────────────────────────────────────────
function startPassing(room) {
clearAfkTimer(room);
@@ -639,17 +818,26 @@ function startPlaying(room) {
room.trickLead = find2Clubs(room);
room.currentTurn = room.trickLead;
room.trick = [];
snapshotTrickStart(room);
broadcastState(room, 'roomInfo');
scheduleBotPlay(room);
scheduleAfkTimer(room);
}
function onCardPlayed(room, player, card) {
// Remove from hand
room.hands[player] = room.hands[player].filter(c => c !== card);
// Add to trick
// ── Guards against a seat getting two cards into one trick ──
// Bots, the AFK auto-player and the socket handler all land here, so the
// checks live in one place rather than at each call site.
if (room.state !== 'PLAYING') return;
if (room.trick.length >= 4) return; // trick already resolving
if (room.currentTurn !== player) return; // not this seat's turn
if (room.trick.some(t => t.player === player)) return; // already played this trick
const idx = room.hands[player].indexOf(card);
if (idx === -1) return; // card isn't in hand — stale or duplicated click
room.hands[player].splice(idx, 1); // remove exactly one copy
room.trick.push({ card, player });
// Break hearts
if (isHeart(card) || card === 'S-Q') room.heartsBroken = true;
if (room.trick.length < 4) {
@@ -660,27 +848,33 @@ function onCardPlayed(room, player, card) {
return;
}
// Trick complete
const winner = trickWinner(room.trick);
// Trick complete. Nobody is on turn during the resolution window, so the
// player who closed the trick can't slip a second card in before the
// trick-advance timer fires.
room.currentTurn = -1;
clearAfkTimer(room);
if (room.trickTimer) clearTimeout(room.trickTimer);
const winner = trickWinner(room.trick);
const trickPts = room.trick.reduce((s, t) => s + points(t.card), 0);
room.handPoints[winner] += trickPts;
room.tricksPlayed++;
room.lastTrick = room.trick.slice();
room.lastTrickWinner = winner;
// Every hand must now hold the same number of cards. If not, rewind.
if (!checkHandIntegrity(room, `end of trick ${room.tricksPlayed}`)) return;
broadcastState(room, 'trickWon');
if (room.tricksPlayed === 13) {
broadcastState(room, 'trickWon');
clearAfkTimer(room);
if (room.trickTimer) clearTimeout(room.trickTimer);
room.trickTimer = setTimeout(() => finishHand(room), 1400);
} else {
broadcastState(room, 'trickWon');
clearAfkTimer(room);
if (room.trickTimer) clearTimeout(room.trickTimer);
room.trickTimer = setTimeout(() => {
room.trickLead = winner;
room.currentTurn = winner;
room.trick = [];
snapshotTrickStart(room);
broadcastState(room, 'roomInfo');
scheduleBotPlay(room);
scheduleAfkTimer(room);
@@ -690,6 +884,11 @@ function onCardPlayed(room, player, card) {
function finishHand(room) {
clearAfkTimer(room);
// A hand can only end with every hand empty. If cards are left over the
// deal desynced somewhere; rewind rather than score a broken hand.
if (room.hands.some(h => h.length > 0)) {
if (!checkHandIntegrity(room, 'end of hand')) return;
}
for (const s of room.aiControlledSeats) broadcastAiControl(room, s, false);
room.aiControlledSeats.clear();
// Check shoot the moon (one player has all 26 pts)
@@ -706,6 +905,17 @@ function finishHand(room) {
room.handDeltas = deltas;
for (let i = 0; i < 4; i++) room.scores[i] += deltas[i];
if (shooter !== -1) room.moonsBySeat[shooter]++;
// Record the hand for the end-of-hand breakdown, the game-over screen and
// the saved game history.
room.roundHistory.push({
hand: room.roundHistory.length + 1,
deltas: deltas.slice(),
scores: room.scores.slice(),
moonShooter: shooter,
moonShooterName: shooter !== -1 ? (room.names[shooter] || '') : '',
});
// Check game over: someone hit winScore
if (room.scores.some(s => s >= room.winScore)) {
@@ -740,7 +950,8 @@ function finishGame(room) {
room.state = 'GAME_OVER';
broadcastState(room, 'gameOver');
// Skip stats entirely if any bot participated — games vs bots don't count
// Skip stats entirely if any bot participated — games vs bots don't count,
// and they aren't written to history either, to keep both lists clean.
if (room.bots.some(Boolean)) return;
const winners = new Set(room.gameWinner);
@@ -750,16 +961,58 @@ function finishGame(room) {
addStats(uid, {
games_played: 1,
games_won: winners.has(i) ? 1 : 0,
moon_shots: 0,
moon_shots: room.moonsBySeat[i],
total_score: room.scores[i],
});
}
saveGameHistory(room, winners);
}
// Persist a finished game so each participant can review it later.
function saveGameHistory(room, winners) {
pushHistory({
id: `${room.id}-${Date.now()}`,
endedAt: Date.now(),
winScore: room.winScore,
playerNames: room.names.slice(),
finalScores: room.scores.slice(),
winners: [...winners],
players: room.userIds
.map((uid, seat) => ({ uid, seat, name: room.names[seat] }))
.filter(p => p.uid != null),
rounds: room.roundHistory,
});
}
// ─── Room teardown / leave recovery ───────────────────────────
function destroyRoom(room) {
if (room.trickTimer) clearTimeout(room.trickTimer);
if (room.afkTimer) clearTimeout(room.afkTimer);
rooms.delete(room.id);
}
// A human who leaves mid-game has their seat handed to AI; nudge the current
// phase so that AI acts if the game is now waiting on that seat.
function resumeAfterLeave(room, seat) {
if (room.state === 'PASSING') {
if (room.bots[seat] && room.passCards[seat] === null) {
setTimeout(() => botPass(room, seat), 700);
}
} else if (room.state === 'PLAYING') {
scheduleAfkTimer(room);
scheduleBotPlay(room);
}
}
// ─── Start the game ───────────────────────────────────────────
function tryStartGame(room) {
if (room.seats.filter(Boolean).length + room.bots.filter(Boolean).length < 4) return;
if (room.seats.some((s, i) => !s && !room.bots[i])) return;
// Fresh game — clear the accumulators that span hands
room.scores = [0, 0, 0, 0];
room.roundHistory = [];
room.moonsBySeat = [0, 0, 0, 0];
dealHand(room); // handNumber is 0 from newRoom; passDirection set inside
if (room.passDirection === 'hold') {
startPlaying(room);
@@ -995,6 +1248,42 @@ io.on('connection', (socket) => {
tryStartGame(room);
});
// ── Swap seats (creator only, while still in the waiting room) ──
socket.on('swapSeats', ({ roomId, seatA, seatB } = {}) => {
const room = rooms.get((roomId || '').toUpperCase());
if (!room || room.state !== 'WAITING') return;
const isCreator = room.seats[0] === socket.id ||
(user?.id && room.userIds[0] === user.id);
if (!isCreator) return;
if (seatA === seatB || ![0,1,2,3].includes(seatA) || ![0,1,2,3].includes(seatB)) return;
for (const key of ['names', 'seats', 'tokens', 'userIds', 'bots']) {
[room[key][seatA], room[key][seatB]] = [room[key][seatB], room[key][seatA]];
}
// Each moved player needs their new seat number and token
if (room.seats[seatA]) io.to(room.seats[seatA]).emit('seatChanged', { seat: seatA, token: room.tokens[seatA] });
if (room.seats[seatB]) io.to(room.seats[seatB]).emit('seatChanged', { seat: seatB, token: room.tokens[seatB] });
broadcastState(room, 'roomInfo');
});
// ── Force start (creator only, fills the remaining seats with bots) ──
socket.on('forceStart', ({ roomId } = {}) => {
const room = rooms.get((roomId || '').toUpperCase());
if (!room || room.state !== 'WAITING') return;
const isCreator = room.seats[0] === socket.id ||
(user?.id && room.userIds[0] === user.id);
if (!isCreator) return;
const botNames = ['Alice', 'Bob', 'Charlie', 'Diana'];
for (let i = 0; i < 4; i++) {
if (!room.seats[i] && !room.bots[i]) {
room.bots[i] = true;
room.names[i] = botNames[i];
}
}
broadcastState(room, 'roomInfo');
tryStartGame(room);
});
// ── Pass cards ─────────────────────────────────────────────
socket.on('passCards', ({ roomId, seat, token, cards } = {}) => {
const room = rooms.get((roomId || '').toUpperCase());
@@ -1022,6 +1311,10 @@ io.on('connection', (socket) => {
if (room.state !== 'PLAYING') return;
if (room.tokens[seat] !== token) return;
if (room.currentTurn !== seat) return socket.emit('playError', 'Not your turn');
// Belt and braces against a double-tap or a duplicated socket event landing
// twice: one seat may only ever contribute one card to a trick.
if (room.trick.some(t => t.player === seat)) return socket.emit('playError', 'Already played this trick');
if (!room.hands[seat].includes(card)) return socket.emit('playError', 'Card not in hand');
if (!isLegal(room, seat, card)) return socket.emit('playError', 'Illegal card');
if (room.aiControlledSeats.has(seat)) {
room.aiControlledSeats.delete(seat);
@@ -1062,12 +1355,34 @@ io.on('connection', (socket) => {
socket.on('leave', ({ roomId, seat, token } = {}) => {
const room = rooms.get((roomId || '').toUpperCase());
if (!room) return;
if (room.tokens[seat] === token) {
room.seats[seat] = null;
room.tokens[seat] = null;
room.userIds[seat] = null;
}
if (room.tokens[seat] !== token) { socket.leave(room.id); return; }
socket.leave(room.id);
// Vacate the seat. Nulling userIds also stops hasActiveGame pulling this
// player straight back into the room they just left.
room.seats[seat] = null;
room.tokens[seat] = null;
room.userIds[seat] = null;
room.aiControlledSeats.delete(seat);
const inProgress = room.state !== 'WAITING' && room.state !== 'GAME_OVER';
// Nobody left to play for — tear the room down
if (!room.seats.some(Boolean) && room.spectators.size === 0) {
destroyRoom(room);
return;
}
if (inProgress) {
// Hand the seat to AI so the game keeps going for everyone else
room.bots[seat] = true;
broadcastState(room, 'roomInfo');
resumeAfterLeave(room, seat);
} else {
room.names[seat] = '';
broadcastState(room, 'roomInfo');
}
});
socket.on('disconnect', () => {