Two Keys: co-op mystery games for couples. Eight games on four engines (story, defuse, sync, labyrinth), two-device and couch play, mobile-first UI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 22:36:12 +02:00
co-authored by Claude Opus 5.5
commit 0de6617c82
85 changed files with 15692 additions and 0 deletions
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@two-keys/server",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc --noEmit -p tsconfig.json && esbuild src/index.ts --bundle --platform=node --format=esm --target=node20 --packages=external --alias:@two-keys/shared=../shared/src/index.ts --outfile=dist/index.js",
"start": "node dist/index.js",
"test": "vitest run"
},
"dependencies": {
"@two-keys/shared": "*",
"express": "^4.21.0",
"js-yaml": "^4.1.0",
"socket.io": "^4.8.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/js-yaml": "^4.0.9",
"@types/node": "^20.16.0",
"esbuild": "^0.24.0",
"socket.io-client": "^4.8.0",
"vitest": "^2.1.0"
}
}
+66
View File
@@ -0,0 +1,66 @@
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import express from 'express';
import { Server } from 'socket.io';
import { findRoot, gamesDir, loadGames } from './content/loader';
import { gameSummary } from './content/sanitize';
import { RoomStore } from './rooms/store';
import { registerHandlers } from './socket/handlers';
export interface AppOptions {
root?: string;
/** Where rooms are snapshotted; null keeps them in memory only. */
dataFile?: string | null;
}
export function createApp(opts: AppOptions = {}) {
const root = opts.root ?? findRoot();
const games = loadGames(gamesDir(root));
const dataFile = opts.dataFile === undefined ? path.join(root, 'server', 'data', 'rooms.json') : opts.dataFile;
const store = new RoomStore(dataFile);
store.load((gameId) => games.has(gameId));
const app = express();
app.disable('x-powered-by');
const summaries = [...games.values()].map(gameSummary);
app.get('/api/health', (_req, res) => res.json({ ok: true, games: games.size, rooms: store.rooms.size }));
app.get('/api/games', (_req, res) => res.json(summaries));
// In production the same process serves the built client.
const clientDist = path.join(root, 'client', 'dist');
if (fs.existsSync(path.join(clientDist, 'index.html'))) {
app.use(express.static(clientDist));
app.get('*', (req, res, next) => {
if (req.path.startsWith('/api/') || req.path.startsWith('/socket.io')) return next();
res.sendFile(path.join(clientDist, 'index.html'));
});
}
const server = http.createServer(app);
const io = new Server(server, { maxHttpBufferSize: 64 * 1024 });
const stopTicker = registerHandlers(io, games, store);
return {
app,
server,
io,
games,
store,
listen(port: number): Promise<number> {
return new Promise((resolve) => {
server.listen(port, () => {
store.start();
const address = server.address();
resolve(typeof address === 'object' && address ? address.port : port);
});
});
},
async close(): Promise<void> {
stopTicker();
store.stop();
await io.close();
},
};
}
+66
View File
@@ -0,0 +1,66 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import yaml from 'js-yaml';
import { gameSchema, type Game } from './schemas';
import { validateGame } from './validate';
/** The repo root: the nearest ancestor of this file that contains content/games. */
export function findRoot(): string {
if (process.env.TWO_KEYS_ROOT) return path.resolve(process.env.TWO_KEYS_ROOT);
let dir = path.dirname(fileURLToPath(import.meta.url));
for (;;) {
if (fs.existsSync(path.join(dir, 'content', 'games'))) return dir;
const parent = path.dirname(dir);
if (parent === dir) throw new Error('Could not find content/games above ' + import.meta.url);
dir = parent;
}
}
export const gamesDir = (root = findRoot()) => path.join(root, 'content', 'games');
export interface LoadedFile {
file: string;
game: Game | null;
errors: string[];
}
export function loadGameFile(file: string): LoadedFile {
const name = path.basename(file);
let raw: unknown;
try {
raw = yaml.load(fs.readFileSync(file, 'utf8'));
} catch (err) {
return { file: name, game: null, errors: [`YAML parse error: ${(err as Error).message}`] };
}
const parsed = gameSchema.safeParse(raw);
if (!parsed.success) {
const errors = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);
return { file: name, game: null, errors };
}
const game = parsed.data;
const errors = validateGame(game);
const expectedId = name.replace(/\.ya?ml$/, '');
if (game.id !== expectedId) errors.push(`id "${game.id}" does not match filename "${name}"`);
return { file: name, game, errors };
}
export function loadAllFiles(dir = gamesDir()): LoadedFile[] {
return fs
.readdirSync(dir)
.filter((f) => /\.ya?ml$/.test(f))
.sort()
.map((f) => loadGameFile(path.join(dir, f)));
}
/** Loads every game at boot; refuses to start on invalid content. */
export function loadGames(dir = gamesDir()): Map<string, Game> {
const games = new Map<string, Game>();
const problems: string[] = [];
for (const { file, game, errors } of loadAllFiles(dir)) {
if (errors.length > 0 || !game) problems.push(...errors.map((e) => `${file}: ${e}`));
else games.set(game.id, game);
}
if (problems.length > 0) throw new Error(`Invalid game content:\n ${problems.join('\n ')}`);
return games;
}
+273
View File
@@ -0,0 +1,273 @@
// Builds everything that leaves the server. Views are assembled field by field (never by
// copying a content object and deleting from it), so answers can't leak by accident.
import type {
ChapterView,
ClueView,
DefuseModuleView,
DefuseView,
Dir,
EngineView,
GameMeta,
GameSummary,
LabyrinthView,
LockView,
Role,
StoryView,
SyncView,
} from '@two-keys/shared';
import { otherRole } from '@two-keys/shared';
import { remainingAt, type DefuseState } from '../engines/defuse';
import { totalKeys } from '../engines/index';
import { DELTAS, cellAt, isWall, type LabyrinthState } from '../engines/labyrinth';
import { NUDGE_AFTER_WRONG, type StoryState } from '../engines/story';
import { canReplay, type SyncState } from '../engines/sync';
import type { Room } from '../rooms/store';
import type { Clue, DefuseGame, Game, LabyrinthGame, Lock, StoryGame, SyncGame } from './schemas';
export function gameSummary(game: Game): GameSummary {
return {
id: game.id,
engine: game.engine,
category: game.category,
title: game.title,
tagline: game.tagline,
estimatedMinutes: game.estimatedMinutes,
difficulty: game.difficulty,
theme: { ...game.theme },
roles: { A: { ...game.roles.A }, B: { ...game.roles.B } },
totalKeys: totalKeys(game),
};
}
export function gameMeta(game: Game): GameMeta {
return { ...gameSummary(game), intro: game.intro };
}
// ---------- story ----------
function clueView(clue: Clue, audience: ClueView['audience']): ClueView {
const view: ClueView = { id: clue.id, title: clue.title, type: clue.type, body: clue.body, audience };
if (clue.type === 'signal' && clue.signal) view.signal = clue.signal;
return view;
}
function lockView(lock: Lock, s: StoryState): LockView {
const solved = s.solved.includes(lock.id);
const wrongAttempts = s.wrong[lock.id] ?? 0;
return {
id: lock.id,
prompt: lock.prompt,
inputType: lock.inputType,
format: lock.format ?? null,
options: lock.options?.map((o) => ({ id: o.id, label: o.label })) ?? null,
solved,
hints: lock.hints.slice(0, s.hints[lock.id] ?? 0),
hintsTotal: lock.hints.length,
wrongAttempts,
nudge: !solved && wrongAttempts >= NUDGE_AFTER_WRONG,
successText: solved ? (lock.successText ?? null) : null,
keyName: solved ? (lock.keyName ?? null) : null,
};
}
export function storyView(game: StoryGame, s: StoryState, role: Role): StoryView {
const total = game.chapters.length;
const atFinale = s.chapter >= total;
const chapters: ChapterView[] = game.chapters.slice(0, Math.min(s.chapter, total - 1) + 1).map((ch) => ({
id: ch.id,
title: ch.title,
narrative: ch.narrative,
clues: [
...ch.clues[role].map((c) => clueView(c, 'private')),
...ch.clues.shared.map((c) => clueView(c, 'shared')),
],
lock: lockView(ch.lock, s),
}));
let finale: StoryView['finale'] = null;
if (atFinale && game.finale.type === 'accusation') {
const f = game.finale;
finale = {
type: 'accusation',
prompt: f.prompt,
questions: f.questions.map((q) => ({
id: q.id,
label: q.label,
options: q.options.map((o) => ({ id: o.id, label: o.label })),
})),
proposal: s.finale.proposal
? { answers: { ...s.finale.proposal.answers }, by: s.finale.proposal.by }
: null,
agreed: s.finale.agreed,
attemptsLeft: Math.max(0, f.maxAttempts - s.finale.attempts),
maxAttempts: f.maxAttempts,
};
} else if (atFinale && game.finale.type === 'escape') {
const f = game.finale;
finale = {
type: 'escape',
prompt: f.prompt,
clues: f.clues[role].map((c) => clueView(c, 'private')),
lock: lockView(f.lock, s),
};
}
return {
engine: 'story',
suspects: (game.suspects ?? []).map((x) => ({ ...x })),
chapters,
currentChapter: Math.min(s.chapter, total),
totalChapters: total,
awaitingContinue: s.awaitingContinue,
finale,
};
}
// ---------- defuse ----------
export function defuseView(game: DefuseGame, s: DefuseState, role: Role, now: number): DefuseView {
const level = game.levels[s.level];
const common = {
engine: 'defuse' as const,
level: { index: s.level, total: game.levels.length, title: level.title, timeSeconds: level.timeSeconds },
status: s.status,
failReason: s.failReason,
strikes: s.strikes,
maxStrikes: game.strikes.max,
clock: s.clock
? { remaining: Math.max(0, remainingAt(s, now)), speed: s.clock.speed, running: s.status === 'active' }
: null,
};
// The Expert gets the manual and nothing about the device.
if (role === 'B') return { ...common, seat: 'expert', manual: game.manual };
// The Technician gets the device and never the manual.
const d = s.device;
if (!d) return { ...common, seat: 'technician', device: null };
const modules: DefuseModuleView[] = [];
if (d.wires) modules.push({ id: 'wires', solved: d.wires.solved, wires: [...d.wires.colors] });
if (d.button) {
modules.push({
id: 'button',
solved: d.button.solved,
label: d.button.label,
color: d.button.color,
holding: d.button.holding,
// The strip only lights up while the button is held.
strip: d.button.holding ? d.button.strip : null,
});
}
if (d.keypad) {
const { pressed } = d.keypad;
modules.push({
id: 'keypad',
solved: d.keypad.solved,
symbols: d.keypad.symbols.map((id) => ({
id,
label: game.modules.keypad.symbols[id] ?? id,
pressed: pressed.includes(id),
})),
});
}
return { ...common, seat: 'technician', device: { serial: d.serial, batteries: d.batteries, modules } };
}
// ---------- sync ----------
export function syncView(game: SyncGame, s: SyncState, role: Role): SyncView {
const round = game.rounds[s.round];
const subject = round.type === 'predict' ? (round.subject ?? 'A') : null;
const q = s.status === 'question' || s.status === 'reveal' ? s.questions[s.q] : undefined;
const answers = q ? (s.answers[q.id] ?? {}) : {};
const both = answers.A !== undefined && answers.B !== undefined;
return {
engine: 'sync',
status: s.status,
round: {
index: s.round,
total: game.rounds.length,
title: round.title,
type: round.type,
blurb: round.blurb,
subject,
},
isReplay: s.attempt > 0,
questionNumber: s.q + 1,
questionsPerRound: s.questions.length,
pointsForKey: game.rules.pointsForKey,
points: s.marks.filter(Boolean).length,
question: q
? {
id: q.id,
text: q.q.replaceAll('{subject}', subject ? game.roles[subject].name : ''),
options: [...q.options],
}
: null,
iAmSubject: subject === role,
myAnswer: answers[role] ?? null,
// Whether the partner has answered, never what they answered, until both are in.
partnerAnswered: answers[otherRole(role)] !== undefined,
reveal: both ? { A: answers.A!, B: answers.B!, match: answers.A === answers.B } : null,
marks: [...s.marks],
summary:
s.status === 'summary'
? { earned: s.earned, canReplay: canReplay(game, s), keyName: round.keyName }
: null,
};
}
// ---------- labyrinth ----------
export function labyrinthView(game: LabyrinthGame, s: LabyrinthState, role: Role): LabyrinthView {
const keysCarried = s.collected.filter(Boolean).length;
const total = game.lanterns.length;
// Navigator: the whole map, but never the Explorer's coordinates.
if (role === 'A') {
return {
engine: 'labyrinth',
seat: 'navigator',
grid: [...game.grid],
glyphs: game.glyphs.map((g) => ({ x: g.x, y: g.y, label: g.label })),
lanterns: game.lanterns.map((l, i) => ({ x: l.x, y: l.y, name: l.name, collected: s.collected[i] })),
keysCarried,
totalKeys: total,
moves: game.navigatorView.showMoveCount ? s.moves : null,
falls: s.falls,
};
}
// Explorer: only the cell under their feet. No grid, no coordinates, no traps.
const open = {} as Record<Dir, boolean>;
for (const dir of Object.keys(DELTAS) as Dir[]) {
open[dir] = !isWall(game.grid, s.x + DELTAS[dir].x, s.y + DELTAS[dir].y);
}
const glyph = game.glyphs.find((g) => g.x === s.x && g.y === s.y);
return {
engine: 'labyrinth',
seat: 'explorer',
glyphLabel: glyph?.label ?? null,
open,
keysCarried,
totalKeys: total,
atExit: cellAt(game.grid, s.x, s.y) === 'E',
message: s.message || (glyph ? '' : game.explorerView.flavour.blank),
moves: s.moves,
falls: s.falls,
};
}
export function engineView(game: Game, room: Room, role: Role, now: number): EngineView {
switch (game.engine) {
case 'story':
return storyView(game, room.engine as StoryState, role);
case 'defuse':
return defuseView(game, room.engine as DefuseState, role, now);
case 'sync':
return syncView(game, room.engine as SyncState, role);
case 'labyrinth':
return labyrinthView(game, room.engine as LabyrinthState, role);
}
}
+229
View File
@@ -0,0 +1,229 @@
import { z } from 'zod';
import { CLUE_TYPES } from '@two-keys/shared';
const hex = z.string().regex(/^#[0-9a-fA-F]{6}$/, 'expected a #rrggbb colour');
const roleInfo = z.object({ name: z.string().min(1), blurb: z.string() });
const header = {
id: z.string().regex(/^[a-z0-9-]+$/),
category: z.enum(['murder-mystery', 'escape-room', 'co-op']),
title: z.string().min(1),
tagline: z.string().min(1),
estimatedMinutes: z.number().positive(),
difficulty: z.number().int().min(1).max(3),
players: z.object({ min: z.literal(2), max: z.literal(2) }),
theme: z.object({ primary: hex, accent: hex, background: hex, headingFont: z.string().min(1) }),
roles: z.object({ A: roleInfo, B: roleInfo }),
intro: z.string().min(1),
};
// ---------- story ----------
const clueSchema = z.object({
id: z.string().min(1),
title: z.string().min(1),
type: z.enum(CLUE_TYPES),
body: z.string(),
signal: z
.string()
.regex(/^[.\-/]+$/, 'signal may only contain . - /')
.optional(),
});
const optionSchema = z.object({ id: z.string().min(1), label: z.string().min(1) });
const lockSchema = z.object({
id: z.string().min(1),
prompt: z.string().min(1),
inputType: z.enum(['code', 'text', 'choice']),
format: z.string().optional(),
options: z.array(optionSchema).min(2).optional(),
answers: z.array(z.string().min(1)).min(1),
hints: z.array(z.string().min(1)).length(3),
successText: z.string().optional(),
keyName: z.string().optional(),
});
const chapterSchema = z.object({
id: z.string().min(1),
title: z.string().min(1),
narrative: z.string(),
clues: z.object({
A: z.array(clueSchema).default([]),
B: z.array(clueSchema).default([]),
shared: z.array(clueSchema).default([]),
}),
lock: lockSchema.extend({ successText: z.string().min(1), keyName: z.string().min(1) }),
});
const finaleSchema = z.discriminatedUnion('type', [
z.object({
type: z.literal('accusation'),
prompt: z.string().min(1),
questions: z
.array(
z.object({
id: z.string().min(1),
label: z.string().min(1),
options: z.array(optionSchema).min(2),
answer: z.string().min(1),
}),
)
.min(1),
maxAttempts: z.number().int().positive(),
successEnding: z.string().min(1),
failEnding: z.string().min(1),
reveal: z.string().min(1),
}),
z.object({
type: z.literal('escape'),
prompt: z.string().min(1),
clues: z.object({ A: z.array(clueSchema).default([]), B: z.array(clueSchema).default([]) }),
lock: lockSchema,
successEnding: z.string().min(1),
}),
]);
const storySchema = z.object({
...header,
engine: z.literal('story'),
suspects: z
.array(z.object({ id: z.string(), name: z.string(), role: z.string(), description: z.string() }))
.optional(),
chapters: z.array(chapterSchema).min(1),
finale: finaleSchema,
});
// ---------- defuse ----------
const range = z.object({ min: z.number().int().nonnegative(), max: z.number().int().nonnegative() });
const moduleId = z.enum(['wires', 'button', 'keypad']);
const defuseSchema = z.object({
...header,
engine: z.literal('defuse'),
device: z.object({
serial: z.object({ length: z.number().int().min(2), alphabet: z.string().min(2) }),
batteries: range,
}),
levels: z
.array(
z.object({
id: z.string().min(1),
title: z.string().min(1),
timeSeconds: z.number().int().positive(),
modules: z.array(moduleId).min(1),
keyName: z.string().min(1),
}),
)
.min(1),
strikes: z.object({ max: z.number().int().positive(), speedUpPerStrike: z.number().nonnegative() }),
modules: z.object({
wires: z.object({ count: range, colors: z.array(z.string()).min(2) }),
button: z.object({
labels: z.array(z.string()).min(1),
colors: z.array(z.string()).min(1),
stripColors: z.array(z.string()).min(1),
}),
keypad: z.object({
symbols: z.record(z.string()),
columns: z.array(z.array(z.string()).min(4)).min(1),
}),
}),
manual: z.string().min(1),
fixtures: z.object({
wires: z.array(
z.object({
serial: z.string(),
batteries: z.number().int(),
wires: z.array(z.string()),
expect: z.object({ type: z.literal('cut'), index: z.number().int() }),
}),
),
button: z.array(
z.object({
batteries: z.number().int(),
label: z.string(),
color: z.string(),
strip: z.string(),
expect: z.union([
z.object({ type: z.literal('tap') }),
z.object({ type: z.literal('hold'), releaseDigit: z.number().int() }),
]),
}),
),
keypad: z.array(z.object({ symbols: z.array(z.string()), expect: z.array(z.string()) })),
}),
});
// ---------- sync ----------
const questionSchema = z.object({
id: z.string().min(1),
q: z.string().min(1),
options: z.array(z.coerce.string()).min(2),
});
const syncSchema = z.object({
...header,
engine: z.literal('sync'),
rules: z.object({
questionsPerRound: z.number().int().positive(),
pointsForKey: z.number().int().positive(),
replaysPerRound: z.number().int().nonnegative(),
}),
rounds: z
.array(
z.object({
id: z.string().min(1),
title: z.string().min(1),
type: z.enum(['match', 'predict']),
subject: z.enum(['A', 'B']).optional(),
blurb: z.string(),
keyName: z.string().min(1),
}),
)
.min(1),
match: z.array(questionSchema),
predict: z.array(questionSchema),
});
// ---------- labyrinth ----------
const labyrinthSchema = z.object({
...header,
engine: z.literal('labyrinth'),
grid: z.array(z.string().regex(/^[#.SEKT]+$/, 'grid may only contain # . S E K T')).min(3),
glyphs: z.array(
z.object({ x: z.number().int(), y: z.number().int(), glyph: z.string(), label: z.string().min(1) }),
),
lanterns: z.array(z.object({ x: z.number().int(), y: z.number().int(), name: z.string().min(1) })),
explorerView: z.object({
flavour: z.object({
blank: z.string(),
trap: z.string(),
lantern: z.string(),
exitLocked: z.string(),
exitOpen: z.string(),
}),
}),
navigatorView: z.object({ showMoveCount: z.boolean().default(true) }),
scoring: z.object({ trapPenaltySeconds: z.number().nonnegative(), parMoves: z.number().int().positive() }),
successEnding: z.string().min(1),
});
export const gameSchema = z.discriminatedUnion('engine', [
storySchema,
defuseSchema,
syncSchema,
labyrinthSchema,
]);
export type StoryGame = z.infer<typeof storySchema>;
export type DefuseGame = z.infer<typeof defuseSchema>;
export type SyncGame = z.infer<typeof syncSchema>;
export type LabyrinthGame = z.infer<typeof labyrinthSchema>;
export type Game = z.infer<typeof gameSchema>;
export type Clue = z.infer<typeof clueSchema>;
export type Lock = z.infer<typeof lockSchema>;
export type SyncQuestion = z.infer<typeof questionSchema>;
+154
View File
@@ -0,0 +1,154 @@
import { normalizeAnswer } from '@two-keys/shared';
import { solveButton, solveKeypad, solveWires } from '../engines/defuse';
import { cellAt, findCells, isReachable, safeReachable } from '../engines/labyrinth';
import type { Clue, DefuseGame, Game, LabyrinthGame, Lock, StoryGame, SyncGame } from './schemas';
export const MIN_SYNC_QUESTIONS = 15;
/** Checks beyond the zod schema. Returns human-readable problems (empty = valid). */
export function validateGame(game: Game): string[] {
switch (game.engine) {
case 'story':
return validateStory(game);
case 'defuse':
return validateDefuse(game);
case 'sync':
return validateSync(game);
case 'labyrinth':
return validateLabyrinth(game);
}
}
function validateStory(game: StoryGame): string[] {
const errors: string[] = [];
const ids = new Set<string>();
const unique = (kind: string, id: string) => {
if (ids.has(`${kind}:${id}`)) errors.push(`duplicate ${kind} id "${id}"`);
ids.add(`${kind}:${id}`);
};
const checkClues = (where: string, clues: Clue[]) => {
for (const clue of clues) {
unique('clue', clue.id);
if (clue.type === 'signal' && !clue.signal) errors.push(`${where}: signal clue "${clue.id}" has no signal`);
}
};
const checkLock = (where: string, lock: Lock) => {
unique('lock', lock.id);
if (lock.answers.length < 1) errors.push(`${where}: lock has no answers`);
if (lock.hints.length !== 3) errors.push(`${where}: lock needs exactly 3 hints`);
if (lock.answers.some((a) => normalizeAnswer(a) === '')) errors.push(`${where}: an answer normalizes to nothing`);
if (lock.inputType === 'choice') {
const options = (lock.options ?? []).map((o) => normalizeAnswer(o.id));
if (options.length === 0) errors.push(`${where}: choice lock has no options`);
for (const a of lock.answers) {
if (!options.includes(normalizeAnswer(a))) errors.push(`${where}: answer "${a}" is not one of the options`);
}
}
};
for (const ch of game.chapters) {
const where = `chapter ${ch.id}`;
unique('chapter', ch.id);
if (ch.clues.A.length < 1) errors.push(`${where}: needs at least one clue for A`);
if (ch.clues.B.length < 1) errors.push(`${where}: needs at least one clue for B`);
checkClues(where, [...ch.clues.A, ...ch.clues.B, ...ch.clues.shared]);
checkLock(where, ch.lock);
}
if (game.finale.type === 'accusation') {
for (const q of game.finale.questions) {
if (!q.options.some((o) => o.id === q.answer)) {
errors.push(`finale question ${q.id}: answer "${q.answer}" is not one of the options`);
}
}
} else {
if (game.finale.clues.A.length < 1) errors.push('finale: needs at least one clue for A');
if (game.finale.clues.B.length < 1) errors.push('finale: needs at least one clue for B');
checkClues('finale', [...game.finale.clues.A, ...game.finale.clues.B]);
checkLock('finale', game.finale.lock);
}
return errors;
}
function validateDefuse(game: DefuseGame): string[] {
const errors: string[] = [];
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
const { fixtures, modules } = game;
fixtures.wires.forEach((f, i) => {
const got = solveWires(f.serial, f.wires);
if (got.index !== f.expect.index) errors.push(`wires fixture ${i + 1}: expected cut ${f.expect.index}, solver says ${got.index}`);
});
fixtures.button.forEach((f, i) => {
const got = solveButton(f);
if (!same(got, f.expect)) errors.push(`button fixture ${i + 1}: expected ${JSON.stringify(f.expect)}, solver says ${JSON.stringify(got)}`);
});
fixtures.keypad.forEach((f, i) => {
const got = solveKeypad(f.symbols, modules.keypad.columns);
if (!same(got, f.expect)) errors.push(`keypad fixture ${i + 1}: expected ${f.expect.join(',')}, solver says ${got?.join(',') ?? 'no unique column'}`);
});
if (!/\d/.test(game.device.serial.alphabet)) errors.push('serial alphabet has no digits');
if (modules.wires.count.min < 1 || modules.wires.count.max < modules.wires.count.min) errors.push('bad wire count range');
const { columns, symbols } = modules.keypad;
columns.forEach((col, i) => {
for (const s of col) if (!(s in symbols)) errors.push(`keypad column ${i + 1}: unknown symbol "${s}"`);
// Any 4 symbols must identify exactly one column.
for (let j = i + 1; j < columns.length; j++) {
if (col.filter((s) => columns[j].includes(s)).length > 3) errors.push(`keypad columns ${i + 1} and ${j + 1} share 4+ symbols`);
}
});
return errors;
}
function validateSync(game: SyncGame): string[] {
const errors: string[] = [];
const perRound = game.rules.questionsPerRound * (1 + game.rules.replaysPerRound);
for (const type of ['match', 'predict'] as const) {
const rounds = game.rounds.filter((r) => r.type === type).length;
if (rounds === 0) continue;
const bank = game[type];
if (bank.length < MIN_SYNC_QUESTIONS) errors.push(`${type} bank has ${bank.length} questions, needs at least ${MIN_SYNC_QUESTIONS}`);
if (bank.length < rounds * perRound) errors.push(`${type} bank has ${bank.length} questions, but ${rounds * perRound} are needed to never repeat`);
if (new Set(bank.map((q) => q.id)).size !== bank.length) errors.push(`${type} bank has duplicate question ids`);
}
for (const r of game.rounds) {
if (r.type === 'predict' && !r.subject) errors.push(`round ${r.id}: predict rounds need a subject`);
}
if (game.rules.pointsForKey > game.rules.questionsPerRound) errors.push('pointsForKey is more than questionsPerRound');
return errors;
}
function validateLabyrinth(game: LabyrinthGame): string[] {
const errors: string[] = [];
const { grid } = game;
if (new Set(grid.map((row) => row.length)).size !== 1) errors.push('grid rows are not all the same length');
const starts = findCells(grid, 'S');
const exits = findCells(grid, 'E');
const keys = findCells(grid, 'K');
if (starts.length !== 1) errors.push(`grid needs exactly one S, found ${starts.length}`);
if (exits.length !== 1) errors.push(`grid needs exactly one E, found ${exits.length}`);
if (keys.length !== 3) errors.push(`grid needs exactly 3 K, found ${keys.length}`);
if (game.lanterns.length !== keys.length) errors.push('lantern list does not match the K cells in the grid');
for (const l of game.lanterns) {
if (cellAt(grid, l.x, l.y) !== 'K') errors.push(`lantern "${l.name}" at (${l.x},${l.y}) is not on a K cell`);
}
for (const g of game.glyphs) {
if (cellAt(grid, g.x, g.y) === '#') errors.push(`glyph "${g.glyph}" at (${g.x},${g.y}) is inside a wall`);
}
if (starts.length === 1) {
const reach = safeReachable(grid);
for (const k of keys) {
if (!isReachable(reach, k)) errors.push(`lantern at (${k.x},${k.y}) is not reachable from S without a trap`);
}
for (const e of exits) {
if (!isReachable(reach, e)) errors.push(`exit at (${e.x},${e.y}) is not reachable from S without a trap`);
}
}
return errors;
}
+269
View File
@@ -0,0 +1,269 @@
import type { DefuseAction, DefuseStatus, Role } from '@two-keys/shared';
import type { DefuseGame } from '../content/schemas';
import { OK, fail, type ActionResult, type Ctx } from './types';
// ---------- Solver: implements the manual exactly ----------
export type WireSolution = { type: 'cut'; index: number };
export type ButtonSolution = { type: 'tap' } | { type: 'hold'; releaseDigit: number };
/** Returns the 1-based index of the wire to cut. */
export function solveWires(serial: string, wires: string[]): WireSolution {
const indexesOf = (color: string) => wires.flatMap((w, i) => (w === color ? [i + 1] : []));
const reds = indexesOf('red');
const yellows = indexesOf('yellow');
const lastDigit = Number(serial.match(/\d(?=\D*$)/)?.[0] ?? NaN);
if (reds.length === 2) return { type: 'cut', index: reds[1] };
if (lastDigit % 2 === 0 && yellows.length > 0) return { type: 'cut', index: yellows[0] };
if (!wires.includes('blue')) return { type: 'cut', index: wires.length };
if (wires.length === 5) return { type: 'cut', index: 4 };
return { type: 'cut', index: 1 };
}
export function solveButton(b: {
batteries: number;
label: string;
color: string;
strip: string;
}): ButtonSolution {
if (b.label === 'LOVE') return { type: 'tap' };
if (b.color === 'red' && b.label === 'HOLD') return { type: 'tap' };
if (b.batteries >= 2 && b.label === 'PRESS') return { type: 'tap' };
const releaseDigit = b.strip === 'blue' ? 4 : b.strip === 'yellow' ? 5 : 1;
return { type: 'hold', releaseDigit };
}
/** The press order, or null unless exactly one column contains every symbol. */
export function solveKeypad(symbols: string[], columns: string[][]): string[] | null {
const matches = columns.filter((col) => symbols.every((s) => col.includes(s)));
if (matches.length !== 1) return null;
return matches[0].filter((s) => symbols.includes(s));
}
// ---------- Generator ----------
export function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export interface DefuseDevice {
serial: string;
batteries: number;
wires?: { colors: string[]; solved: boolean };
button?: { label: string; color: string; strip: string; holding: boolean; solved: boolean };
keypad?: { symbols: string[]; pressed: string[]; solved: boolean };
}
export function generateDevice(game: DefuseGame, levelIndex: number, seed: number): DefuseDevice {
const rng = mulberry32(seed);
const int = (min: number, max: number) => min + Math.floor(rng() * (max - min + 1));
const pick = <T>(items: readonly T[]): T => items[Math.floor(rng() * items.length)];
const shuffle = <T>(items: T[]): T[] => {
const out = [...items];
for (let i = out.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[out[i], out[j]] = [out[j], out[i]];
}
return out;
};
const { serial: serialDef, batteries } = game.device;
const alphabet = [...serialDef.alphabet];
const digits = alphabet.filter((c) => /\d/.test(c));
let serial = '';
for (let i = 0; i < serialDef.length - 1; i++) serial += pick(alphabet);
serial += pick(digits); // last char is always a digit
const device: DefuseDevice = { serial, batteries: int(batteries.min, batteries.max) };
const mods = game.modules;
for (const id of game.levels[levelIndex].modules) {
if (id === 'wires') {
const count = int(mods.wires.count.min, mods.wires.count.max);
device.wires = { colors: Array.from({ length: count }, () => pick(mods.wires.colors)), solved: false };
} else if (id === 'button') {
device.button = {
label: pick(mods.button.labels),
color: pick(mods.button.colors),
strip: pick(mods.button.stripColors),
holding: false,
solved: false,
};
} else {
const column = pick(mods.keypad.columns);
device.keypad = { symbols: shuffle(shuffle(column).slice(0, 4)), pressed: [], solved: false };
}
}
return device;
}
/** A generated device must always be solvable by the manual. */
export function isSolvable(game: DefuseGame, device: DefuseDevice): boolean {
if (device.wires) {
const { index } = solveWires(device.serial, device.wires.colors);
if (index < 1 || index > device.wires.colors.length) return false;
}
if (device.keypad && !solveKeypad(device.keypad.symbols, game.modules.keypad.columns)) return false;
return true;
}
// ---------- Level state ----------
export interface DefuseState {
level: number;
status: DefuseStatus;
failReason: 'strikes' | 'time' | null;
seed: number;
device: DefuseDevice | null;
strikes: number;
/** `remaining` game-seconds as of `anchor`; ticks down at `speed` per real second. */
clock: { remaining: number; anchor: number; speed: number } | null;
}
const newSeed = () => Math.floor(Math.random() * 0xffffffff);
export function initDefuse(): DefuseState {
return { level: 0, status: 'ready', failReason: null, seed: newSeed(), device: null, strikes: 0, clock: null };
}
const state = (ctx: Ctx) => ctx.room.engine as DefuseState;
export function remainingAt(s: DefuseState, now: number): number {
if (!s.clock) return 0;
if (s.status !== 'active') return s.clock.remaining;
return s.clock.remaining - ((now - s.clock.anchor) / 1000) * s.clock.speed;
}
export function timerText(remaining: number): string {
const t = Math.max(0, Math.ceil(remaining));
return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, '0')}`;
}
function freezeClock(s: DefuseState, now: number) {
if (s.clock) s.clock = { ...s.clock, remaining: Math.max(0, remainingAt(s, now)), anchor: now };
}
function explode(ctx: Ctx, s: DefuseState, reason: 'strikes' | 'time') {
freezeClock(s, ctx.now);
s.status = 'exploded';
s.failReason = reason;
if (s.device?.button) s.device.button.holding = false;
}
function strike(game: DefuseGame, ctx: Ctx, s: DefuseState) {
const remaining = remainingAt(s, ctx.now);
s.strikes++;
ctx.room.wrongGuesses++;
s.clock = { remaining, anchor: ctx.now, speed: 1 + game.strikes.speedUpPerStrike * s.strikes };
if (s.strikes >= game.strikes.max) explode(ctx, s, 'strikes');
else ctx.toast('all', `Strike ${s.strikes} of ${game.strikes.max}! The clock speeds up.`);
}
function checkCleared(game: DefuseGame, ctx: Ctx, s: DefuseState) {
const d = s.device!;
const modules = [d.wires, d.button, d.keypad].filter((m) => m !== undefined);
if (!modules.every((m) => m.solved)) return;
freezeClock(s, ctx.now);
s.status = 'cleared';
ctx.addKey(game.levels[s.level].keyName);
if (s.level === game.levels.length - 1) {
ctx.finish(
true,
'**Device disarmed.** The ticking stops. Somewhere inside the box, a tiny speaker plays a wedding march.\n\nOne of you had the hands, one of you had the manual. Neither of you could have done it alone. 💣🔑',
);
}
}
/** Starts the level, retries after an explosion, or moves on after a clear. */
export function continueDefuse(game: DefuseGame, ctx: Ctx): ActionResult {
const s = state(ctx);
if (s.status === 'ready') {
s.device = generateDevice(game, s.level, s.seed);
s.strikes = 0;
s.clock = { remaining: game.levels[s.level].timeSeconds, anchor: ctx.now, speed: 1 };
s.status = 'active';
return OK;
}
if (s.status === 'active') return fail('busy', 'The clock is running!');
if (s.status === 'cleared') {
if (s.level >= game.levels.length - 1) return fail('done', 'Every level is cleared.');
s.level++;
}
// Retry (same level, no key lost) or next level: fresh seed, back to the briefing.
Object.assign(s, { status: 'ready', failReason: null, seed: newSeed(), device: null, strikes: 0, clock: null });
return OK;
}
export function defuseAction(
game: DefuseGame,
ctx: Ctx,
role: Role,
moduleId: string,
action: DefuseAction,
): ActionResult {
const s = state(ctx);
if (role !== 'A') return fail('wrong_role', 'Only the Technician can touch the device.');
if (s.status !== 'active' || !s.device) return fail('not_active', 'The device is not live.');
if (remainingAt(s, ctx.now) <= 0) {
explode(ctx, s, 'time');
return OK;
}
const d = s.device;
if (moduleId === 'wires' && d.wires && !d.wires.solved && action.type === 'cut') {
if (action.index === solveWires(d.serial, d.wires.colors).index) d.wires.solved = true;
else strike(game, ctx, s);
} else if (moduleId === 'button' && d.button && !d.button.solved) {
const b = d.button;
const solution = solveButton({ ...b, batteries: d.batteries });
if (action.type === 'tap' && !b.holding) {
if (solution.type === 'tap') b.solved = true;
else strike(game, ctx, s);
} else if (action.type === 'hold' && !b.holding) {
if (solution.type === 'hold') b.holding = true;
else strike(game, ctx, s);
} else if (action.type === 'release' && b.holding && solution.type === 'hold') {
// Checked against the server's own clock, with a second of grace for latency.
const remaining = remainingAt(s, ctx.now);
const digit = String(solution.releaseDigit);
const shown = [remaining - 1, remaining, remaining + 1].map(timerText);
b.holding = false;
if (shown.some((text) => text.includes(digit))) b.solved = true;
else strike(game, ctx, s);
} else {
return fail('bad_action', "That doesn't work on the button right now.");
}
} else if (moduleId === 'keypad' && d.keypad && !d.keypad.solved && action.type === 'press') {
const k = d.keypad;
if (!k.symbols.includes(action.symbol) || k.pressed.includes(action.symbol)) {
return fail('bad_action', 'That key is not available.');
}
const order = solveKeypad(k.symbols, game.modules.keypad.columns)!;
if (order[k.pressed.length] === action.symbol) {
k.pressed.push(action.symbol);
if (k.pressed.length === order.length) k.solved = true;
} else {
strike(game, ctx, s);
}
} else {
return fail('bad_action', "That module isn't on this device.");
}
if (state(ctx).status === 'active') checkCleared(game, ctx, s);
return OK;
}
/** Called on a timer; returns true if the room changed (the clock ran out). */
export function tickDefuse(ctx: Ctx): boolean {
const s = state(ctx);
if (!s || s.status !== 'active' || remainingAt(s, ctx.now) > 0) return false;
explode(ctx, s, 'time');
return true;
}
+46
View File
@@ -0,0 +1,46 @@
import type { Game } from '../content/schemas';
import { continueDefuse, initDefuse } from './defuse';
import { initLabyrinth } from './labyrinth';
import { continueChapter, initStory } from './story';
import { continueSync, initSync } from './sync';
import type { ActionResult, Ctx } from './types';
export function initEngine(game: Game): unknown {
switch (game.engine) {
case 'story':
return initStory();
case 'defuse':
return initDefuse();
case 'sync':
return initSync(game);
case 'labyrinth':
return initLabyrinth(game);
}
}
export function totalKeys(game: Game): number {
switch (game.engine) {
case 'story':
return game.chapters.length;
case 'defuse':
return game.levels.length;
case 'sync':
return game.rounds.length;
case 'labyrinth':
return game.lanterns.length;
}
}
/** `chapter:continue` means "move on" in every engine that has stages. */
export function continueGame(game: Game, ctx: Ctx): ActionResult {
switch (game.engine) {
case 'story':
return continueChapter(game, ctx);
case 'defuse':
return continueDefuse(game, ctx);
case 'sync':
return continueSync(game, ctx);
case 'labyrinth':
return { ok: false, code: 'no_stages', message: 'Nothing to continue.' };
}
}
+102
View File
@@ -0,0 +1,102 @@
import type { Dir, Role } from '@two-keys/shared';
import type { LabyrinthGame } from '../content/schemas';
import { OK, fail, type ActionResult, type Ctx } from './types';
export interface Point {
x: number;
y: number;
}
export const DELTAS: Record<Dir, Point> = {
n: { x: 0, y: -1 },
e: { x: 1, y: 0 },
s: { x: 0, y: 1 },
w: { x: -1, y: 0 },
};
export const cellAt = (grid: string[], x: number, y: number): string => grid[y]?.[x] ?? '#';
export const isWall = (grid: string[], x: number, y: number): boolean => cellAt(grid, x, y) === '#';
export function findCells(grid: string[], char: string): Point[] {
const found: Point[] = [];
grid.forEach((row, y) => [...row].forEach((c, x) => c === char && found.push({ x, y })));
return found;
}
const key = (p: Point) => `${p.x},${p.y}`;
/** Every cell reachable from S without ever stepping on a trap. */
export function safeReachable(grid: string[]): Set<string> {
const [start] = findCells(grid, 'S');
const seen = new Set<string>();
if (!start) return seen;
const queue: Point[] = [start];
seen.add(key(start));
while (queue.length > 0) {
const p = queue.shift()!;
for (const d of Object.values(DELTAS)) {
const next = { x: p.x + d.x, y: p.y + d.y };
const c = cellAt(grid, next.x, next.y);
if (c === '#' || c === 'T' || seen.has(key(next))) continue;
seen.add(key(next));
queue.push(next);
}
}
return seen;
}
export const isReachable = (reach: Set<string>, p: Point) => reach.has(key(p));
export interface LabyrinthState {
x: number;
y: number;
collected: boolean[];
moves: number;
falls: number;
message: string;
}
export function initLabyrinth(game: LabyrinthGame): LabyrinthState {
const [start] = findCells(game.grid, 'S');
return { ...start, collected: game.lanterns.map(() => false), moves: 0, falls: 0, message: '' };
}
export function moveExplorer(game: LabyrinthGame, ctx: Ctx, role: Role, dir: Dir): ActionResult {
const s = ctx.room.engine as LabyrinthState;
if (role !== 'B') return fail('wrong_role', 'Only the Explorer can move.');
const d = DELTAS[dir];
const next = { x: s.x + d.x, y: s.y + d.y };
if (isWall(game.grid, next.x, next.y)) return fail('wall', "Solid stone. You can't go that way.");
const flavour = game.explorerView.flavour;
s.moves++;
s.x = next.x;
s.y = next.y;
s.message = '';
const cell = cellAt(game.grid, next.x, next.y);
if (cell === 'T') {
const [start] = findCells(game.grid, 'S');
s.x = start.x;
s.y = start.y;
s.falls++;
s.message = flavour.trap;
ctx.addPenalty(game.scoring.trapPenaltySeconds);
ctx.toast('A', 'Your Explorer fell into a trap and is back at the entrance.');
} else if (cell === 'K') {
const i = game.lanterns.findIndex((l) => l.x === next.x && l.y === next.y);
if (i >= 0 && !s.collected[i]) {
s.collected[i] = true;
ctx.addKey(game.lanterns[i].name);
s.message = flavour.lantern.replace('{name}', game.lanterns[i].name);
}
} else if (cell === 'E') {
if (s.collected.every(Boolean)) {
s.message = flavour.exitOpen;
ctx.finish(true, game.successEnding);
} else {
s.message = flavour.exitLocked;
}
}
return OK;
}
+155
View File
@@ -0,0 +1,155 @@
import { matchesAnswer, type Role } from '@two-keys/shared';
import type { Lock, StoryGame } from '../content/schemas';
import { OK, fail, type ActionResult, type Ctx } from './types';
export const HINT_PENALTY_SECONDS = 120;
export const SUBMIT_COOLDOWN_MS = 2000;
export const NUDGE_AFTER_WRONG = 5;
export interface StoryState {
/** Index of the open chapter; equals chapters.length once the finale is open. */
chapter: number;
awaitingContinue: boolean;
solved: string[];
hints: Record<string, number>;
wrong: Record<string, number>;
lastSubmit: Record<string, number>;
finale: {
proposal: { answers: Record<string, string>; by: Role } | null;
agreed: boolean;
attempts: number;
};
}
export function initStory(): StoryState {
return {
chapter: 0,
awaitingContinue: false,
solved: [],
hints: {},
wrong: {},
lastSubmit: {},
finale: { proposal: null, agreed: false, attempts: 0 },
};
}
const state = (ctx: Ctx) => ctx.room.engine as StoryState;
const atFinale = (game: StoryGame, s: StoryState) => s.chapter >= game.chapters.length;
/** The one lock that can currently be worked on, if any. */
export function openLock(game: StoryGame, s: StoryState): { lock: Lock; finale: boolean } | null {
if (!atFinale(game, s)) {
return s.awaitingContinue ? null : { lock: game.chapters[s.chapter].lock, finale: false };
}
if (game.finale.type === 'escape' && !s.solved.includes(game.finale.lock.id)) {
return { lock: game.finale.lock, finale: true };
}
return null;
}
export function submitLock(game: StoryGame, ctx: Ctx, lockId: string, value: string): ActionResult {
const s = state(ctx);
const open = openLock(game, s);
if (!open || open.lock.id !== lockId) return fail('lock_closed', "That lock isn't open right now.");
const last = s.lastSubmit[lockId] ?? 0;
if (ctx.now - last < SUBMIT_COOLDOWN_MS) {
return fail('rate_limited', 'Easy! One guess every two seconds.');
}
s.lastSubmit[lockId] = ctx.now;
if (!matchesAnswer(value, open.lock.answers)) {
s.wrong[lockId] = (s.wrong[lockId] ?? 0) + 1;
ctx.room.wrongGuesses++;
return { ok: true, correct: false };
}
s.solved.push(lockId);
if (open.finale) {
ctx.finish(true, game.finale.successEnding);
} else {
ctx.addKey(open.lock.keyName ?? 'Key');
s.awaitingContinue = true;
}
return { ok: true, correct: true };
}
export function requestHint(game: StoryGame, ctx: Ctx, lockId: string): ActionResult {
const s = state(ctx);
const open = openLock(game, s);
if (!open || open.lock.id !== lockId) return fail('lock_closed', "That lock isn't open right now.");
const tier = s.hints[lockId] ?? 0;
if (tier >= open.lock.hints.length) return fail('no_more_hints', "That's every hint for this lock.");
s.hints[lockId] = tier + 1;
ctx.room.hintsUsed++;
ctx.addPenalty(HINT_PENALTY_SECONDS);
ctx.toast('all', `Hint ${tier + 1} revealed (+2:00)`);
return OK;
}
export function continueChapter(game: StoryGame, ctx: Ctx): ActionResult {
const s = state(ctx);
if (!s.awaitingContinue) return fail('not_ready', 'Solve the lock first.');
s.awaitingContinue = false;
s.chapter++;
return OK;
}
function accusation(game: StoryGame, s: StoryState) {
return atFinale(game, s) && game.finale.type === 'accusation' ? game.finale : null;
}
export function proposeAccusation(
game: StoryGame,
ctx: Ctx,
role: Role,
answers: Record<string, string>,
): ActionResult {
const s = state(ctx);
const finale = accusation(game, s);
if (!finale) return fail('no_finale', "The finale isn't open yet.");
const clean: Record<string, string> = {};
for (const q of finale.questions) {
const pick = answers[q.id];
if (!q.options.some((o) => o.id === pick)) return fail('incomplete', 'Answer every question first.');
clean[q.id] = pick;
}
s.finale.proposal = { answers: clean, by: role };
s.finale.agreed = false;
return OK;
}
export function agreeAccusation(game: StoryGame, ctx: Ctx, role: Role): ActionResult {
const s = state(ctx);
if (!accusation(game, s) || !s.finale.proposal) return fail('no_proposal', 'Nothing to agree to yet.');
if (s.finale.proposal.by === role) return fail('own_proposal', 'Your partner has to agree, not you.');
s.finale.agreed = true;
return OK;
}
export function submitAccusation(game: StoryGame, ctx: Ctx): ActionResult {
const s = state(ctx);
const finale = accusation(game, s);
if (!finale || !s.finale.proposal) return fail('no_proposal', 'Propose an accusation first.');
if (!s.finale.agreed) return fail('not_agreed', 'You both have to agree before submitting.');
const { answers } = s.finale.proposal;
const correct = finale.questions.every((q) => answers[q.id] === q.answer);
if (correct) {
ctx.finish(true, finale.successEnding);
return { ok: true, correct: true };
}
s.finale.attempts++;
s.finale.proposal = null;
s.finale.agreed = false;
ctx.room.wrongGuesses++;
const left = finale.maxAttempts - s.finale.attempts;
if (left <= 0) {
ctx.finish(false, finale.failEnding, finale.reveal);
} else {
// Deliberately doesn't say which part was wrong.
ctx.toast('all', `Not quite. ${left} attempt${left === 1 ? '' : 's'} left.`);
}
return { ok: true, correct: false };
}
+120
View File
@@ -0,0 +1,120 @@
import type { Role } from '@two-keys/shared';
import type { SyncGame, SyncQuestion } from '../content/schemas';
import { OK, fail, type ActionResult, type Ctx } from './types';
export interface SyncState {
round: number;
/** 0 on the first try, 1+ on a replay. */
attempt: number;
status: 'intro' | 'question' | 'reveal' | 'summary';
questions: SyncQuestion[];
q: number;
answers: Record<string, Partial<Record<Role, number>>>;
marks: boolean[];
earned: boolean;
/** Question ids already drawn this session, so nothing repeats. */
used: string[];
}
export function initSync(game: SyncGame): SyncState {
const s: SyncState = {
round: 0,
attempt: 0,
status: 'intro',
questions: [],
q: 0,
answers: {},
marks: [],
earned: false,
used: [],
};
deal(game, s);
return s;
}
const state = (ctx: Ctx) => ctx.room.engine as SyncState;
/** Draws a fresh hand of questions for the current round. */
function deal(game: SyncGame, s: SyncState, random: () => number = Math.random) {
const bank = game[game.rounds[s.round].type].filter((q) => !s.used.includes(q.id));
const hand: SyncQuestion[] = [];
while (hand.length < game.rules.questionsPerRound && bank.length > 0) {
hand.push(...bank.splice(Math.floor(random() * bank.length), 1));
}
s.used.push(...hand.map((q) => q.id));
s.questions = hand;
s.q = 0;
s.answers = {};
s.marks = [];
s.earned = false;
}
export function canReplay(game: SyncGame, s: SyncState): boolean {
return !s.earned && s.attempt < game.rules.replaysPerRound;
}
export function answerSync(
game: SyncGame,
ctx: Ctx,
role: Role,
questionId: string,
option: number,
): ActionResult {
const s = state(ctx);
const question = s.questions[s.q];
if (s.status !== 'question' || !question || question.id !== questionId) {
return fail('not_open', "That question isn't open.");
}
if (!Number.isInteger(option) || option < 0 || option >= question.options.length) {
return fail('bad_option', 'Pick one of the options.');
}
const answers = (s.answers[questionId] ??= {});
if (answers[role] !== undefined) return fail('answered', "You've already locked in an answer.");
answers[role] = option;
if (answers.A !== undefined && answers.B !== undefined) {
s.marks.push(answers.A === answers.B);
s.status = 'reveal';
}
return OK;
}
export function continueSync(game: SyncGame, ctx: Ctx): ActionResult {
const s = state(ctx);
const round = game.rounds[s.round];
if (s.status === 'intro') {
s.status = 'question';
} else if (s.status === 'question') {
return fail('waiting', 'Both of you need to answer first.');
} else if (s.status === 'reveal') {
if (s.q < s.questions.length - 1) {
s.q++;
s.status = 'question';
} else {
s.earned = s.marks.filter(Boolean).length >= game.rules.pointsForKey;
if (s.earned) ctx.addKey(round.keyName);
s.status = 'summary';
}
} else if (canReplay(game, s)) {
s.attempt++;
deal(game, s);
s.status = 'question';
} else if (s.round < game.rounds.length - 1) {
s.round++;
s.attempt = 0;
deal(game, s);
s.status = 'intro';
} else {
const keys = ctx.room.keys.length;
const total = game.rounds.length;
const ending =
keys === total
? `**${keys} out of ${total} keys.** You two are frighteningly in sync. Finishing each other's sentences is next. 💞🔑`
: keys > 0
? `**${keys} out of ${total} keys.** In sync where it counts, with a few surprises left to discover. That's the fun part. 💞`
: `**No keys this time.** Which just means you have a lot of excellent conversations ahead of you. Rematch? 😏`;
ctx.finish(keys > 0, ending);
}
return OK;
}
+42
View File
@@ -0,0 +1,42 @@
import type { Role } from '@two-keys/shared';
import type { Room } from '../rooms/store';
export interface Toast {
to: Role | 'all';
message: string;
}
/** What an engine may do to a room while handling an action. */
export interface Ctx {
room: Room;
now: number;
toasts: Toast[];
toast(to: Role | 'all', message: string): void;
addKey(name: string): void;
addPenalty(seconds: number): void;
finish(success: boolean, ending?: string | null, reveal?: string | null): void;
}
export function createCtx(room: Room, now = Date.now()): Ctx {
const toasts: Toast[] = [];
return {
room,
now,
toasts,
toast: (to, message) => void toasts.push({ to, message }),
addKey: (name) => void room.keys.push(name),
addPenalty: (seconds) => void (room.penaltySeconds += seconds),
finish(success, ending = null, reveal = null) {
room.phase = 'finished';
room.finishedAt = now;
room.result = { success, ending, reveal };
},
};
}
export type ActionResult =
| { ok: true; correct?: boolean }
| { ok: false; code: string; message: string };
export const OK: ActionResult = { ok: true };
export const fail = (code: string, message: string): ActionResult => ({ ok: false, code, message });
+12
View File
@@ -0,0 +1,12 @@
import { createApp } from './app';
const app = createApp();
const port = await app.listen(Number(process.env.PORT) || 3001);
console.log(`Two Keys server on http://localhost:${port} (${app.games.size} games, ${app.store.rooms.size} rooms restored)`);
// Snapshot rooms on the way out so a restart doesn't kill a game in progress.
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.on(signal, () => {
app.close().finally(() => process.exit(0));
});
}
+17
View File
@@ -0,0 +1,17 @@
import { randomInt } from 'node:crypto';
/** No 0/O/1/I, so codes survive being read out loud. */
export const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
export const CODE_LENGTH = 5;
export function makeCode(isTaken: (code: string) => boolean = () => false): string {
for (;;) {
let code = '';
for (let i = 0; i < CODE_LENGTH; i++) code += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
if (!isTaken(code)) return code;
}
}
export function cleanCode(input: string): string {
return input.trim().toUpperCase();
}
+77
View File
@@ -0,0 +1,77 @@
import { rankFor, type GameResult, type Role, type RoomState } from '@two-keys/shared';
import type { Game } from '../content/schemas';
import { engineView, gameMeta } from '../content/sanitize';
import { totalKeys } from '../engines/index';
import type { PlayerRec, Room } from './store';
export function computeResult(room: Room, game: Game): GameResult | null {
if (room.phase !== 'finished' || !room.result || room.startedAt === null || room.finishedAt === null) {
return null;
}
const elapsedSeconds = Math.round((room.finishedAt - room.startedAt) / 1000);
const finalSeconds = elapsedSeconds + room.penaltySeconds;
const keys = totalKeys(game);
return {
success: room.result.success,
elapsedSeconds,
penaltySeconds: room.penaltySeconds,
finalSeconds,
hintsUsed: room.hintsUsed,
wrongGuesses: room.wrongGuesses,
keysEarned: room.keys.length,
totalKeys: keys,
rank: rankFor({
success: room.result.success,
hintsUsed: room.hintsUsed,
finalSeconds,
estimatedMinutes: game.estimatedMinutes,
keysEarned: room.keys.length,
totalKeys: keys,
}),
ending: room.result.ending,
reveal: room.result.reveal,
};
}
/** The full, sanitized state for one player. This is the only thing sockets ever receive. */
export function buildState(
room: Room,
player: PlayerRec,
game: Game,
isOnline: (token: string) => boolean,
now = Date.now(),
): RoomState {
const roles: Role[] = player.seat === 'both' ? ['A', 'B'] : player.seat ? [player.seat] : [];
const views: RoomState['views'] = {};
if (room.phase !== 'lobby' && room.engine) {
for (const role of roles) views[role] = engineView(game, room, role, now);
}
const partner = room.players.find((p) => p !== player);
return {
code: room.code,
mode: room.mode,
phase: room.phase,
game: gameMeta(game),
you: { seat: player.seat, ready: player.ready },
partner: partner
? {
online: isOnline(partner.token),
seat: partner.seat === 'both' ? null : partner.seat,
ready: partner.ready,
viewing: partner.viewing,
}
: null,
notepad: room.notepad,
keys: [...room.keys],
timer: {
startedAt: room.startedAt,
finishedAt: room.finishedAt,
penaltySeconds: room.penaltySeconds,
serverNow: now,
},
stats: { hintsUsed: room.hintsUsed, wrongGuesses: room.wrongGuesses },
views,
result: computeResult(room, game),
};
}
+131
View File
@@ -0,0 +1,131 @@
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 } | 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();
}
}
+24
View File
@@ -0,0 +1,24 @@
import { loadAllFiles } from '../content/loader';
const files = loadAllFiles();
let failed = 0;
for (const { file, game, errors } of files) {
if (errors.length === 0 && game) {
console.log(`✔ ${file} (${game.engine})`);
} else {
failed++;
console.error(`✖ ${file}`);
for (const e of errors) console.error(` ${e}`);
}
}
if (files.length === 0) {
console.error('No game files found in content/games.');
process.exit(1);
}
if (failed > 0) {
console.error(`\n${failed} of ${files.length} game files failed validation.`);
process.exit(1);
}
console.log(`\nAll ${files.length} games are valid.`);
+282
View File
@@ -0,0 +1,282 @@
import { randomUUID } from 'node:crypto';
import type { Server, Socket } from 'socket.io';
import { z } from 'zod';
import { PING_EMOJIS, otherRole, type JoinAck, type Phase, type Role } from '@two-keys/shared';
import type { Game } from '../content/schemas';
import { defuseAction, tickDefuse } from '../engines/defuse';
import { continueGame, initEngine } from '../engines/index';
import { moveExplorer } from '../engines/labyrinth';
import { agreeAccusation, proposeAccusation, requestHint, submitAccusation, submitLock } from '../engines/story';
import { answerSync } from '../engines/sync';
import { createCtx, fail, type ActionResult, type Ctx } from '../engines/types';
import { cleanCode } from '../rooms/codes';
import { buildState } from '../rooms/state';
import type { PlayerRec, Room, RoomStore } from '../rooms/store';
const NOTEPAD_MAX = 5000;
const role = z.enum(['A', 'B']);
const asRole = { asRole: role.optional() };
const empty = z.object(asRole).default({});
const schemas = {
create: z.object({ gameId: z.string(), mode: z.enum(['duo', 'couch']).default('duo') }),
join: z.object({ code: z.string().min(1).max(12), playerToken: z.string().max(64).nullish() }),
pickRole: z.object({ role }),
lockSubmit: z.object({ lockId: z.string(), value: z.string().max(200), ...asRole }),
hint: z.object({ lockId: z.string(), ...asRole }),
propose: z.object({ answers: z.record(z.string()), ...asRole }),
defuse: z.object({
moduleId: z.enum(['wires', 'button', 'keypad']),
action: z.discriminatedUnion('type', [
z.object({ type: z.literal('cut'), index: z.number().int() }),
z.object({ type: z.literal('tap') }),
z.object({ type: z.literal('hold') }),
z.object({ type: z.literal('release') }),
z.object({ type: z.literal('press'), symbol: z.string() }),
]),
...asRole,
}),
sync: z.object({ questionId: z.string(), optionId: z.number().int(), ...asRole }),
move: z.object({ dir: z.enum(['n', 'e', 's', 'w']), ...asRole }),
notepad: z.object({ text: z.string() }),
ping: z.object({ emoji: z.enum(PING_EMOJIS), ...asRole }),
view: z.object({ label: z.string().max(80) }),
};
interface ActionArgs<T> {
socket: Socket;
room: Room;
player: PlayerRec;
game: Game;
data: T;
/** The role this action is taken as (couch players say which via `asRole`). */
role: Role;
ctx: Ctx;
}
export function registerHandlers(io: Server, games: Map<string, Game>, store: RoomStore): () => void {
const socketsIn = (code: string): Socket[] =>
[...(io.sockets.adapter.rooms.get(code) ?? [])]
.map((id) => io.sockets.sockets.get(id))
.filter((s): s is Socket => s !== undefined);
const playerOf = (room: Room, socket: Socket) => room.players.find((p) => p.token === socket.data.token);
function broadcast(room: Room, except?: Socket) {
const game = games.get(room.gameId);
if (!game) return;
const sockets = socketsIn(room.code);
const isOnline = (token: string) => sockets.some((s) => s.data.token === token);
const now = Date.now();
for (const s of sockets) {
const player = playerOf(room, s);
if (player && s !== except) s.emit('room:state', buildState(room, player, game, isOnline, now));
}
}
function flushToasts(room: Room, ctx: Ctx) {
for (const { to, message } of ctx.toasts) {
for (const s of socketsIn(room.code)) {
const seat = playerOf(room, s)?.seat;
if (to === 'all' || seat === 'both' || seat === to) s.emit('toast', { message });
}
}
}
const sendError = (socket: Socket, code: string, message: string) => socket.emit('error', { code, message });
function maybeStart(room: Room, game: Game) {
if (room.phase !== 'lobby') return;
const seated = room.mode === 'couch' ? room.players.length === 1 : room.players.length === 2;
if (!seated || !room.players.every((p) => p.ready && p.seat)) return;
room.phase = 'playing';
room.startedAt = Date.now();
room.engine = initEngine(game);
}
io.on('connection', (socket) => {
/** Registers a room-scoped event: validate, resolve room + role, run, then broadcast. */
function on<S extends z.ZodTypeAny>(
event: string,
schema: S,
phase: Phase | null,
handler: (args: ActionArgs<z.infer<S>>) => ActionResult | void,
opts: { echo?: boolean } = {},
) {
socket.on(event, (payload: unknown) => {
const parsed = schema.safeParse(payload ?? {});
if (!parsed.success) return sendError(socket, 'bad_request', 'That request made no sense.');
const room = store.get(socket.data.code);
const player = room && playerOf(room, socket);
const game = room && games.get(room.gameId);
if (!room || !player || !game) return sendError(socket, 'not_in_room', 'Join a room first.');
if (phase && room.phase !== phase) return sendError(socket, 'wrong_phase', "You can't do that right now.");
const data = parsed.data as z.infer<S> & { asRole?: Role };
const actingAs: Role = player.seat === 'both' ? (data.asRole ?? 'A') : (player.seat ?? 'A');
const ctx = createCtx(room);
const result = handler({ socket, room, player, game, data, role: actingAs, ctx });
if (result && !result.ok) sendError(socket, result.code, result.message);
room.lastActivity = ctx.now;
flushToasts(room, ctx);
broadcast(room, opts.echo === false ? socket : undefined);
});
}
socket.on('room:create', (payload: unknown, ack?: (res: JoinAck) => void) => {
const reply = (res: JoinAck) => typeof ack === 'function' && ack(res);
const parsed = schemas.create.safeParse(payload);
if (!parsed.success || !games.has(parsed.data.gameId)) {
return reply({ ok: false, code: 'unknown_game', message: "That game doesn't exist." });
}
const { room, player } = store.create(parsed.data.gameId, parsed.data.mode);
attach(room, player);
reply({ ok: true, code: room.code, playerToken: player.token });
broadcast(room);
});
socket.on('room:join', (payload: unknown, ack?: (res: JoinAck) => void) => {
const reply = (res: JoinAck) => typeof ack === 'function' && ack(res);
const parsed = schemas.join.safeParse(payload);
const room = parsed.success ? store.get(cleanCode(parsed.data.code)) : undefined;
if (!parsed.success || !room) {
return reply({ ok: false, code: 'not_found', message: "We couldn't find that room. Check the code?" });
}
// Reconnect: same token (or the same socket asking twice) gets the same seat back.
const token = parsed.data.playerToken ?? (socket.data.code === room.code ? socket.data.token : null);
let player = room.players.find((p) => p.token === token);
if (!player) {
const capacity = room.mode === 'couch' ? 1 : 2;
if (room.players.length >= capacity) {
return reply({ ok: false, code: 'room_full', message: 'This room already has two players.' });
}
const taken = room.players[0]?.seat;
player = {
token: randomUUID(),
seat: taken === 'A' || taken === 'B' ? otherRole(taken) : null,
ready: false,
viewing: null,
};
room.players.push(player);
}
attach(room, player);
room.lastActivity = Date.now();
reply({ ok: true, code: room.code, playerToken: player.token });
broadcast(room);
});
function attach(room: Room, player: PlayerRec) {
if (socket.data.code && socket.data.code !== room.code) socket.leave(socket.data.code);
socket.data.code = room.code;
socket.data.token = player.token;
socket.join(room.code);
}
// ----- lobby -----
on('room:pickRole', schemas.pickRole, 'lobby', ({ room, player, data }) => {
if (room.mode === 'couch') return;
// Picking a role hands your partner the other one.
for (const p of room.players) {
p.seat = p === player ? data.role : otherRole(data.role);
p.ready = false;
}
});
on('room:ready', empty, 'lobby', ({ room, player, game }) => {
if (!player.seat) return fail('no_role', 'Pick a role first.');
player.ready = !player.ready;
maybeStart(room, game);
});
// ----- story -----
on('lock:submit', schemas.lockSubmit, 'playing', ({ room, game, data, ctx }) => {
if (game.engine !== 'story') return fail('wrong_engine', 'This game has no locks.');
const result = submitLock(game, ctx, data.lockId, data.value);
if (result.ok) io.to(room.code).emit('lock:result', { lockId: data.lockId, correct: result.correct === true });
return result;
});
on('hint:request', schemas.hint, 'playing', ({ game, data, ctx }) =>
game.engine === 'story' ? requestHint(game, ctx, data.lockId) : fail('wrong_engine', 'No hints here.'),
);
on('chapter:continue', empty, 'playing', ({ game, ctx }) => continueGame(game, ctx));
on('finale:propose', schemas.propose, 'playing', ({ game, data, role, ctx }) =>
game.engine === 'story' ? proposeAccusation(game, ctx, role, data.answers) : fail('wrong_engine', 'No finale here.'),
);
on('finale:agree', empty, 'playing', ({ game, role, ctx }) =>
game.engine === 'story' ? agreeAccusation(game, ctx, role) : fail('wrong_engine', 'No finale here.'),
);
on('finale:submit', empty, 'playing', ({ game, ctx }) =>
game.engine === 'story' ? submitAccusation(game, ctx) : fail('wrong_engine', 'No finale here.'),
);
// ----- other engines -----
on('defuse:action', schemas.defuse, 'playing', ({ game, data, role, ctx }) =>
game.engine === 'defuse'
? defuseAction(game, ctx, role, data.moduleId, data.action)
: fail('wrong_engine', 'Nothing to defuse.'),
);
on('sync:answer', schemas.sync, 'playing', ({ game, data, role, ctx }) =>
game.engine === 'sync'
? answerSync(game, ctx, role, data.questionId, data.optionId)
: fail('wrong_engine', 'No questions here.'),
);
on('maze:move', schemas.move, 'playing', ({ game, data, role, ctx }) =>
game.engine === 'labyrinth' ? moveExplorer(game, ctx, role, data.dir) : fail('wrong_engine', 'No maze here.'),
);
// ----- presence -----
on(
'notepad:update',
schemas.notepad,
null,
({ room, data }) => {
room.notepad = data.text.slice(0, NOTEPAD_MAX); // last write wins
},
{ echo: false },
);
on('presence:view', schemas.view, null, ({ player, data }) => {
player.viewing = data.label;
}, { echo: false });
socket.on('ping', (payload: unknown) => {
const parsed = schemas.ping.safeParse(payload);
const room = store.get(socket.data.code);
const player = room && playerOf(room, socket);
if (!parsed.success || !room || !player) return;
const from: Role = player.seat === 'both' ? (parsed.data.asRole ?? 'A') : (player.seat ?? 'A');
socket.to(room.code).emit('ping', { from, emoji: parsed.data.emoji });
});
socket.on('disconnect', () => {
const room = store.get(socket.data.code);
if (room) broadcast(room);
});
});
// The defuse clock can run out with nobody touching anything.
const ticker = setInterval(() => {
for (const room of store.rooms.values()) {
const game = games.get(room.gameId);
if (room.phase !== 'playing' || game?.engine !== 'defuse') continue;
const ctx = createCtx(room);
if (tickDefuse(ctx)) {
flushToasts(room, ctx);
broadcast(room);
}
}
}, 500);
ticker.unref();
return () => clearInterval(ticker);
}
+77
View File
@@ -0,0 +1,77 @@
import { describe, expect, it } from 'vitest';
import { loadAllFiles } from '../src/content/loader';
import { gameSchema } from '../src/content/schemas';
import { validateGame } from '../src/content/validate';
import { CODE_ALPHABET, makeCode } from '../src/rooms/codes';
import { ROOM_TTL_MS, RoomStore } from '../src/rooms/store';
import { games, getGame, labyrinth, sync } from './helpers';
describe('content', () => {
it('loads all 8 games with no validation errors', () => {
const files = loadAllFiles();
expect(files.flatMap((f) => f.errors.map((e) => `${f.file}: ${e}`))).toEqual([]);
expect(files).toHaveLength(8);
expect([...games.values()].map((g) => g.engine).sort()).toEqual(
['defuse', 'labyrinth', 'story', 'story', 'story', 'story', 'story', 'sync'],
);
});
it('rejects a story chapter with no clue for one player', () => {
const game = structuredClone(getGame('clockmakers-attic', 'story'));
game.chapters[0].clues.B = [];
expect(validateGame(game).join('\n')).toMatch(/at least one clue for B/);
});
it('rejects a finale answer that is not an option, and a lock without 3 hints', () => {
const game = structuredClone(getGame('vineyard-hollow', 'story'));
if (game.finale.type !== 'accusation') throw new Error('expected accusation');
game.finale.questions[0].answer = 'nobody';
expect(validateGame(game).join('\n')).toMatch(/not one of the options/);
const raw = structuredClone(getGame('vineyard-hollow', 'story')) as any;
raw.chapters[0].lock.hints.pop();
expect(gameSchema.safeParse(raw).success).toBe(false);
});
it('rejects a labyrinth whose lantern is only reachable through a trap', () => {
const game = structuredClone(labyrinth());
// Wall off (1,6)... the only trap-free way to the Listening lantern is via (3,6)/(3,7).
game.grid[6] = '#######.#.#';
expect(validateGame(game).join('\n')).toMatch(/not reachable/);
});
it('rejects a labyrinth with ragged rows or the wrong number of lanterns', () => {
const ragged = structuredClone(labyrinth());
ragged.grid[1] = ragged.grid[1] + '#';
expect(validateGame(ragged).join('\n')).toMatch(/same length/);
const fewer = structuredClone(labyrinth());
fewer.grid[7] = '#...#.T.#.#';
expect(validateGame(fewer).join('\n')).toMatch(/exactly 3 K/);
});
it('rejects a sync bank with fewer than 15 questions', () => {
const game = structuredClone(sync());
game.match = game.match.slice(0, 14);
expect(validateGame(game).join('\n')).toMatch(/at least 15/);
});
});
describe('rooms', () => {
it('makes 5-char codes with no confusable characters', () => {
for (let i = 0; i < 200; i++) {
const code = makeCode();
expect(code).toMatch(/^[A-Z2-9]{5}$/);
expect(code).not.toMatch(/[0O1I]/);
}
expect(CODE_ALPHABET).not.toMatch(/[0O1I]/);
});
it('expires rooms after 24h idle', () => {
const store = new RoomStore(null);
const { room } = store.create('in-sync', 'duo', 0);
expect(store.sweep(ROOM_TTL_MS - 1)).toBe(0);
expect(store.sweep(ROOM_TTL_MS + 1)).toBe(1);
expect(store.get(room.code)).toBeUndefined();
});
});
+125
View File
@@ -0,0 +1,125 @@
// End-to-end over real sockets: two clients complete The Clockmaker's Attic.
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { io as connect, type Socket } from 'socket.io-client';
import type { JoinAck, RoomState, StoryView } from '@two-keys/shared';
import { createApp } from '../src/app';
const app = createApp({ dataFile: null });
let url = '';
const sockets: Socket[] = [];
beforeAll(async () => {
url = `http://localhost:${await app.listen(0)}`;
});
afterAll(async () => {
sockets.forEach((s) => s.close());
await app.close();
});
function client() {
const socket = connect(url, { transports: ['websocket'], forceNew: true });
sockets.push(socket);
const seen: RoomState[] = [];
let latest: RoomState | undefined;
let wake = () => {};
socket.on('room:state', (state: RoomState) => {
latest = state;
seen.push(state);
wake();
});
return {
socket,
seen,
get state() {
return latest!;
},
ack: (event: string, payload: object) =>
new Promise<JoinAck>((resolve) => socket.emit(event, payload, resolve)),
/** Resolves once a received state satisfies the predicate. */
async until(predicate: (s: RoomState) => boolean): Promise<RoomState> {
const deadline = Date.now() + 5000;
while (!(latest && predicate(latest))) {
if (Date.now() > deadline) throw new Error('timed out waiting for room state');
await new Promise<void>((resolve) => {
wake = resolve;
setTimeout(resolve, 100);
});
}
return latest;
},
};
}
describe('two players over sockets', () => {
it('create, join, pick roles, play Clockmaker\'s Attic to the end, and reconnect', async () => {
const game = app.games.get('clockmakers-attic')!;
if (game.engine !== 'story' || game.finale.type !== 'escape') throw new Error('unexpected game shape');
const a = client();
const b = client();
const created = await a.ack('room:create', { gameId: game.id });
if (!created.ok) throw new Error(created.message);
expect(created.code).toMatch(/^[A-Z2-9]{5}$/);
a.socket.emit('room:pickRole', { role: 'A' });
const joined = await b.ack('room:join', { code: created.code.toLowerCase() });
if (!joined.ok) throw new Error(joined.message);
await b.until((s) => s.you.seat === 'B'); // partner gets the other role
// A third player can't get in.
const c = client();
expect(await c.ack('room:join', { code: created.code })).toMatchObject({ ok: false, code: 'room_full' });
expect(await c.ack('room:join', { code: 'ZZZZZ' })).toMatchObject({ ok: false, code: 'not_found' });
a.socket.emit('room:ready');
b.socket.emit('room:ready');
await a.until((s) => s.phase === 'playing');
await b.until((s) => s.phase === 'playing');
for (const [i, chapter] of game.chapters.entries()) {
// Either player can submit; alternate.
const [me, partner] = i % 2 ? [b, a] : [a, b];
me.socket.emit('lock:submit', { lockId: chapter.lock.id, value: chapter.lock.answers[0] });
await partner.until((s) => s.keys.length === i + 1);
partner.socket.emit('chapter:continue');
await me.until((s) => (s.views[s.you.seat as 'A' | 'B'] as StoryView).currentChapter === i + 1);
}
// Refresh mid-game: a new socket with the same token gets the same seat and progress.
b.socket.close();
await a.until((s) => s.partner?.online === false);
const b2 = client();
expect(await b2.ack('room:join', { code: created.code, playerToken: joined.playerToken })).toMatchObject({ ok: true });
const restored = await b2.until((s) => s.phase === 'playing');
expect(restored.you.seat).toBe('B');
expect(restored.keys).toHaveLength(game.chapters.length);
expect((restored.views.B as StoryView).finale?.type).toBe('escape');
b2.socket.emit('lock:submit', { lockId: game.finale.lock.id, value: 'forever' });
const done = await a.until((s) => s.phase === 'finished');
expect(done.result).toMatchObject({ success: true, keysEarned: 3, totalKeys: 3, hintsUsed: 0 });
expect(done.result?.ending).toContain('FOREVER');
// Nothing A ever received contained B's clues, or any answers.
const everything = JSON.stringify(a.seen);
for (const chapter of game.chapters) {
for (const clue of chapter.clues.B) expect(everything).not.toContain(JSON.stringify(clue.title));
}
expect(everything).not.toContain('"answers"');
expect(everything).not.toContain(JSON.stringify(game.finale.clues.B[0].title));
});
it('couch mode: one device holds both roles and sees both views', async () => {
const solo = client();
const created = await solo.ack('room:create', { gameId: 'labyrinth-of-lanterns', mode: 'couch' });
if (!created.ok) throw new Error(created.message);
solo.socket.emit('room:ready');
const state = await solo.until((s) => s.phase === 'playing');
expect(state.you.seat).toBe('both');
expect(Object.keys(state.views).sort()).toEqual(['A', 'B']);
solo.socket.emit('maze:move', { dir: 'e', asRole: 'B' });
await solo.until((s) => (s.views.B as { moves: number }).moves === 1);
});
});
+257
View File
@@ -0,0 +1,257 @@
import { describe, expect, it } from 'vitest';
import type { Dir } from '@two-keys/shared';
import {
continueDefuse,
defuseAction,
generateDevice,
isSolvable,
remainingAt,
solveButton,
solveKeypad,
solveWires,
tickDefuse,
timerText,
type DefuseState,
} from '../src/engines/defuse';
import { DELTAS, cellAt, findCells, moveExplorer, type LabyrinthState } from '../src/engines/labyrinth';
import { answerSync, continueSync, type SyncState } from '../src/engines/sync';
import { clock, defuse, labyrinth, playingRoom, sync } from './helpers';
describe('defuse solver', () => {
const game = defuse();
it.each(game.fixtures.wires)('wires fixture %#', (f) => {
expect(solveWires(f.serial, f.wires)).toEqual(f.expect);
});
it.each(game.fixtures.button)('button fixture %#', (f) => {
expect(solveButton(f)).toEqual(f.expect);
});
it.each(game.fixtures.keypad)('keypad fixture %#', (f) => {
expect(solveKeypad(f.symbols, game.modules.keypad.columns)).toEqual(f.expect);
});
it('never generates a device the solver cannot solve', () => {
for (let seed = 1; seed <= 2000; seed++) {
const device = generateDevice(game, 2, seed);
expect(isSolvable(game, device), `seed ${seed}`).toBe(true);
expect(device.serial).toMatch(/^[A-Z0-9]{5}\d$/);
expect(device.wires!.colors.length).toBeGreaterThanOrEqual(3);
expect(device.wires!.colors.length).toBeLessThanOrEqual(5);
expect(device.keypad!.symbols).toHaveLength(4);
}
});
it('is deterministic per seed and only builds the modules of the level', () => {
expect(generateDevice(game, 2, 42)).toEqual(generateDevice(game, 2, 42));
const lvl1 = generateDevice(game, 0, 42);
expect(lvl1.wires).toBeDefined();
expect(lvl1.button).toBeUndefined();
expect(lvl1.keypad).toBeUndefined();
});
it('formats the timer like the device shows it', () => {
expect(timerText(180)).toBe('3:00');
expect(timerText(64.2)).toBe('1:05');
expect(timerText(-3)).toBe('0:00');
});
});
describe('defuse level flow', () => {
const game = defuse();
/** Solves whatever is on the device, using only the solver. */
function solveAll(room: ReturnType<typeof playingRoom>, t: ReturnType<typeof clock>) {
const s = room.engine as DefuseState;
const d = s.device!;
if (d.wires) defuseAction(game, t.ctx(100), 'A', 'wires', solveWires(d.serial, d.wires.colors));
if (d.keypad) {
for (const symbol of solveKeypad(d.keypad.symbols, game.modules.keypad.columns)!) {
defuseAction(game, t.ctx(100), 'A', 'keypad', { type: 'press', symbol });
}
}
if (d.button) {
const solution = solveButton({ ...d.button, batteries: d.batteries });
if (solution.type === 'tap') {
defuseAction(game, t.ctx(100), 'A', 'button', { type: 'tap' });
} else {
defuseAction(game, t.ctx(100), 'A', 'button', { type: 'hold' });
// Wait until the server's own timer shows the digit, then let go.
for (let i = 0; i < 400; i++) {
if (timerText(remainingAt(s, t.now)).includes(String(solution.releaseDigit))) break;
t.ctx(500);
}
defuseAction(game, t.ctx(0), 'A', 'button', { type: 'release' });
}
}
}
it('clears all three levels for a key each and finishes the game', () => {
const room = playingRoom(game);
const t = clock(room);
for (let level = 0; level < game.levels.length; level++) {
expect(continueDefuse(game, t.ctx()).ok).toBe(true); // start
solveAll(room, t);
const s = room.engine as DefuseState;
expect(s.strikes, `level ${level}`).toBe(0);
expect(s.status).toBe('cleared');
if (level < game.levels.length - 1) continueDefuse(game, t.ctx());
}
expect(room.keys).toEqual(game.levels.map((l) => l.keyName));
expect(room.phase).toBe('finished');
expect(room.result?.success).toBe(true);
});
it('strikes speed the clock up by 25% and three strikes blow the level without losing keys', () => {
const room = playingRoom(game);
room.keys.push('Earlier Key');
const t = clock(room);
continueDefuse(game, t.ctx());
const s = room.engine as DefuseState;
const right = solveWires(s.device!.serial, s.device!.wires!.colors).index;
const wrong = right === 1 ? 2 : 1;
defuseAction(game, t.ctx(), 'A', 'wires', { type: 'cut', index: wrong });
expect(s.strikes).toBe(1);
expect(s.clock!.speed).toBeCloseTo(1.25);
const before = remainingAt(s, t.now);
expect(before - remainingAt(s, t.now + 4000)).toBeCloseTo(5);
expect(defuseAction(game, t.ctx(), 'B', 'wires', { type: 'cut', index: right }).ok).toBe(false); // Expert can't cut
defuseAction(game, t.ctx(), 'A', 'wires', { type: 'cut', index: wrong });
defuseAction(game, t.ctx(), 'A', 'wires', { type: 'cut', index: wrong });
expect(s.status).toBe('exploded');
expect(s.failReason).toBe('strikes');
expect(room.keys).toEqual(['Earlier Key']);
const oldSeed = s.seed;
continueDefuse(game, t.ctx()); // retry → briefing with a new seed
expect(s).toMatchObject({ status: 'ready', level: 0, strikes: 0, device: null });
expect(s.seed).not.toBe(oldSeed);
});
it('explodes when the clock runs out', () => {
const room = playingRoom(game);
const t = clock(room);
continueDefuse(game, t.ctx());
expect(tickDefuse(t.ctx(10_000))).toBe(false);
expect(tickDefuse(t.ctx(game.levels[0].timeSeconds * 1000))).toBe(true);
expect(room.engine).toMatchObject({ status: 'exploded', failReason: 'time' });
});
});
describe('sync', () => {
const game = sync();
it('awards a key for 3+ matches, offers one replay otherwise, and never repeats a question', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as SyncState;
const seen: string[] = [];
const playRound = (matches: number) => {
for (let i = 0; i < game.rules.questionsPerRound; i++) {
const q = s.questions[s.q];
seen.push(q.id);
expect(answerSync(game, t.ctx(), 'A', q.id, 0).ok).toBe(true);
expect(answerSync(game, t.ctx(), 'A', q.id, 1).ok).toBe(false); // locked in
expect(continueSync(game, t.ctx()).ok).toBe(false); // partner still thinking
expect(answerSync(game, t.ctx(), 'B', q.id, i < matches ? 0 : 1).ok).toBe(true);
expect(s.status).toBe('reveal');
continueSync(game, t.ctx());
}
expect(s.status).toBe('summary');
};
continueSync(game, t.ctx()); // intro → first question
playRound(2); // fail
expect(s.earned).toBe(false);
continueSync(game, t.ctx()); // replay with fresh questions
expect(s).toMatchObject({ round: 0, attempt: 1, status: 'question' });
playRound(1); // fail again: no more replays
continueSync(game, t.ctx());
expect(s).toMatchObject({ round: 1, attempt: 0, status: 'intro' });
continueSync(game, t.ctx());
playRound(3);
expect(room.keys).toEqual([game.rounds[1].keyName]);
continueSync(game, t.ctx()); // earned → straight to round 3
expect(s.round).toBe(2);
continueSync(game, t.ctx());
playRound(5);
continueSync(game, t.ctx());
expect(room.phase).toBe('finished');
expect(room.keys).toHaveLength(2);
expect(new Set(seen).size).toBe(seen.length);
});
});
describe('labyrinth', () => {
const game = labyrinth();
const walk = (room: ReturnType<typeof playingRoom>, t: ReturnType<typeof clock>, path: string) =>
[...path].map((dir) => moveExplorer(game, t.ctx(), 'B', dir as Dir));
it('validates every move on the server', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as LabyrinthState;
expect(s).toMatchObject({ x: 1, y: 1 });
expect(moveExplorer(game, t.ctx(), 'B', 'n')).toMatchObject({ ok: false, code: 'wall' });
expect(moveExplorer(game, t.ctx(), 'A', 'e')).toMatchObject({ ok: false, code: 'wrong_role' });
expect(s).toMatchObject({ x: 1, y: 1, moves: 0 });
expect(moveExplorer(game, t.ctx(), 'B', 'e').ok).toBe(true);
expect(s).toMatchObject({ x: 2, y: 1, moves: 1 });
});
it('sends the Explorer back to the start on a trap, with a penalty, keys kept', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as LabyrinthState;
walk(room, t, 'ssss'); // (1,5)
walk(room, t, 'ee'); // (3,5)
const ctx = t.ctx();
moveExplorer(game, ctx, 'B', 'e'); // (4,5) is a trap
expect(s).toMatchObject({ x: 1, y: 1, falls: 1 });
expect(room.penaltySeconds).toBe(60);
expect(ctx.toasts).toEqual([{ to: 'A', message: expect.stringMatching(/fell into a trap/) }]);
});
it('can be completed: three lanterns, then the exit', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as LabyrinthState;
// Breadth-first route planner over safe cells, standing in for a good Navigator.
const goTo = (target: { x: number; y: number }) => {
const start = `${s.x},${s.y}`;
const prev = new Map<string, { from: string; dir: Dir }>();
const queue = [{ x: s.x, y: s.y }];
const seen = new Set([start]);
while (queue.length) {
const p = queue.shift()!;
for (const dir of Object.keys(DELTAS) as Dir[]) {
const n = { x: p.x + DELTAS[dir].x, y: p.y + DELTAS[dir].y };
const c = cellAt(game.grid, n.x, n.y);
if (c === '#' || c === 'T' || seen.has(`${n.x},${n.y}`)) continue;
seen.add(`${n.x},${n.y}`);
prev.set(`${n.x},${n.y}`, { from: `${p.x},${p.y}`, dir });
queue.push(n);
}
}
const path: Dir[] = [];
for (let at = `${target.x},${target.y}`; at !== start; at = prev.get(at)!.from) path.unshift(prev.get(at)!.dir);
for (const dir of path) expect(moveExplorer(game, t.ctx(), 'B', dir).ok).toBe(true);
};
const [exit] = findCells(game.grid, 'E');
goTo(exit);
expect(room.phase).toBe('playing'); // locked without lanterns
expect(s.message).toBe(game.explorerView.flavour.exitLocked);
for (const lantern of game.lanterns) goTo(lantern);
expect(room.keys).toEqual(expect.arrayContaining(game.lanterns.map((l) => l.name)));
goTo(exit);
expect(room.phase).toBe('finished');
expect(s.falls).toBe(0);
});
});
+40
View File
@@ -0,0 +1,40 @@
import { loadGames } from '../src/content/loader';
import type { DefuseGame, Game, LabyrinthGame, StoryGame, SyncGame } from '../src/content/schemas';
import { initEngine } from '../src/engines/index';
import { createCtx } from '../src/engines/types';
import { RoomStore, type Room } from '../src/rooms/store';
export const games = loadGames();
export function getGame<E extends Game['engine']>(id: string, engine: E): Extract<Game, { engine: E }> {
const game = games.get(id);
if (!game || game.engine !== engine) throw new Error(`no ${engine} game "${id}"`);
return game as Extract<Game, { engine: E }>;
}
export const storyGames = [...games.values()].filter((g): g is StoryGame => g.engine === 'story');
export const defuse = () => getGame('tick-tock-together', 'defuse') as DefuseGame;
export const sync = () => getGame('in-sync', 'sync') as SyncGame;
export const labyrinth = () => getGame('labyrinth-of-lanterns', 'labyrinth') as LabyrinthGame;
/** A room that is already in the `playing` phase for the given game. */
export function playingRoom(game: Game, startedAt = 1_000_000): Room {
const { room } = new RoomStore(null).create(game.id, 'duo', startedAt);
room.players[0].seat = 'A';
room.players.push({ token: 'b', seat: 'B', ready: true, viewing: null });
room.phase = 'playing';
room.startedAt = startedAt;
room.engine = initEngine(game);
return room;
}
/** A clock for tests: every call to `ctx()` is 3 seconds later, clear of the rate limit. */
export function clock(room: Room, start = 1_000_000) {
let now = start;
return {
ctx: (advanceMs = 3000) => createCtx(room, (now += advanceMs)),
get now() {
return now;
},
};
}
+194
View File
@@ -0,0 +1,194 @@
import { describe, expect, it } from 'vitest';
import type { Role } from '@two-keys/shared';
import type { Clue, Lock, StoryGame } from '../src/content/schemas';
import { continueDefuse, defuseAction, solveButton, type DefuseState } from '../src/engines/defuse';
import type { LabyrinthState } from '../src/engines/labyrinth';
import { continueChapter, requestHint, submitLock, type StoryState } from '../src/engines/story';
import { answerSync, continueSync, type SyncState } from '../src/engines/sync';
import { buildState } from '../src/rooms/state';
import type { Room } from '../src/rooms/store';
import { clock, defuse, games, labyrinth, playingRoom, storyGames, sync } from './helpers';
const FORBIDDEN_KEYS = ['answers', 'answer', 'solution', 'fixtures', 'expect', 'failEnding', 'successEnding'];
function payload(room: Room, role: Role, now = 2_000_000): string {
const player = room.players.find((p) => p.seat === role)!;
return JSON.stringify(buildState(room, player, games.get(room.gameId)!, () => true, now));
}
function keysOf(value: unknown, out = new Set<string>()): Set<string> {
if (value && typeof value === 'object') {
for (const [k, v] of Object.entries(value)) {
if (!Array.isArray(value)) out.add(k);
keysOf(v, out);
}
}
return out;
}
const locksOf = (game: StoryGame): Lock[] => [
...game.chapters.map((c) => c.lock),
...(game.finale.type === 'escape' ? [game.finale.lock] : []),
];
const cluesFor = (game: StoryGame, role: Role): Clue[] => [
...game.chapters.flatMap((c) => c.clues[role]),
...(game.finale.type === 'escape' ? game.finale.clues[role] : []),
];
describe.each(storyGames.map((g) => [g.id, g] as const))('sanitized story payloads: %s', (_id, game) => {
// Walk the whole game, checking both players' payloads at every step.
it('never contain answers, unrevealed hints, unearned text, or the other role\'s clues', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as StoryState;
const check = () => {
for (const role of ['A', 'B'] as const) {
const json = payload(room, role);
const other: Role = role === 'A' ? 'B' : 'A';
for (const key of keysOf(JSON.parse(json))) expect(FORBIDDEN_KEYS, `${role} got key "${key}"`).not.toContain(key);
// The other role's private clues never arrive, in any chapter.
const prefix = (c: Clue) => JSON.stringify(c.body).slice(1, 60);
const mine = cluesFor(game, role).map(prefix);
for (const clue of cluesFor(game, other)) {
expect(json, `${role} can see ${other}'s clue ${clue.id}`).not.toContain(JSON.stringify(clue.title));
// (Station Echo hands the same Morse chart to each player in turn.)
if (!mine.includes(prefix(clue))) expect(json).not.toContain(prefix(clue));
}
for (const lock of locksOf(game)) {
const revealed = s.hints[lock.id] ?? 0;
lock.hints.forEach((hint, i) => {
if (i >= revealed) expect(json, `${role} got unrevealed hint ${i + 1} of ${lock.id}`).not.toContain(JSON.stringify(hint));
});
if (!s.solved.includes(lock.id) && lock.successText) {
expect(json, `${role} got successText of unsolved ${lock.id}`).not.toContain(JSON.stringify(lock.successText));
}
// Lock objects carry no answer list at all. (Answer *words* may legitimately
// appear inside a player's own clues, so those can't be grepped for.)
const sent = (JSON.parse(json).views[role].chapters as { lock: object }[]).map((c) => c.lock);
for (const l of sent) expect(Object.keys(l)).not.toContain('answers');
}
// Signal patterns only ever ride on signal clues.
const view = JSON.parse(json).views[role];
const clues = [...view.chapters.flatMap((c: { clues: Clue[] }) => c.clues), ...(view.finale?.clues ?? [])];
for (const clue of clues) if (clue.type !== 'signal') expect(clue.signal).toBeUndefined();
if (room.phase !== 'finished') {
expect(json).not.toContain(JSON.stringify(game.finale.successEnding));
if (game.finale.type === 'accusation') expect(json).not.toContain(JSON.stringify(game.finale.reveal));
}
// Future chapters are not sent ahead of time.
expect(view.chapters.length).toBeLessThanOrEqual(Math.min(s.chapter, game.chapters.length - 1) + 1);
}
};
check();
for (const ch of game.chapters) {
requestHint(game, t.ctx(), ch.lock.id);
check();
submitLock(game, t.ctx(), ch.lock.id, 'wrong');
check();
submitLock(game, t.ctx(), ch.lock.id, ch.lock.answers[0]);
check();
continueChapter(game, t.ctx());
check();
}
});
it('sends each player only their own and shared clues', () => {
const room = playingRoom(game);
const view = JSON.parse(payload(room, 'A')).views.A;
const ids = view.chapters[0].clues.map((c: Clue) => c.id);
const ch = game.chapters[0];
expect(ids).toEqual([...ch.clues.A, ...ch.clues.shared].map((c) => c.id));
expect(JSON.parse(payload(room, 'A')).views.B).toBeUndefined();
});
});
describe('sanitized payloads: other engines', () => {
it('defuse: the Technician never gets the manual, the Expert never gets the device', () => {
const game = defuse();
const room = playingRoom(game);
const t = clock(room);
continueDefuse(game, t.ctx());
const s = room.engine as DefuseState;
const tech = payload(room, 'A', t.now);
const expert = payload(room, 'B', t.now);
expect(tech).not.toContain('Bomb Defusal Manual');
expect(keysOf(JSON.parse(tech))).not.toContain('manual');
expect(tech).toContain(s.device!.serial);
expect(expert).toContain('Bomb Defusal Manual');
expect(expert).not.toContain(s.device!.serial);
for (const key of ['device', 'serial', 'batteries', 'wires', 'modules', 'strip', 'seed']) {
expect(keysOf(JSON.parse(expert)), `expert got "${key}"`).not.toContain(key);
}
for (const json of [tech, expert]) {
for (const key of FORBIDDEN_KEYS) expect(keysOf(JSON.parse(json))).not.toContain(key);
expect(keysOf(JSON.parse(json))).not.toContain('seed');
}
});
it('defuse: the strip colour is only sent while the button is held', () => {
const game = defuse();
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as DefuseState;
s.level = 1;
// Find a seed whose button has to be held.
for (s.seed = 1; ; s.seed++) {
s.status = 'ready';
continueDefuse(game, t.ctx());
if (solveButton({ ...s.device!.button!, batteries: s.device!.batteries }).type === 'hold') break;
}
const button = () => JSON.parse(payload(room, 'A', t.now)).views.A.device.modules.find((m: { id: string }) => m.id === 'button');
expect(button().strip).toBeNull();
defuseAction(game, t.ctx(100), 'A', 'button', { type: 'hold' });
expect(button()).toMatchObject({ holding: true, strip: s.device!.button!.strip });
});
it('sync: the partner\'s answer is hidden until both have answered', () => {
const game = sync();
const room = playingRoom(game);
const t = clock(room);
continueSync(game, t.ctx());
const q = (room.engine as SyncState).questions[0];
answerSync(game, t.ctx(), 'A', q.id, 2);
const b = JSON.parse(payload(room, 'B')).views.B;
expect(b).toMatchObject({ myAnswer: null, partnerAnswered: true, reveal: null });
expect(JSON.parse(payload(room, 'A')).views.A).toMatchObject({ myAnswer: 2, partnerAnswered: false, reveal: null });
answerSync(game, t.ctx(), 'B', q.id, 1);
expect(JSON.parse(payload(room, 'B')).views.B.reveal).toEqual({ A: 2, B: 1, match: false });
});
it('labyrinth: the Explorer never gets the map, the Navigator never gets the position', () => {
const game = labyrinth();
const room = playingRoom(game);
const s = room.engine as LabyrinthState;
Object.assign(s, { x: 5, y: 3 }); // standing on the crescent moon
const explorer = JSON.parse(payload(room, 'B')).views.B;
for (const key of ['grid', 'glyphs', 'lanterns', 'x', 'y', 'traps']) {
expect(keysOf(explorer), `explorer got "${key}"`).not.toContain(key);
}
expect(explorer.glyphLabel).toMatch(/crescent moon/);
expect(explorer.open).toEqual({ n: true, e: false, s: false, w: true });
expect(JSON.stringify(explorer)).not.toContain('#');
const navigator = JSON.parse(payload(room, 'A')).views.A;
expect(navigator.grid).toEqual(game.grid);
// The only coordinates the Navigator has are the static map features.
const { glyphs, lanterns, grid, ...rest } = navigator;
expect(keysOf(rest)).not.toContain('x');
expect(keysOf(rest)).not.toContain('y');
expect(Object.keys(navigator)).not.toEqual(expect.arrayContaining(['open', 'glyphLabel', 'atExit', 'message']));
});
});
+127
View File
@@ -0,0 +1,127 @@
import { describe, expect, it } from 'vitest';
import type { Role } from '@two-keys/shared';
import type { StoryGame } from '../src/content/schemas';
import {
agreeAccusation,
continueChapter,
proposeAccusation,
requestHint,
submitAccusation,
submitLock,
type StoryState,
} from '../src/engines/story';
import { computeResult } from '../src/rooms/state';
import { clock, getGame, playingRoom, storyGames } from './helpers';
const correctAccusation = (game: StoryGame) => {
if (game.finale.type !== 'accusation') throw new Error('not an accusation finale');
return Object.fromEntries(game.finale.questions.map((q) => [q.id, q.answer]));
};
describe.each(storyGames.map((g) => [g.id, g] as const))('story: %s', (_id, game) => {
it('accepts every answer listed in the YAML, for every lock', () => {
const locks = [...game.chapters.map((c) => c.lock), ...(game.finale.type === 'escape' ? [game.finale.lock] : [])];
for (const lock of locks) {
for (const answer of lock.answers) {
// Fresh room fast-forwarded to this lock.
const room = playingRoom(game);
const s = room.engine as StoryState;
const index = game.chapters.findIndex((c) => c.lock.id === lock.id);
s.chapter = index === -1 ? game.chapters.length : index;
const t = clock(room);
expect(submitLock(game, t.ctx(), lock.id, answer), `${lock.id}: ${answer}`).toEqual({ ok: true, correct: true });
// Sloppy formatting is fine too.
const room2 = playingRoom(game);
(room2.engine as StoryState).chapter = s.chapter;
const sloppy = ` ${answer.toLowerCase().split('').join(' ')}! `;
expect(submitLock(game, clock(room2).ctx(), lock.id, sloppy).ok && true).toBe(true);
expect((room2.engine as StoryState).solved).toContain(lock.id);
}
}
});
it('plays start to finish and earns one key per chapter', () => {
const room = playingRoom(game);
const t = clock(room);
for (const ch of game.chapters) {
expect(submitLock(game, t.ctx(), ch.lock.id, 'definitely wrong')).toEqual({ ok: true, correct: false });
expect(submitLock(game, t.ctx(), ch.lock.id, ch.lock.answers[0])).toEqual({ ok: true, correct: true });
expect(continueChapter(game, t.ctx()).ok).toBe(true);
}
expect(room.keys).toEqual(game.chapters.map((c) => c.lock.keyName));
if (game.finale.type === 'escape') {
expect(submitLock(game, t.ctx(), game.finale.lock.id, game.finale.lock.answers[0])).toMatchObject({ correct: true });
} else {
expect(proposeAccusation(game, t.ctx(), 'A', correctAccusation(game)).ok).toBe(true);
expect(submitAccusation(game, t.ctx()).ok).toBe(false); // not agreed yet
expect(agreeAccusation(game, t.ctx(), 'A').ok).toBe(false); // can't agree with yourself
expect(agreeAccusation(game, t.ctx(), 'B').ok).toBe(true);
expect(submitAccusation(game, t.ctx())).toMatchObject({ correct: true });
}
expect(room.phase).toBe('finished');
expect(room.result).toMatchObject({ success: true, ending: game.finale.successEnding });
expect(room.wrongGuesses).toBe(game.chapters.length);
expect(computeResult(room, game)).toMatchObject({ success: true, keysEarned: game.chapters.length });
});
});
describe('story rules', () => {
const game = getGame('vineyard-hollow', 'story');
const lock = game.chapters[0].lock;
it('rate-limits to one submission per 2s per lock', () => {
const room = playingRoom(game);
const t = clock(room);
expect(submitLock(game, t.ctx(), lock.id, '0000')).toMatchObject({ ok: true, correct: false });
expect(submitLock(game, t.ctx(500), lock.id, lock.answers[0])).toMatchObject({ ok: false, code: 'rate_limited' });
expect(submitLock(game, t.ctx(2000), lock.id, lock.answers[0])).toMatchObject({ ok: true, correct: true });
});
it('only accepts the lock that is currently open', () => {
const room = playingRoom(game);
const t = clock(room);
const next = game.chapters[1].lock;
expect(submitLock(game, t.ctx(), next.id, next.answers[0])).toMatchObject({ ok: false, code: 'lock_closed' });
submitLock(game, t.ctx(), lock.id, lock.answers[0]);
// Solved but not continued: neither lock is open.
expect(submitLock(game, t.ctx(), next.id, next.answers[0])).toMatchObject({ ok: false });
expect(continueChapter(game, t.ctx()).ok).toBe(true);
expect(continueChapter(game, t.ctx()).ok).toBe(false);
});
it('reveals hints in order with a 2:00 penalty each', () => {
const room = playingRoom(game);
const t = clock(room);
for (let tier = 1; tier <= 3; tier++) {
expect(requestHint(game, t.ctx(), lock.id).ok).toBe(true);
expect((room.engine as StoryState).hints[lock.id]).toBe(tier);
}
expect(requestHint(game, t.ctx(), lock.id).ok).toBe(false);
expect(room.hintsUsed).toBe(3);
expect(room.penaltySeconds).toBe(360);
});
it('fails the case after maxAttempts wrong accusations without saying which part was wrong', () => {
if (game.finale.type !== 'accusation') throw new Error('expected accusation');
const room = playingRoom(game);
(room.engine as StoryState).chapter = game.chapters.length;
const t = clock(room);
const wrong = { ...correctAccusation(game), who: 'clara' };
for (let attempt = 1; attempt <= game.finale.maxAttempts; attempt++) {
const by: Role = attempt % 2 ? 'A' : 'B';
expect(proposeAccusation(game, t.ctx(), by, { who: 'clara' }).ok).toBe(false); // incomplete
proposeAccusation(game, t.ctx(), by, wrong);
agreeAccusation(game, t.ctx(), by === 'A' ? 'B' : 'A');
const ctx = t.ctx();
expect(submitAccusation(game, ctx)).toMatchObject({ ok: true, correct: false });
if (attempt < game.finale.maxAttempts) {
expect(ctx.toasts.map((x) => x.message).join()).toMatch(/Not quite\. 1 attempt left/);
expect(room.phase).toBe('playing');
}
}
expect(room.phase).toBe('finished');
expect(room.result).toEqual({ success: false, ending: game.finale.failEnding, reveal: game.finale.reveal });
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src", "test"]
}