Files
two-keys/server/src/rooms/store.ts
T
joshuaandClaude Opus 5.5 6669be11e5 V1.2.0
Bring games 9-18 in line with GAMES-NEW.md:
- Library sorts easiest first, filters by category and difficulty; difficulty 5
  shows a Nightmare chip, and a no-hint finish earns Nightmare Survivors.
- Time limits end on "Out of time" (no rank); Deep Lab Nereid's countdown is a
  rising water gauge behind the header.
- Evidence Locker search, chapter filter and starred clues (partner sees a count).
- One-shot accusations ask "One shot. Are you both sure?" first.
- Symbol font fallback, tight monospace blocks for grids/keypads/SQL.
- Rank rounds reorder by drag or up/down buttons; reveal highlights #1 and #4.
- Telepathy capped at 30 characters; maze:move accepts forward/left/right/back;
  gate buttons read "Gate (won't open from this side)".
- Overtime solver tables checked against Appendix A; keypad generator re-rolls.
- More content checks (rank items, password fixtures, glyphs/gates on traps) and
  sanitize tests for all ten new games.
- GAMES.md carries the full spoiler guide for 9-18.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 08:44:28 +02:00

132 lines
3.4 KiB
TypeScript

import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import type { Phase, PlayMode, Role, Seat } from '@two-keys/shared';
import { makeCode } from './codes';
export interface PlayerRec {
token: string;
seat: Seat | null;
ready: boolean;
viewing: string | null;
}
export interface Room {
code: string;
gameId: string;
mode: PlayMode;
phase: Phase;
players: PlayerRec[];
createdAt: number;
lastActivity: number;
notepad: string;
keys: string[];
startedAt: number | null;
finishedAt: number | null;
penaltySeconds: number;
hintsUsed: number;
wrongGuesses: number;
/** Engine-specific state, owned by the game's engine. */
engine: unknown;
result: { success: boolean; ending: string | null; reveal: string | null; outOfTime?: boolean } | null;
}
export const ROOM_TTL_MS = 24 * 60 * 60 * 1000;
export const SNAPSHOT_INTERVAL_MS = 10_000;
export function seatFor(room: Room, role: Role): PlayerRec | undefined {
return room.players.find((p) => p.seat === role || p.seat === 'both');
}
/** In-memory room store, snapshotted to disk so a restart doesn't kill a game in progress. */
export class RoomStore {
readonly rooms = new Map<string, Room>();
private timer: NodeJS.Timeout | null = null;
constructor(private readonly file: string | null) {}
create(gameId: string, mode: PlayMode, now = Date.now()): { room: Room; player: PlayerRec } {
const player: PlayerRec = {
token: randomUUID(),
seat: mode === 'couch' ? 'both' : null,
ready: false,
viewing: null,
};
const room: Room = {
code: makeCode((code) => this.rooms.has(code)),
gameId,
mode,
phase: 'lobby',
players: [player],
createdAt: now,
lastActivity: now,
notepad: '',
keys: [],
startedAt: null,
finishedAt: null,
penaltySeconds: 0,
hintsUsed: 0,
wrongGuesses: 0,
engine: null,
result: null,
};
this.rooms.set(room.code, room);
return { room, player };
}
get(code: string): Room | undefined {
return this.rooms.get(code);
}
/** Drop rooms idle for more than 24h. */
sweep(now = Date.now()): number {
let removed = 0;
for (const [code, room] of this.rooms) {
if (now - room.lastActivity > ROOM_TTL_MS) {
this.rooms.delete(code);
removed++;
}
}
return removed;
}
load(isKnownGame: (gameId: string) => boolean): void {
if (!this.file || !fs.existsSync(this.file)) return;
try {
const rooms = JSON.parse(fs.readFileSync(this.file, 'utf8')) as Room[];
for (const room of rooms) {
if (room?.code && isKnownGame(room.gameId)) this.rooms.set(room.code, room);
}
this.sweep();
} catch (err) {
console.warn(`Could not restore rooms from ${this.file}:`, err);
}
}
snapshot(): void {
if (!this.file) return;
try {
fs.mkdirSync(path.dirname(this.file), { recursive: true });
const tmp = `${this.file}.tmp`;
fs.writeFileSync(tmp, JSON.stringify([...this.rooms.values()]));
fs.renameSync(tmp, this.file);
} catch (err) {
console.warn('Room snapshot failed:', err);
}
}
start(): void {
this.timer = setInterval(() => {
this.sweep();
this.snapshot();
}, SNAPSHOT_INTERVAL_MS);
this.timer.unref();
}
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
this.snapshot();
}
}