Add ten new games (18 in total) and the engine features they need.

Story: Dead Air, The Masquerade at Montague House, The Kalahari Expedition,
The Alchemist's Vault, Submerged: Deep Lab Nereid, The Kestrel Bank Job.
Games can now set their own hint penalty and a hard time limit, shown as a
countdown; running out ends the game with the fail ending.

Defuse: Tick Tock: Overtime. Manuals are now rulesets, so each game has its
own solver. Adds indicator lights, per-level strike limits, and the
Passwords, Morse Light and Say It Back modules.

Sync: In Sync: Deep Cuts. Adds telepathy (typed word) and ranking rounds,
and a per-round bar for the key.

Labyrinth: The Drowned Catacombs and The Mirror Maze. Adds one-way gates, a
relative (no compass) Explorer, a mirrored Navigator map, and mazes with a
lantern count other than three. Validation now rejects a maze where a gate
can leave the Explorer stuck.

Difficulty runs from 1 to 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-13 23:34:11 +02:00
co-authored by Claude Opus 5.5
parent 62245ca67a
commit bbe44e84c4
38 changed files with 4201 additions and 197 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@two-keys/server",
"version": "1.0.1",
"version": "1.1.0",
"private": true,
"type": "module",
"scripts": {
+80 -19
View File
@@ -11,16 +11,27 @@ import type {
GameSummary,
LabyrinthView,
LockView,
MoveDir,
Role,
StoryView,
SyncView,
} from '@two-keys/shared';
import { otherRole } from '@two-keys/shared';
import { remainingAt, type DefuseState } from '../engines/defuse';
import { maxStrikes, remainingAt, toSignal, 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 {
DELTAS,
OPPOSITE,
REL_DIRS,
cellAt,
facingOf,
gateBlocks,
isWall,
toAbsolute,
type LabyrinthState,
} from '../engines/labyrinth';
import { NUDGE_AFTER_WRONG, hintPenalty, type StoryState } from '../engines/story';
import { canReplay, isMatch, pointsForKey, subjectOf, type SyncState } from '../engines/sync';
import type { Room } from '../rooms/store';
import type { Clue, DefuseGame, Game, LabyrinthGame, Lock, StoryGame, SyncGame } from './schemas';
@@ -36,6 +47,7 @@ export function gameSummary(game: Game): GameSummary {
theme: { ...game.theme },
roles: { A: { ...game.roles.A }, B: { ...game.roles.B } },
totalKeys: totalKeys(game),
timeLimitMinutes: game.engine === 'story' ? (game.rules.timeLimitMinutes ?? null) : null,
};
}
@@ -51,7 +63,7 @@ function clueView(clue: Clue, audience: ClueView['audience']): ClueView {
return view;
}
function lockView(lock: Lock, s: StoryState): LockView {
function lockView(game: StoryGame, lock: Lock, s: StoryState): LockView {
const solved = s.solved.includes(lock.id);
const wrongAttempts = s.wrong[lock.id] ?? 0;
return {
@@ -63,6 +75,7 @@ function lockView(lock: Lock, s: StoryState): LockView {
solved,
hints: lock.hints.slice(0, s.hints[lock.id] ?? 0),
hintsTotal: lock.hints.length,
hintPenaltySeconds: hintPenalty(game),
wrongAttempts,
nudge: !solved && wrongAttempts >= NUDGE_AFTER_WRONG,
successText: solved ? (lock.successText ?? null) : null,
@@ -81,7 +94,7 @@ export function storyView(game: StoryGame, s: StoryState, role: Role): StoryView
...ch.clues[role].map((c) => clueView(c, 'private')),
...ch.clues.shared.map((c) => clueView(c, 'shared')),
],
lock: lockView(ch.lock, s),
lock: lockView(game, ch.lock, s),
}));
let finale: StoryView['finale'] = null;
@@ -108,7 +121,7 @@ export function storyView(game: StoryGame, s: StoryState, role: Role): StoryView
type: 'escape',
prompt: f.prompt,
clues: f.clues[role].map((c) => clueView(c, 'private')),
lock: lockView(f.lock, s),
lock: lockView(game, f.lock, s),
};
}
@@ -125,6 +138,9 @@ export function storyView(game: StoryGame, s: StoryState, role: Role): StoryView
// ---------- defuse ----------
/** The Morse dial runs from 3.500 to 3.600 MHz. */
const MORSE_BAND = { minKhz: 3500, maxKhz: 3600 };
export function defuseView(game: DefuseGame, s: DefuseState, role: Role, now: number): DefuseView {
const level = game.levels[s.level];
const common = {
@@ -133,7 +149,7 @@ export function defuseView(game: DefuseGame, s: DefuseState, role: Role, now: nu
status: s.status,
failReason: s.failReason,
strikes: s.strikes,
maxStrikes: game.strikes.max,
maxStrikes: maxStrikes(game, s.level),
clock: s.clock
? { remaining: Math.max(0, remainingAt(s, now)), speed: s.clock.speed, running: s.status === 'active' }
: null,
@@ -170,14 +186,39 @@ export function defuseView(game: DefuseGame, s: DefuseState, role: Role, now: nu
})),
});
}
return { ...common, seat: 'technician', device: { serial: d.serial, batteries: d.batteries, modules } };
if (d.passwords) modules.push({ id: 'passwords', solved: d.passwords.solved, columns: [...d.passwords.columns] });
if (d.morse) {
// The light is the puzzle: the Technician gets the blink pattern, never the word.
modules.push({ id: 'morse', solved: d.morse.solved, signal: toSignal(d.morse.word), ...MORSE_BAND });
}
if (d.simon) {
modules.push({
id: 'simon',
solved: d.simon.solved,
colors: [...(game.modules.simon?.colors ?? [])],
flashes: d.simon.sequence.slice(0, d.simon.stage),
stage: d.simon.stage,
stages: d.simon.sequence.length,
entered: d.simon.progress,
});
}
return {
...common,
seat: 'technician',
device: {
serial: d.serial,
batteries: d.batteries,
indicators: (d.indicators ?? []).map((i) => ({ label: i.label, lit: i.lit })),
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 subject = subjectOf(round, s.q);
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;
@@ -196,20 +237,20 @@ export function syncView(game: SyncGame, s: SyncState, role: Role): SyncView {
isReplay: s.attempt > 0,
questionNumber: s.q + 1,
questionsPerRound: s.questions.length,
pointsForKey: game.rules.pointsForKey,
pointsForKey: pointsForKey(game, round),
points: s.marks.filter(Boolean).length,
question: q
? {
id: q.id,
text: q.q.replaceAll('{subject}', subject ? game.roles[subject].name : ''),
options: [...q.options],
options: [...(q.options ?? q.items ?? [])],
}
: 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,
reveal: both ? { A: answers.A!, B: answers.B!, match: isMatch(round.type, answers.A!, answers.B!) } : null,
marks: [...s.marks],
summary:
s.status === 'summary'
@@ -226,12 +267,22 @@ export function labyrinthView(game: LabyrinthGame, s: LabyrinthState, role: Role
// Navigator: the whole map, but never the Explorer's coordinates.
if (role === 'A') {
// A mirrored map is flipped left to right: rows reversed, x counted from the other side.
const mirror = game.navigatorView.mapTransform === 'mirror-x';
const width = game.grid[0].length;
const fx = (x: number) => (mirror ? width - 1 - x : x);
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] })),
grid: game.grid.map((row) => (mirror ? [...row].reverse().join('') : row)),
glyphs: game.glyphs.map((g) => ({ x: fx(g.x), y: g.y, label: g.label })),
lanterns: game.lanterns.map((l, i) => ({ x: fx(l.x), y: l.y, name: l.name, collected: s.collected[i] })),
oneWay: game.oneWay.map((g) => ({
x: fx(g.x),
y: g.y,
dir: mirror && (g.dir === 'e' || g.dir === 'w') ? OPPOSITE[g.dir] : g.dir,
})),
banner: game.navigatorView.banner ?? null,
keysCarried,
totalKeys: total,
moves: game.navigatorView.showMoveCount ? s.moves : null,
@@ -240,16 +291,26 @@ export function labyrinthView(game: LabyrinthGame, s: LabyrinthState, role: Role
}
// 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);
// With no compass, the ways out are forward/left/right/back and never N/E/S/W.
const relative = game.explorer.compass === 'relative';
const facing = facingOf(game, s);
const open: Partial<Record<MoveDir, boolean>> = {};
const gates: MoveDir[] = [];
for (const move of relative ? REL_DIRS : (Object.keys(DELTAS) as Dir[])) {
const dir = relative ? toAbsolute(facing, move as (typeof REL_DIRS)[number]) : (move as Dir);
const wall = isWall(game.grid, s.x + DELTAS[dir].x, s.y + DELTAS[dir].y);
const gate = !wall && gateBlocks(game.oneWay, s.x, s.y, dir);
open[move] = !wall && !gate;
if (gate) gates.push(move);
}
const glyph = game.glyphs.find((g) => g.x === s.x && g.y === s.y);
return {
engine: 'labyrinth',
seat: 'explorer',
glyphLabel: glyph?.label ?? null,
compass: game.explorer.compass,
open,
gates,
keysCarried,
totalKeys: total,
atExit: cellAt(game.grid, s.x, s.y) === 'E',
+79 -9
View File
@@ -1,5 +1,5 @@
import { z } from 'zod';
import { CLUE_TYPES } from '@two-keys/shared';
import { CLUE_TYPES, DEFUSE_MODULES, SYNC_ROUND_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() });
@@ -10,7 +10,7 @@ const header = {
title: z.string().min(1),
tagline: z.string().min(1),
estimatedMinutes: z.number().positive(),
difficulty: z.number().int().min(1).max(3),
difficulty: z.number().int().min(1).max(5),
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 }),
@@ -81,12 +81,22 @@ const finaleSchema = z.discriminatedUnion('type', [
clues: z.object({ A: z.array(clueSchema).default([]), B: z.array(clueSchema).default([]) }),
lock: lockSchema,
successEnding: z.string().min(1),
/** Shown if a time limit runs out. */
failEnding: z.string().min(1).optional(),
}),
]);
const storySchema = z.object({
...header,
engine: z.literal('story'),
rules: z
.object({
hintPenaltySeconds: z.number().int().nonnegative().optional(),
/** Hard limit on the clock (elapsed + penalties). Running out ends the game. */
timeLimitMinutes: z.number().positive().optional(),
timeLimitLabel: z.string().min(1).optional(),
})
.default({}),
suspects: z
.array(z.object({ id: z.string(), name: z.string(), role: z.string(), description: z.string() }))
.optional(),
@@ -97,14 +107,18 @@ const storySchema = z.object({
// ---------- defuse ----------
const range = z.object({ min: z.number().int().nonnegative(), max: z.number().int().nonnegative() });
const moduleId = z.enum(['wires', 'button', 'keypad']);
const moduleId = z.enum(DEFUSE_MODULES);
const indicators = z.object({ lit: z.array(z.string()), unlit: z.array(z.string()) }).optional();
const defuseSchema = z.object({
...header,
engine: z.literal('defuse'),
/** Which manual the solver implements. Each manual's rules live in engines/defuse.ts. */
ruleset: z.enum(['classic', 'overtime']).default('classic'),
device: z.object({
serial: z.object({ length: z.number().int().min(2), alphabet: z.string().min(2) }),
batteries: range,
indicators: z.object({ labels: z.array(z.string().min(1)).min(1), count: range }).optional(),
}),
levels: z
.array(
@@ -113,6 +127,7 @@ const defuseSchema = z.object({
title: z.string().min(1),
timeSeconds: z.number().int().positive(),
modules: z.array(moduleId).min(1),
strikesOverride: z.number().int().positive().optional(),
keyName: z.string().min(1),
}),
)
@@ -129,6 +144,15 @@ const defuseSchema = z.object({
symbols: z.record(z.string()),
columns: z.array(z.array(z.string()).min(4)).min(1),
}),
passwords: z
.object({
columnsCount: z.number().int().positive(),
lettersPerColumn: z.number().int().min(2).max(26),
words: z.array(z.string().regex(/^[A-Z]+$/)).min(2),
})
.optional(),
morse: z.object({ words: z.record(z.string().regex(/^\d\.\d{3}$/)) }).optional(),
simon: z.object({ colors: z.array(z.string()).min(2), stages: range }).optional(),
}),
manual: z.string().min(1),
fixtures: z.object({
@@ -136,6 +160,7 @@ const defuseSchema = z.object({
z.object({
serial: z.string(),
batteries: z.number().int(),
indicators,
wires: z.array(z.string()),
expect: z.object({ type: z.literal('cut'), index: z.number().int() }),
}),
@@ -143,6 +168,7 @@ const defuseSchema = z.object({
button: z.array(
z.object({
batteries: z.number().int(),
indicators,
label: z.string(),
color: z.string(),
strip: z.string(),
@@ -153,6 +179,20 @@ const defuseSchema = z.object({
}),
),
keypad: z.array(z.object({ symbols: z.array(z.string()), expect: z.array(z.string()) })),
passwords: z.array(z.object({ columns: z.array(z.string()), expect: z.string() })).default([]),
morse: z
.array(z.object({ signal: z.string(), expect: z.object({ word: z.string(), frequency: z.string() }) }))
.default([]),
simon: z
.array(
z.object({
serial: z.string(),
strikes: z.number().int(),
flashes: z.array(z.string()),
expect: z.array(z.string()),
}),
)
.default([]),
}),
});
@@ -163,13 +203,20 @@ const questionSchema = z.object({
q: z.string().min(1),
options: z.array(z.coerce.string()).min(2),
});
const telepathySchema = z.object({ id: z.string().min(1), q: z.string().min(1) });
const rankSchema = z.object({
id: z.string().min(1),
q: z.string().min(1),
items: z.array(z.coerce.string()).min(3),
});
const syncSchema = z.object({
...header,
engine: z.literal('sync'),
rules: z.object({
questionsPerRound: z.number().int().positive(),
pointsForKey: z.number().int().positive(),
/** Default for rounds that don't set their own. */
pointsForKey: z.number().int().positive().default(3),
replaysPerRound: z.number().int().nonnegative(),
}),
rounds: z
@@ -177,19 +224,26 @@ const syncSchema = z.object({
z.object({
id: z.string().min(1),
title: z.string().min(1),
type: z.enum(['match', 'predict']),
type: z.enum(SYNC_ROUND_TYPES),
subject: z.enum(['A', 'B']).optional(),
/** rank rounds: who does the ranking on each question, cycled. */
subjectPattern: z.array(z.enum(['A', 'B'])).min(1).optional(),
pointsForKey: z.number().int().positive().optional(),
blurb: z.string(),
keyName: z.string().min(1),
}),
)
.min(1),
match: z.array(questionSchema),
predict: z.array(questionSchema),
match: z.array(questionSchema).default([]),
predict: z.array(questionSchema).default([]),
telepathy: z.array(telepathySchema).default([]),
rank: z.array(rankSchema).default([]),
});
// ---------- labyrinth ----------
const dir = z.enum(['n', 'e', 's', 'w']);
const labyrinthSchema = z.object({
...header,
engine: z.literal('labyrinth'),
@@ -198,6 +252,16 @@ const labyrinthSchema = z.object({
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) })),
lanternsRequired: z.number().int().positive().default(3),
/** One-way gates: you may step from (x, y) in `dir`, never back the other way. */
oneWay: z.array(z.object({ x: z.number().int(), y: z.number().int(), dir })).default([]),
explorer: z
.object({
/** `relative` swaps N/E/S/W for forward/left/right/back from the way the Explorer faces. */
compass: z.enum(['absolute', 'relative']).default('absolute'),
startFacing: dir.default('n'),
})
.default({}),
explorerView: z.object({
flavour: z.object({
blank: z.string(),
@@ -205,9 +269,15 @@ const labyrinthSchema = z.object({
lantern: z.string(),
exitLocked: z.string(),
exitOpen: z.string(),
gate: z.string().optional(),
}),
}),
navigatorView: z.object({ showMoveCount: z.boolean().default(true) }),
navigatorView: z.object({
showMoveCount: z.boolean().default(true),
/** `mirror-x` serves the map flipped left to right. */
mapTransform: z.enum(['none', 'mirror-x']).default('none'),
banner: z.string().optional(),
}),
scoring: z.object({ trapPenaltySeconds: z.number().nonnegative(), parMoves: z.number().int().positive() }),
successEnding: z.string().min(1),
});
@@ -226,4 +296,4 @@ 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>;
export type SyncQuestion = { id: string; q: string; options?: string[]; items?: string[] };
+71 -13
View File
@@ -1,6 +1,15 @@
import { normalizeAnswer } from '@two-keys/shared';
import { solveButton, solveKeypad, solveWires } from '../engines/defuse';
import { cellAt, findCells, isReachable, safeReachable } from '../engines/labyrinth';
import { SYNC_ROUND_TYPES, normalizeAnswer } from '@two-keys/shared';
import {
buttonSolution,
solveKeypad,
solveMorse,
solvePassword,
solveSimon,
toSignal,
wireSolution,
} from '../engines/defuse';
import { DELTAS, analyseMaze, cellAt, findCells, isReachable, safeReachable } from '../engines/labyrinth';
import { groupOf, pointsForKey } from '../engines/sync';
import type { Clue, DefuseGame, Game, LabyrinthGame, Lock, StoryGame, SyncGame } from './schemas';
export const MIN_SYNC_QUESTIONS = 15;
@@ -75,14 +84,14 @@ function validateStory(game: StoryGame): string[] {
function validateDefuse(game: DefuseGame): string[] {
const errors: string[] = [];
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
const { fixtures, modules } = game;
const { fixtures, modules, ruleset } = game;
fixtures.wires.forEach((f, i) => {
const got = solveWires(f.serial, f.wires);
const got = wireSolution(ruleset, f, 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);
const got = buttonSolution(ruleset, { serial: '', ...f }, 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) => {
@@ -90,6 +99,38 @@ function validateDefuse(game: DefuseGame): string[] {
if (!same(got, f.expect)) errors.push(`keypad fixture ${i + 1}: expected ${f.expect.join(',')}, solver says ${got?.join(',') ?? 'no unique column'}`);
});
fixtures.passwords.forEach((f, i) => {
const got = solvePassword(f.columns, modules.passwords?.words ?? []);
if (got !== f.expect) errors.push(`passwords fixture ${i + 1}: expected ${f.expect}, solver says ${got ?? 'no unique word'}`);
});
fixtures.morse.forEach((f, i) => {
const got = solveMorse(f.signal, modules.morse?.words ?? {});
if (!same(got, f.expect)) errors.push(`morse fixture ${i + 1}: expected ${JSON.stringify(f.expect)}, solver says ${JSON.stringify(got)}`);
});
fixtures.simon.forEach((f, i) => {
const got = solveSimon(f.serial, f.strikes, f.flashes);
if (!same(got, f.expect)) errors.push(`simon fixture ${i + 1}: expected ${f.expect.join(',')}, solver says ${got.join(',')}`);
});
for (const level of game.levels) {
for (const id of level.modules) {
if (!(id in modules)) errors.push(`level ${level.id}: module "${id}" is not defined under modules`);
}
}
if (modules.passwords) {
const { words, columnsCount } = modules.passwords;
for (const w of words) if (w.length !== columnsCount) errors.push(`password "${w}" is not ${columnsCount} letters`);
if (new Set(words).size !== words.length) errors.push('password list has duplicates');
}
if (modules.morse) {
const entries = Object.entries(modules.morse.words);
for (const [word] of entries) {
if (!solveMorse(toSignal(word), modules.morse.words)) errors.push(`morse word "${word}" can't be sent in Morse`);
}
if (new Set(entries.map(([, f]) => f)).size !== entries.length) errors.push('two morse words share a frequency');
}
if (modules.simon && modules.simon.stages.min < 1) errors.push('simon needs at least one stage');
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;
@@ -106,18 +147,22 @@ function validateDefuse(game: DefuseGame): string[] {
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;
for (const type of SYNC_ROUND_TYPES) {
const rounds = game.rounds.filter((r) => r.type === type);
if (rounds.length === 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`);
// A question never repeats, except that a spotlight question may be asked once about each partner.
const groups = new Map<string, number>();
for (const r of rounds) groups.set(groupOf(r), (groups.get(groupOf(r)) ?? 0) + 1);
const needed = Math.max(...groups.values()) * perRound;
if (bank.length < needed) errors.push(`${type} bank has ${bank.length} questions, but ${needed} 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 (pointsForKey(game, r) > game.rules.questionsPerRound) errors.push(`round ${r.id}: pointsForKey is more than questionsPerRound`);
}
if (game.rules.pointsForKey > game.rules.questionsPerRound) errors.push('pointsForKey is more than questionsPerRound');
return errors;
}
@@ -131,7 +176,8 @@ function validateLabyrinth(game: LabyrinthGame): string[] {
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}`);
const required = game.lanternsRequired;
if (keys.length !== required) errors.push(`grid needs exactly ${required} 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) {
@@ -141,14 +187,26 @@ function validateLabyrinth(game: LabyrinthGame): string[] {
if (cellAt(grid, g.x, g.y) === '#') errors.push(`glyph "${g.glyph}" at (${g.x},${g.y}) is inside a wall`);
}
for (const g of game.oneWay) {
const through = DELTAS[g.dir];
if (cellAt(grid, g.x, g.y) === '#' || cellAt(grid, g.x + through.x, g.y + through.y) === '#') {
errors.push(`one-way gate at (${g.x},${g.y}) ${g.dir} opens into a wall`);
}
}
if (starts.length === 1) {
const reach = safeReachable(grid);
const reach = safeReachable(grid, game.oneWay);
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`);
}
if (errors.length === 0) {
const { winnable, stuck } = analyseMaze(grid, game.oneWay, game.lanterns);
if (!winnable) errors.push('no trap-free route collects every lantern and then reaches the exit');
for (const p of stuck) errors.push(`the Explorer can get stuck for good at (${p.x},${p.y})`);
}
}
return errors;
}
+230 -14
View File
@@ -2,12 +2,26 @@ 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 ----------
// ---------- Solver: implements each manual exactly ----------
// `classic` is the Tick Tock Together manual, `overtime` the Tick Tock: Overtime one.
export type WireSolution = { type: 'cut'; index: number };
export type ButtonSolution = { type: 'tap' } | { type: 'hold'; releaseDigit: number };
export interface Indicators {
lit: string[];
unlit: string[];
}
/** What the Technician reads out before anything else. */
export interface Edgework {
serial: string;
batteries: number;
indicators?: Indicators;
}
/** Returns the 1-based index of the wire to cut. */
const hasVowel = (serial: string) => /[AEIOU]/.test(serial);
const isLit = (e: { indicators?: Indicators }, label: string) => e.indicators?.lit.includes(label) ?? false;
/** Classic manual. 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');
@@ -21,6 +35,43 @@ export function solveWires(serial: string, wires: string[]): WireSolution {
return { type: 'cut', index: 1 };
}
/** Overtime manual: one section per wire count, first rule that applies. */
export function solveWiresOvertime(e: Edgework, wires: string[]): WireSolution {
const indexesOf = (color: string) => wires.flatMap((w, i) => (w === color ? [i + 1] : []));
const cut = (index: number): WireSolution => ({ type: 'cut', index });
const n = wires.length;
if (n === 3) {
if (new Set(wires).size === 3) return cut(2);
if (indexesOf('blue').length >= 2) return cut(indexesOf('blue')[0]);
if (hasVowel(e.serial)) return cut(3);
return cut(1);
}
if (n === 4) {
const greens = indexesOf('green');
const whites = indexesOf('white');
if (greens.length === 1 && e.batteries >= 2) return cut(greens[0]);
if (wires[0] === wires[3]) return cut(3);
if (whites.length === 0) return cut(2);
return cut(whites[whites.length - 1]);
}
if (n === 5) {
const blacks = indexesOf('black');
const yellows = indexesOf('yellow');
const lastDigit = Number(e.serial.match(/\d(?=\D*$)/)?.[0] ?? NaN);
if (blacks.length > indexesOf('red').length) return cut(blacks[0]);
if (lastDigit % 2 === 1) return cut(4);
if (yellows.length === 1) return cut(yellows[0] === 5 ? 1 : yellows[0] + 1);
return cut(2);
}
const reds = indexesOf('red');
if (isLit(e, 'LUV')) return cut(6);
if (reds.length === 3) return cut(reds[2]);
if (!wires.includes('yellow')) return cut(3);
return cut(5);
}
/** Classic manual. */
export function solveButton(b: {
batteries: number;
label: string;
@@ -34,6 +85,85 @@ export function solveButton(b: {
return { type: 'hold', releaseDigit };
}
export function solveButtonOvertime(b: {
batteries: number;
indicators?: Indicators;
label: string;
color: string;
strip: string;
}): ButtonSolution {
const releaseDigit = { blue: 4, white: 1, yellow: 5, red: 3 }[b.strip] ?? 1;
const hold: ButtonSolution = { type: 'hold', releaseDigit };
if (b.color === 'blue' && b.label === 'ABORT') return hold;
if (b.batteries > 1 && b.label === 'DETONATE') return { type: 'tap' };
if (b.color === 'white' && isLit(b, 'BAE')) return hold;
if (b.batteries > 2 && isLit(b, 'HUG')) return { type: 'tap' };
if (b.color === 'yellow') return hold;
if (b.color === 'red' && b.label === 'HOLD') return { type: 'tap' };
return hold;
}
type Ruleset = DefuseGame['ruleset'];
export function wireSolution(ruleset: Ruleset, e: Edgework, wires: string[]): WireSolution {
return ruleset === 'overtime' ? solveWiresOvertime(e, wires) : solveWires(e.serial, wires);
}
export function buttonSolution(
ruleset: Ruleset,
e: Edgework,
button: { label: string; color: string; strip: string },
): ButtonSolution {
const b = { ...button, batteries: e.batteries, indicators: e.indicators };
return ruleset === 'overtime' ? solveButtonOvertime(b) : solveButton(b);
}
/** The one listed word the letter columns can spell, or null unless there is exactly one. */
export function solvePassword(columns: string[], words: string[]): string | null {
const matches = words.filter(
(word) => word.length === columns.length && [...word].every((letter, i) => columns[i].includes(letter)),
);
return matches.length === 1 ? matches[0] : null;
}
const MORSE: Record<string, string> = {
A: '.-', B: '-...', C: '-.-.', D: '-..', E: '.', F: '..-.', G: '--.', H: '....', I: '..', J: '.---',
K: '-.-', L: '.-..', M: '--', N: '-.', O: '---', P: '.--.', Q: '--.-', R: '.-.', S: '...', T: '-',
U: '..-', V: '...-', W: '.--', X: '-..-', Y: '-.--', Z: '--..',
};
/** "HUG" → "..../..-/--." (the signal format of §6.3). */
export const toSignal = (word: string): string => [...word].map((letter) => MORSE[letter] ?? '').join('/');
export function solveMorse(
signal: string,
words: Record<string, string>,
): { word: string; frequency: string } | null {
const letters = signal.split('/').map((code) => Object.keys(MORSE).find((l) => MORSE[l] === code));
const word = letters.join('');
return letters.every(Boolean) && word in words ? { word, frequency: words[word] } : null;
}
// Say It Back: flashed colour → colour to press, one row per strike count.
const SIMON_MAPS: Record<'vowel' | 'noVowel', Record<string, string>[]> = {
vowel: [
{ red: 'blue', blue: 'red', green: 'yellow', yellow: 'green' },
{ red: 'yellow', blue: 'green', green: 'blue', yellow: 'red' },
{ red: 'green', blue: 'red', green: 'yellow', yellow: 'blue' },
],
noVowel: [
{ red: 'blue', blue: 'yellow', green: 'green', yellow: 'red' },
{ red: 'red', blue: 'blue', green: 'yellow', yellow: 'green' },
{ red: 'yellow', blue: 'green', green: 'blue', yellow: 'red' },
],
};
export function solveSimon(serial: string, strikes: number, flashes: string[]): string[] {
const rows = SIMON_MAPS[hasVowel(serial) ? 'vowel' : 'noVowel'];
const map = rows[Math.min(Math.max(strikes, 0), rows.length - 1)];
return flashes.map((color) => map[color] ?? color);
}
/** 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)));
@@ -60,6 +190,25 @@ export interface DefuseDevice {
wires?: { colors: string[]; solved: boolean };
button?: { label: string; color: string; strip: string; holding: boolean; solved: boolean };
keypad?: { symbols: string[]; pressed: string[]; solved: boolean };
indicators?: { label: string; lit: boolean }[];
passwords?: { columns: string[]; solved: boolean };
morse?: { word: string; solved: boolean };
/** `stage` flashes are showing; `progress` of them have been answered. */
simon?: { sequence: string[]; stage: number; progress: number; solved: boolean };
}
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
export function edgework(d: DefuseDevice): Edgework {
const shown = d.indicators ?? [];
return {
serial: d.serial,
batteries: d.batteries,
indicators: {
lit: shown.filter((i) => i.lit).map((i) => i.label),
unlit: shown.filter((i) => !i.lit).map((i) => i.label),
},
};
}
export function generateDevice(game: DefuseGame, levelIndex: number, seed: number): DefuseDevice {
@@ -83,6 +232,11 @@ export function generateDevice(game: DefuseGame, levelIndex: number, seed: numbe
serial += pick(digits); // last char is always a digit
const device: DefuseDevice = { serial, batteries: int(batteries.min, batteries.max) };
const ind = game.device.indicators;
if (ind) {
const shown = shuffle(ind.labels).slice(0, int(ind.count.min, ind.count.max));
device.indicators = shown.map((label) => ({ label, lit: rng() < 0.5 }));
}
const mods = game.modules;
for (const id of game.levels[levelIndex].modules) {
if (id === 'wires') {
@@ -96,9 +250,28 @@ export function generateDevice(game: DefuseGame, levelIndex: number, seed: numbe
holding: false,
solved: false,
};
} else {
} else if (id === 'keypad') {
const column = pick(mods.keypad.columns);
device.keypad = { symbols: shuffle(shuffle(column).slice(0, 4)), pressed: [], solved: false };
} else if (id === 'passwords' && mods.passwords) {
const { words, lettersPerColumn } = mods.passwords;
// Re-roll until exactly one listed word can be spelled.
let columns: string[] = [];
for (let attempt = 0; attempt < 200; attempt++) {
const target = pick(words);
columns = [...target].map((letter) => {
const others = shuffle([...ALPHABET].filter((l) => l !== letter)).slice(0, lettersPerColumn - 1);
return shuffle([letter, ...others]).join('');
});
if (solvePassword(columns, words) === target) break;
}
device.passwords = { columns, solved: false };
} else if (id === 'morse' && mods.morse) {
device.morse = { word: pick(Object.keys(mods.morse.words)), solved: false };
} else if (id === 'simon' && mods.simon) {
const { colors, stages } = mods.simon;
const sequence = Array.from({ length: int(stages.min, stages.max) }, () => pick(colors));
device.simon = { sequence, stage: 1, progress: 0, solved: false };
}
}
return device;
@@ -106,11 +279,15 @@ export function generateDevice(game: DefuseGame, levelIndex: number, seed: numbe
/** A generated device must always be solvable by the manual. */
export function isSolvable(game: DefuseGame, device: DefuseDevice): boolean {
if (!game.levels.some((level) => level.modules.every((id) => device[id] !== undefined))) return false;
if (device.wires) {
const { index } = solveWires(device.serial, device.wires.colors);
const { index } = wireSolution(game.ruleset, edgework(device), 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;
if (device.passwords && !solvePassword(device.passwords.columns, game.modules.passwords?.words ?? [])) return false;
if (device.morse && !solveMorse(toSignal(device.morse.word), game.modules.morse?.words ?? {})) return false;
if (device.simon && device.simon.sequence.length < 1) return false;
return true;
}
@@ -135,6 +312,13 @@ export function initDefuse(): DefuseState {
const state = (ctx: Ctx) => ctx.room.engine as DefuseState;
/** Strikes allowed on a level (some levels are stricter than the game default). */
export const maxStrikes = (game: DefuseGame, level: number): number =>
game.levels[level]?.strikesOverride ?? game.strikes.max;
const deviceModules = (d: DefuseDevice) =>
[d.wires, d.button, d.keypad, d.passwords, d.morse, d.simon].filter((m) => m !== undefined);
export function remainingAt(s: DefuseState, now: number): number {
if (!s.clock) return 0;
if (s.status !== 'active') return s.clock.remaining;
@@ -162,14 +346,15 @@ function strike(game: DefuseGame, ctx: Ctx, s: DefuseState) {
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.`);
const max = maxStrikes(game, s.level);
// The Say It Back mapping moves with the strike count, so the stage starts over.
if (s.device?.simon) s.device.simon.progress = 0;
if (s.strikes >= max) explode(ctx, s, 'strikes');
else ctx.toast('all', `Strike ${s.strikes} of ${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;
if (!deviceModules(s.device!).every((m) => m.solved)) return;
freezeClock(s, ctx.now);
s.status = 'cleared';
ctx.addKey(game.levels[s.level].keyName);
@@ -186,6 +371,11 @@ export function continueDefuse(game: DefuseGame, ctx: Ctx): ActionResult {
const s = state(ctx);
if (s.status === 'ready') {
s.device = generateDevice(game, s.level, s.seed);
// Never arm a device the solver can't solve.
for (let i = 0; i < 20 && !isSolvable(game, s.device); i++) {
s.seed = newSeed();
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';
@@ -216,13 +406,14 @@ export function defuseAction(
return OK;
}
const d = s.device;
const edge = edgework(d);
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;
if (action.index === wireSolution(game.ruleset, edge, 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 });
const solution = buttonSolution(game.ruleset, edge, b);
if (action.type === 'tap' && !b.holding) {
if (solution.type === 'tap') b.solved = true;
else strike(game, ctx, s);
@@ -242,16 +433,41 @@ export function defuseAction(
}
} 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)) {
const symbol = action.symbol ?? '';
if (!k.symbols.includes(symbol) || k.pressed.includes(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 (order[k.pressed.length] === symbol) {
k.pressed.push(symbol);
if (k.pressed.length === order.length) k.solved = true;
} else {
strike(game, ctx, s);
}
} else if (moduleId === 'passwords' && d.passwords && !d.passwords.solved && action.type === 'submit') {
const word = action.word.trim().toUpperCase();
if (word === solvePassword(d.passwords.columns, game.modules.passwords?.words ?? [])) d.passwords.solved = true;
else strike(game, ctx, s);
} else if (moduleId === 'morse' && d.morse && !d.morse.solved && action.type === 'transmit') {
const khz = Math.round(Number(action.frequency) * 1000);
if (!Number.isFinite(khz)) return fail('bad_action', "That isn't a frequency.");
const target = Number(game.modules.morse?.words[d.morse.word]);
if (khz === Math.round(target * 1000)) d.morse.solved = true;
else strike(game, ctx, s);
} else if (moduleId === 'simon' && d.simon && !d.simon.solved && action.type === 'press') {
const sim = d.simon;
const color = action.color ?? '';
if (!game.modules.simon?.colors.includes(color)) return fail('bad_action', 'That pad is not on the device.');
const [expected] = solveSimon(d.serial, s.strikes, [sim.sequence[sim.progress]]);
if (color !== expected) {
strike(game, ctx, s); // also restarts the stage
} else if (++sim.progress >= sim.stage) {
if (sim.stage >= sim.sequence.length) sim.solved = true;
else {
sim.stage++;
sim.progress = 0;
}
}
} else {
return fail('bad_action', "That module isn't on this device.");
}
+115 -8
View File
@@ -1,4 +1,4 @@
import type { Dir, Role } from '@two-keys/shared';
import type { Dir, MoveDir, RelDir, Role } from '@two-keys/shared';
import type { LabyrinthGame } from '../content/schemas';
import { OK, fail, type ActionResult, type Ctx } from './types';
@@ -7,16 +7,35 @@ export interface Point {
y: number;
}
/** You may step from (x, y) in `dir`, never back the other way. */
export interface Gate extends Point {
dir: Dir;
}
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 OPPOSITE: Record<Dir, Dir> = { n: 's', e: 'w', s: 'n', w: 'e' };
export const REL_DIRS: readonly RelDir[] = ['f', 'r', 'b', 'l'];
const CLOCKWISE: readonly Dir[] = ['n', 'e', 's', 'w'];
/** Forward / right / back / left from the way you face → a compass direction. */
export function toAbsolute(facing: Dir, rel: RelDir): Dir {
return CLOCKWISE[(CLOCKWISE.indexOf(facing) + REL_DIRS.indexOf(rel)) % 4];
}
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) === '#';
/** True if a one-way gate stops a step from (x, y) in `dir`. */
export function gateBlocks(gates: readonly Gate[], x: number, y: number, dir: Dir): boolean {
const d = DELTAS[dir];
return gates.some((g) => g.x === x + d.x && g.y === y + d.y && g.dir === OPPOSITE[dir]);
}
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 })));
@@ -26,7 +45,7 @@ export function findCells(grid: string[], char: string): Point[] {
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> {
export function safeReachable(grid: string[], gates: readonly Gate[] = []): Set<string> {
const [start] = findCells(grid, 'S');
const seen = new Set<string>();
if (!start) return seen;
@@ -34,10 +53,10 @@ export function safeReachable(grid: string[]): Set<string> {
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 };
for (const dir of CLOCKWISE) {
const next = { x: p.x + DELTAS[dir].x, y: p.y + DELTAS[dir].y };
const c = cellAt(grid, next.x, next.y);
if (c === '#' || c === 'T' || seen.has(key(next))) continue;
if (c === '#' || c === 'T' || seen.has(key(next)) || gateBlocks(gates, p.x, p.y, dir)) continue;
seen.add(key(next));
queue.push(next);
}
@@ -47,9 +66,78 @@ export function safeReachable(grid: string[]): Set<string> {
export const isReachable = (reach: Set<string>, p: Point) => reach.has(key(p));
/**
* Plays the maze out as a graph of (cell, lanterns held). Returns whether a trap-free run can
* finish, and any cell where the Explorer could end up with no way left to finish (one-way
* gates make that possible). Falling into a trap counts as a way out: it leads back to S.
*/
export function analyseMaze(
grid: string[],
gates: readonly Gate[],
lanterns: readonly Point[],
): { winnable: boolean; stuck: Point[] } {
const [start] = findCells(grid, 'S');
if (!start) return { winnable: false, stuck: [] };
const full = (1 << lanterns.length) - 1;
const id = (p: Point, mask: number, safe: boolean) => `${p.x},${p.y},${mask},${safe ? 1 : 0}`;
const pickUp = (p: Point, mask: number) => {
const i = lanterns.findIndex((l) => l.x === p.x && l.y === p.y);
return i >= 0 ? mask | (1 << i) : mask;
};
// `safe` tracks whether the run so far is trap-free.
type Node = { p: Point; mask: number; safe: boolean };
const first: Node = { p: start, mask: 0, safe: true };
const seen = new Map<string, Node>([[id(start, 0, true), first]]);
const reverse = new Map<string, string[]>();
const queue: Node[] = [first];
const goals: string[] = [];
while (queue.length > 0) {
const node = queue.shift()!;
const from = id(node.p, node.mask, node.safe);
if (cellAt(grid, node.p.x, node.p.y) === 'E' && node.mask === full) {
goals.push(from);
continue;
}
for (const dir of CLOCKWISE) {
const step = { x: node.p.x + DELTAS[dir].x, y: node.p.y + DELTAS[dir].y };
const c = cellAt(grid, step.x, step.y);
if (c === '#' || gateBlocks(gates, node.p.x, node.p.y, dir)) continue;
const next: Node =
c === 'T'
? { p: start, mask: node.mask, safe: false }
: { p: step, mask: pickUp(step, node.mask), safe: node.safe };
const to = id(next.p, next.mask, next.safe);
reverse.set(to, [...(reverse.get(to) ?? []), from]);
if (!seen.has(to)) {
seen.set(to, next);
queue.push(next);
}
}
}
const canFinish = new Set<string>(goals);
const back = [...goals];
while (back.length > 0) {
for (const from of reverse.get(back.pop()!) ?? []) {
if (!canFinish.has(from)) {
canFinish.add(from);
back.push(from);
}
}
}
const stuck = new Map<string, Point>();
for (const [nodeId, node] of seen) if (!canFinish.has(nodeId)) stuck.set(key(node.p), node.p);
return { winnable: goals.some((g) => g.endsWith(',1')), stuck: [...stuck.values()] };
}
export interface LabyrinthState {
x: number;
y: number;
/** The way the Explorer faces: the direction of their last step. */
facing?: Dir;
collected: boolean[];
moves: number;
falls: number;
@@ -58,27 +146,46 @@ export interface LabyrinthState {
export function initLabyrinth(game: LabyrinthGame): LabyrinthState {
const [start] = findCells(game.grid, 'S');
return { ...start, collected: game.lanterns.map(() => false), moves: 0, falls: 0, message: '' };
return {
...start,
facing: game.explorer.startFacing,
collected: game.lanterns.map(() => false),
moves: 0,
falls: 0,
message: '',
};
}
export function moveExplorer(game: LabyrinthGame, ctx: Ctx, role: Role, dir: Dir): ActionResult {
export const facingOf = (game: LabyrinthGame, s: LabyrinthState): Dir => s.facing ?? game.explorer.startFacing;
export function moveExplorer(game: LabyrinthGame, ctx: Ctx, role: Role, move: MoveDir): ActionResult {
const s = ctx.room.engine as LabyrinthState;
if (role !== 'B') return fail('wrong_role', 'Only the Explorer can move.');
const relative = game.explorer.compass === 'relative';
const isRel = (REL_DIRS as readonly string[]).includes(move);
if (relative !== isRel) return fail('bad_dir', relative ? 'You have no compass in here.' : "You can't move like that here.");
const dir = isRel ? toAbsolute(facingOf(game, s), move as RelDir) : (move as Dir);
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.");
if (gateBlocks(game.oneWay, s.x, s.y, dir)) return fail('gate', "The gate won't open from this side.");
const flavour = game.explorerView.flavour;
const throughGate = game.oneWay.some((g) => g.x === s.x && g.y === s.y && g.dir === dir);
s.moves++;
s.x = next.x;
s.y = next.y;
s.message = '';
s.facing = dir;
s.message = throughGate ? (flavour.gate ?? "A gate swings shut behind you. It won't open from this side.") : '';
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.facing = game.explorer.startFacing;
s.falls++;
s.message = flavour.trap;
ctx.addPenalty(game.scoring.trapPenaltySeconds);
+25 -3
View File
@@ -1,4 +1,4 @@
import { matchesAnswer, type Role } from '@two-keys/shared';
import { formatClock, matchesAnswer, type Role } from '@two-keys/shared';
import type { Lock, StoryGame } from '../content/schemas';
import { OK, fail, type ActionResult, type Ctx } from './types';
@@ -34,6 +34,28 @@ export function initStory(): StoryState {
}
const state = (ctx: Ctx) => ctx.room.engine as StoryState;
/** What one hint costs in this game. */
export const hintPenalty = (game: StoryGame): number => game.rules.hintPenaltySeconds ?? HINT_PENALTY_SECONDS;
/** The hard limit on elapsed + penalty time, for the games that have one. */
export const timeLimitSeconds = (game: StoryGame): number | null =>
game.rules.timeLimitMinutes ? Math.round(game.rules.timeLimitMinutes * 60) : null;
/** Called on a timer; returns true if the room changed (the time limit ran out). */
export function tickStory(game: StoryGame, ctx: Ctx): boolean {
const limit = timeLimitSeconds(game);
const { room } = ctx;
if (limit === null || room.phase !== 'playing' || room.startedAt === null) return false;
if ((ctx.now - room.startedAt) / 1000 + room.penaltySeconds < limit) return false;
const { finale } = game;
ctx.finish(
false,
finale.failEnding ?? "**Time's up.** The clock beat you this time. Run it back?",
finale.type === 'accusation' ? finale.reveal : null,
);
return true;
}
const atFinale = (game: StoryGame, s: StoryState) => s.chapter >= game.chapters.length;
/** The one lock that can currently be worked on, if any. */
@@ -82,8 +104,8 @@ export function requestHint(game: StoryGame, ctx: Ctx, lockId: string): ActionRe
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)`);
ctx.addPenalty(hintPenalty(game));
ctx.toast('all', `Hint ${tier + 1} revealed (+${formatClock(hintPenalty(game))})`);
return OK;
}
+79 -13
View File
@@ -1,7 +1,11 @@
import type { Role } from '@two-keys/shared';
import { normalizeAnswer, type Role, type SyncAnswer } from '@two-keys/shared';
import type { SyncGame, SyncQuestion } from '../content/schemas';
import { OK, fail, type ActionResult, type Ctx } from './types';
export const TELEPATHY_MAX_LENGTH = 40;
type Round = SyncGame['rounds'][number];
export interface SyncState {
round: number;
/** 0 on the first try, 1+ on a replay. */
@@ -9,10 +13,10 @@ export interface SyncState {
status: 'intro' | 'question' | 'reveal' | 'summary';
questions: SyncQuestion[];
q: number;
answers: Record<string, Partial<Record<Role, number>>>;
answers: Record<string, Partial<Record<Role, SyncAnswer>>>;
marks: boolean[];
earned: boolean;
/** Question ids already drawn this session, so nothing repeats. */
/** Questions already drawn this session, as `group|id`, so nothing repeats. */
used: string[];
}
@@ -34,14 +38,38 @@ export function initSync(game: SyncGame): SyncState {
const state = (ctx: Ctx) => ctx.room.engine as SyncState;
export const pointsForKey = (game: SyncGame, round: Round): number => round.pointsForKey ?? game.rules.pointsForKey;
/** Who question number `q` (0-based) of a round is about, if anyone. */
export function subjectOf(round: Round, q: number): Role | null {
if (round.type === 'predict') return round.subject ?? 'A';
if (round.type === 'rank') {
const pattern = round.subjectPattern ?? ['A', 'B'];
return pattern[q % pattern.length];
}
return null;
}
/** Rounds that ask the same question in the same way share a group. */
export const groupOf = (round: Round): string => `${round.type}:${round.type === 'predict' ? (round.subject ?? 'A') : ''}`;
/** 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 round = game.rounds[s.round];
const group = groupOf(round);
const all: SyncQuestion[] = game[round.type];
const usedIds = new Set(s.used.map((u) => u.slice(u.lastIndexOf('|') + 1)));
// Never-seen questions first. A spotlight question may come back only to be asked about the other partner.
const fresh = all.filter((q) => !usedIds.has(q.id));
const recycled = all.filter((q) => usedIds.has(q.id) && !s.used.includes(`${group}|${q.id}`));
const hand: SyncQuestion[] = [];
while (hand.length < game.rules.questionsPerRound && bank.length > 0) {
hand.push(...bank.splice(Math.floor(random() * bank.length), 1));
for (const bank of [fresh, recycled]) {
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.used.push(...hand.map((q) => `${group}|${q.id}`));
s.questions = hand;
s.q = 0;
s.answers = {};
@@ -53,27 +81,65 @@ export function canReplay(game: SyncGame, s: SyncState): boolean {
return !s.earned && s.attempt < game.rules.replaysPerRound;
}
/** Telepathy: case, spaces, punctuation and a trailing S are ignored. */
export function normalizeWord(input: string): string {
const word = normalizeAnswer(input);
return word.length > 1 ? word.replace(/S$/, '') : word;
}
/** Checks an answer against the question's shape and returns it in stored form, or null if it doesn't fit. */
function cleanAnswer(type: Round['type'], question: SyncQuestion, answer: unknown): SyncAnswer | null {
if (type === 'telepathy') {
if (typeof answer !== 'string') return null;
const text = answer.trim().slice(0, TELEPATHY_MAX_LENGTH);
return normalizeAnswer(text) === '' ? null : text;
}
if (type === 'rank') {
const count = question.items?.length ?? 0;
if (!Array.isArray(answer) || answer.length !== count) return null;
const valid = answer.every((i) => Number.isInteger(i) && i >= 0 && i < count);
return valid && new Set(answer).size === count ? [...answer] : null;
}
const count = question.options?.length ?? 0;
return typeof answer === 'number' && Number.isInteger(answer) && answer >= 0 && answer < count ? answer : null;
}
export function isMatch(type: Round['type'], a: SyncAnswer, b: SyncAnswer): boolean {
if (type === 'telepathy') return normalizeWord(String(a)) === normalizeWord(String(b));
if (type === 'rank') {
// Only the top and the bottom of the ranking have to agree.
const [x, y] = [a as number[], b as number[]];
return x[0] === y[0] && x[x.length - 1] === y[y.length - 1];
}
return a === b;
}
export function answerSync(
game: SyncGame,
ctx: Ctx,
role: Role,
questionId: string,
option: number,
answer: SyncAnswer | undefined,
): 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 { type } = game.rounds[s.round];
const clean = cleanAnswer(type, question, answer);
if (clean === null) {
return fail(
'bad_option',
type === 'telepathy' ? 'Type one word.' : type === 'rank' ? 'Put every item in order.' : '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;
answers[role] = clean;
if (answers.A !== undefined && answers.B !== undefined) {
s.marks.push(answers.A === answers.B);
s.marks.push(isMatch(type, answers.A, answers.B));
s.status = 'reveal';
}
return OK;
@@ -92,7 +158,7 @@ export function continueSync(game: SyncGame, ctx: Ctx): ActionResult {
s.q++;
s.status = 'question';
} else {
s.earned = s.marks.filter(Boolean).length >= game.rules.pointsForKey;
s.earned = s.marks.filter(Boolean).length >= pointsForKey(game, round);
if (s.earned) ctx.addKey(round.keyName);
s.status = 'summary';
}
+3
View File
@@ -2,6 +2,7 @@ import { rankFor, type GameResult, type Role, type RoomState } from '@two-keys/s
import type { Game } from '../content/schemas';
import { engineView, gameMeta } from '../content/sanitize';
import { totalKeys } from '../engines/index';
import { timeLimitSeconds } from '../engines/story';
import type { PlayerRec, Room } from './store';
export function computeResult(room: Room, game: Game): GameResult | null {
@@ -69,6 +70,8 @@ export function buildState(
finishedAt: room.finishedAt,
penaltySeconds: room.penaltySeconds,
serverNow: now,
limitSeconds: game.engine === 'story' ? timeLimitSeconds(game) : null,
limitLabel: game.engine === 'story' ? (game.rules.timeLimitLabel ?? null) : null,
},
stats: { hintsUsed: room.hintsUsed, wrongGuesses: room.wrongGuesses },
views,
+28 -11
View File
@@ -1,13 +1,20 @@
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 { DEFUSE_MODULES, 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 {
agreeAccusation,
proposeAccusation,
requestHint,
submitAccusation,
submitLock,
tickStory,
} from '../engines/story';
import { TELEPATHY_MAX_LENGTH, answerSync } from '../engines/sync';
import { createCtx, fail, type ActionResult, type Ctx } from '../engines/types';
import { cleanCode } from '../rooms/codes';
import { buildState } from '../rooms/state';
@@ -26,18 +33,27 @@ const schemas = {
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']),
moduleId: z.enum(DEFUSE_MODULES),
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() }),
z.object({ type: z.literal('press'), symbol: z.string().optional(), color: z.string().optional() }),
z.object({ type: z.literal('submit'), word: z.string().max(20) }),
z.object({ type: z.literal('transmit'), frequency: z.string().max(10) }),
]),
...asRole,
}),
sync: z.object({ questionId: z.string(), optionId: z.number().int(), ...asRole }),
move: z.object({ dir: z.enum(['n', 'e', 's', 'w']), ...asRole }),
// One of: an option index, a typed word (telepathy), or item indexes in order (rank).
sync: z.object({
questionId: z.string(),
optionId: z.number().int().optional(),
text: z.string().max(TELEPATHY_MAX_LENGTH * 2).optional(),
order: z.array(z.number().int()).max(12).optional(),
...asRole,
}),
move: z.object({ dir: z.enum(['n', 'e', 's', 'w', 'f', 'l', 'r', 'b']), ...asRole }),
notepad: z.object({ text: z.string() }),
ping: z.object({ emoji: z.enum(PING_EMOJIS), ...asRole }),
view: z.object({ label: z.string().max(80) }),
@@ -226,7 +242,7 @@ export function registerHandlers(io: Server, games: Map<string, Game>, store: Ro
on('sync:answer', schemas.sync, 'playing', ({ game, data, role, ctx }) =>
game.engine === 'sync'
? answerSync(game, ctx, role, data.questionId, data.optionId)
? answerSync(game, ctx, role, data.questionId, data.order ?? data.text ?? data.optionId)
: fail('wrong_engine', 'No questions here.'),
);
@@ -265,13 +281,14 @@ export function registerHandlers(io: Server, games: Map<string, Game>, store: Ro
});
});
// The defuse clock can run out with nobody touching anything.
// A defuse clock or a story time limit 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;
if (room.phase !== 'playing' || !game) continue;
if (game.engine !== 'defuse' && !(game.engine === 'story' && game.rules.timeLimitMinutes)) continue;
const ctx = createCtx(room);
if (tickDefuse(ctx)) {
if (game.engine === 'defuse' ? tickDefuse(ctx) : tickStory(game, ctx)) {
flushToasts(room, ctx);
broadcast(room);
}
+9 -5
View File
@@ -7,13 +7,17 @@ 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', () => {
it('loads all 18 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'],
);
expect(files).toHaveLength(18);
const engines = [...games.values()].map((g) => g.engine);
expect(Object.fromEntries(['story', 'defuse', 'sync', 'labyrinth'].map((e) => [e, engines.filter((x) => x === e).length]))).toEqual({
story: 11,
defuse: 2,
sync: 2,
labyrinth: 3,
});
});
it('rejects a story chapter with no clue for one player', () => {
+471
View File
@@ -0,0 +1,471 @@
// The second wave of games: Overtime (defuse), Deep Cuts (sync), the Drowned Catacombs and
// the Mirror Maze (labyrinth), and the story games with their own penalties and time limits.
import { describe, expect, it } from 'vitest';
import type { Dir, MoveDir, Role } from '@two-keys/shared';
import {
buttonSolution,
continueDefuse,
defuseAction,
edgework,
generateDevice,
isSolvable,
remainingAt,
solveKeypad,
solveMorse,
solvePassword,
solveSimon,
timerText,
toSignal,
wireSolution,
type DefuseState,
} from '../src/engines/defuse';
import { validateGame } from '../src/content/validate';
import { DELTAS, cellAt, findCells, gateBlocks, moveExplorer, toAbsolute, type LabyrinthState } from '../src/engines/labyrinth';
import { continueChapter, requestHint, submitLock, tickStory, type StoryState } from '../src/engines/story';
import { answerSync, continueSync, normalizeWord, type SyncState } from '../src/engines/sync';
import { buildState } from '../src/rooms/state';
import type { Room } from '../src/rooms/store';
import { clock, games, getGame, playingRoom } from './helpers';
const overtime = () => getGame('tick-tock-overtime', 'defuse');
const deepCuts = () => getGame('in-sync-deep-cuts', 'sync');
const catacombs = () => getGame('drowned-catacombs', 'labyrinth');
const mirrorMaze = () => getGame('mirror-maze', 'labyrinth');
const viewOf = (room: Room, role: Role, now = 2_000_000) => {
const player = room.players.find((p) => p.seat === role)!;
return JSON.parse(JSON.stringify(buildState(room, player, games.get(room.gameId)!, () => true, now)));
};
describe('defuse: Overtime manual', () => {
const game = overtime();
const { fixtures, modules, ruleset } = game;
it.each(fixtures.wires)('wires fixture %#', (f) => {
expect(wireSolution(ruleset, f, f.wires)).toEqual(f.expect);
});
it.each(fixtures.button)('button fixture %#', (f) => {
expect(buttonSolution(ruleset, { serial: '', ...f }, f)).toEqual(f.expect);
});
it.each(fixtures.keypad)('keypad fixture %#', (f) => {
expect(solveKeypad(f.symbols, modules.keypad.columns)).toEqual(f.expect);
});
it.each(fixtures.passwords)('passwords fixture %#', (f) => {
expect(solvePassword(f.columns, modules.passwords!.words)).toBe(f.expect);
});
it.each(fixtures.morse)('morse fixture %#', (f) => {
expect(solveMorse(f.signal, modules.morse!.words)).toEqual(f.expect);
});
it.each(fixtures.simon)('simon fixture %#', (f) => {
expect(solveSimon(f.serial, f.strikes, f.flashes)).toEqual(f.expect);
});
it('never generates a device the solver cannot solve, on any level', () => {
for (let level = 0; level < game.levels.length; level++) {
for (let seed = 1; seed <= 400; seed++) {
const device = generateDevice(game, level, seed);
expect(isSolvable(game, device), `level ${level} seed ${seed}`).toBe(true);
expect(device.indicators!.length).toBeGreaterThanOrEqual(1);
expect(device.indicators!.length).toBeLessThanOrEqual(3);
if (device.passwords) {
expect(device.passwords.columns).toHaveLength(5);
for (const column of device.passwords.columns) expect(new Set(column).size).toBe(6);
}
if (device.simon) {
expect(device.simon.sequence.length).toBeGreaterThanOrEqual(3);
expect(device.simon.sequence.length).toBeLessThanOrEqual(5);
}
}
}
});
/** Solves whatever is on the device, using only the solver. */
function solveAll(room: Room, t: ReturnType<typeof clock>) {
const s = room.engine as DefuseState;
const d = s.device!;
const act = (id: string, action: Parameters<typeof defuseAction>[4], ms = 100) =>
expect(defuseAction(game, t.ctx(ms), 'A', id, action).ok, id).toBe(true);
if (d.wires) act('wires', wireSolution(ruleset, edgework(d), d.wires.colors));
if (d.keypad) for (const symbol of solveKeypad(d.keypad.symbols, modules.keypad.columns)!) act('keypad', { type: 'press', symbol });
if (d.passwords) act('passwords', { type: 'submit', word: solvePassword(d.passwords.columns, modules.passwords!.words)! });
if (d.morse) act('morse', { type: 'transmit', frequency: solveMorse(toSignal(d.morse.word), modules.morse!.words)!.frequency });
if (d.simon) {
for (let stage = 1; stage <= d.simon.sequence.length; stage++) {
for (const color of solveSimon(d.serial, s.strikes, d.simon.sequence.slice(0, stage))) act('simon', { type: 'press', color });
}
}
if (d.button) {
const solution = buttonSolution(ruleset, edgework(d), d.button);
if (solution.type === 'tap') act('button', { type: 'tap' });
else {
act('button', { type: 'hold' });
for (let i = 0; i < 400; i++) {
if (timerText(remainingAt(s, t.now)).includes(String(solution.releaseDigit))) break;
t.ctx(500);
}
act('button', { type: 'release' }, 0);
}
}
}
it('clears all four 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);
solveAll(room, t);
const s = room.engine as DefuseState;
expect(s.strikes, `level ${level}`).toBe(0);
expect(s.status, `level ${level}`).toBe('cleared');
if (level < game.levels.length - 1) continueDefuse(game, t.ctx());
}
expect(room.keys).toEqual(game.levels.map((l) => l.keyName));
expect(room.result?.success).toBe(true);
});
it('Say It Back: a wrong pad strikes, restarts the stage, and moves the mapping', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as DefuseState;
s.level = 2;
continueDefuse(game, t.ctx());
const sim = s.device!.simon!;
const expected = (strikes: number) => solveSimon(s.device!.serial, strikes, [sim.sequence[0]])[0];
defuseAction(game, t.ctx(), 'A', 'simon', { type: 'press', color: expected(0) });
expect(sim).toMatchObject({ stage: 2, progress: 0 });
defuseAction(game, t.ctx(), 'A', 'simon', { type: 'press', color: expected(0) });
expect(sim.progress).toBe(1);
const wrong = modules.simon!.colors.find((c) => c !== solveSimon(s.device!.serial, 0, [sim.sequence[1]])[0])!;
defuseAction(game, t.ctx(), 'A', 'simon', { type: 'press', color: wrong });
expect(s.strikes).toBe(1);
expect(sim).toMatchObject({ stage: 2, progress: 0 });
// One strike in, the first flash now maps to a different pad.
expect(expected(1)).not.toBe(expected(0));
defuseAction(game, t.ctx(), 'A', 'simon', { type: 'press', color: expected(1) });
expect(s.strikes).toBe(1);
expect(sim.progress).toBe(1);
});
it('a wrong password or frequency is a strike, and the last level only allows two', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as DefuseState;
s.level = 3;
continueDefuse(game, t.ctx());
expect(viewOf(room, 'A', t.now).views.A.maxStrikes).toBe(2);
defuseAction(game, t.ctx(), 'A', 'passwords', { type: 'submit', word: 'ZZZZZ' });
expect(s).toMatchObject({ strikes: 1, status: 'active' });
expect(defuseAction(game, t.ctx(), 'A', 'morse', { type: 'transmit', frequency: 'loud' }).ok).toBe(false);
expect(s.strikes).toBe(1);
defuseAction(game, t.ctx(), 'A', 'morse', { type: 'transmit', frequency: '3.501' });
expect(s).toMatchObject({ strikes: 2, status: 'exploded', failReason: 'strikes' });
});
it('the Technician gets the blinking pattern and the letters, never the word or the manual', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as DefuseState;
s.level = 3;
continueDefuse(game, t.ctx());
const d = s.device!;
const tech = viewOf(room, 'A', t.now).views.A;
const json = JSON.stringify(tech);
expect(json).not.toContain('Defusal Manual');
expect(tech.device.indicators).toEqual(d.indicators);
const byId = Object.fromEntries(tech.device.modules.map((m: { id: string }) => [m.id, m]));
expect(Object.keys(byId).sort()).toEqual([...game.levels[3].modules].sort());
expect(byId.morse.signal).toBe(toSignal(d.morse!.word));
expect(byId.morse).not.toHaveProperty('word');
expect(byId.passwords.columns).toEqual(d.passwords!.columns);
// Only the flashes of the current stage, not the whole sequence.
expect(byId.simon.flashes).toEqual(d.simon!.sequence.slice(0, 1));
expect(json).not.toContain('"sequence"');
const expert = JSON.stringify(viewOf(room, 'B', t.now).views.B);
expect(expert).toContain('Overtime Edition');
expect(expert).not.toContain(d.serial);
for (const key of ['device', 'indicators', 'signal', 'columns', 'flashes']) expect(expert).not.toContain(`"${key}"`);
});
});
describe('sync: Deep Cuts', () => {
const game = deepCuts();
it('telepathy ignores case, spacing, punctuation and a trailing S', () => {
expect(normalizeWord(' Ice-Cream ')).toBe(normalizeWord('ice cream'));
expect(normalizeWord('Apples')).toBe(normalizeWord('apple'));
expect(normalizeWord('kiss')).toBe(normalizeWord('KISS'));
expect(normalizeWord('pear')).not.toBe(normalizeWord('peach'));
});
/** Plays the open round; `matches` of the questions are answered in sync. */
function playRound(room: Room, t: ReturnType<typeof clock>, matches: number, seen: string[]) {
const s = room.engine as SyncState;
const { type } = game.rounds[s.round];
expect(s.questions, `round ${s.round} attempt ${s.attempt}`).toHaveLength(game.rules.questionsPerRound);
for (let i = 0; i < game.rules.questionsPerRound; i++) {
const q = s.questions[s.q];
seen.push(`${s.round}:${q.id}`);
const hit = i < matches;
if (type === 'telepathy') {
expect(answerSync(game, t.ctx(), 'A', q.id, 2).ok).toBe(false); // no options to pick from
expect(answerSync(game, t.ctx(), 'A', q.id, ' ').ok).toBe(false);
answerSync(game, t.ctx(), 'A', q.id, 'Mangos');
answerSync(game, t.ctx(), 'B', q.id, hit ? ' mango' : 'pear');
} else if (type === 'rank') {
expect(answerSync(game, t.ctx(), 'A', q.id, [0, 1, 2]).ok).toBe(false); // every item, once
expect(answerSync(game, t.ctx(), 'A', q.id, [0, 1, 1, 3]).ok).toBe(false);
answerSync(game, t.ctx(), 'A', q.id, [0, 1, 2, 3]);
// Top and bottom agree (the middle doesn't have to), or only the top does.
answerSync(game, t.ctx(), 'B', q.id, hit ? [0, 2, 1, 3] : [0, 1, 3, 2]);
} else {
answerSync(game, t.ctx(), 'A', q.id, 0);
answerSync(game, t.ctx(), 'B', q.id, hit ? 0 : 1);
}
expect(s.status).toBe('reveal');
expect(s.marks[i]).toBe(hit);
continueSync(game, t.ctx());
}
expect(s.status).toBe('summary');
}
it('scores each round type, with its own bar for the key', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as SyncState;
const seen: string[] = [];
continueSync(game, t.ctx());
playRound(room, t, 3, seen); // telepathy needs 3
expect(room.keys).toEqual(['Telepathy Key']);
continueSync(game, t.ctx());
continueSync(game, t.ctx());
expect(viewOf(room, 'A').views.A).toMatchObject({ pointsForKey: 4, round: { type: 'predict', subject: 'A' }, iAmSubject: true });
playRound(room, t, 3, seen); // spotlight needs 4: not enough
expect(s.earned).toBe(false);
continueSync(game, t.ctx()); // replay
playRound(room, t, 4, seen);
expect(room.keys).toEqual(['Telepathy Key', 'Deep Key A']);
continueSync(game, t.ctx());
continueSync(game, t.ctx());
playRound(room, t, 0, seen);
continueSync(game, t.ctx());
playRound(room, t, 0, seen); // both tries missed
continueSync(game, t.ctx());
expect(s.round).toBe(3);
continueSync(game, t.ctx());
// The spotlight alternates A, B, A, B, A through the ranking round.
expect(viewOf(room, 'B').views.B).toMatchObject({ round: { type: 'rank', subject: 'A' }, iAmSubject: false });
expect(viewOf(room, 'B').views.B.question.options).toHaveLength(4);
playRound(room, t, 3, seen);
expect(room.keys).toEqual(['Telepathy Key', 'Deep Key A', 'Ranking Key']);
continueSync(game, t.ctx());
expect(room.phase).toBe('finished');
// Nothing was asked twice in the same way (a spotlight question may return for the other partner).
const groups = seen.map((x) => x.replace(/^[12]:/, (m) => (m === '1:' ? 'A:' : 'B:')));
expect(new Set(groups).size).toBe(groups.length);
});
it("keeps a typed word private until both are in", () => {
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, 'Banana');
expect(JSON.stringify(viewOf(room, 'B').views.B)).not.toContain('Banana');
expect(viewOf(room, 'B').views.B).toMatchObject({ myAnswer: null, partnerAnswered: true, reveal: null });
answerSync(game, t.ctx(), 'B', q.id, 'bananas');
expect(viewOf(room, 'B').views.B.reveal).toEqual({ A: 'Banana', B: 'bananas', match: true });
});
});
describe('labyrinth: one-way gates (Drowned Catacombs)', () => {
const game = catacombs();
it('lets the Explorer through a gate one way only', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as LabyrinthState;
const [gate] = game.oneWay; // (5,9) → east
Object.assign(s, { x: gate.x, y: gate.y });
expect(viewOf(room, 'B').views.B).toMatchObject({ compass: 'absolute', gates: [] });
expect(moveExplorer(game, t.ctx(), 'B', gate.dir).ok).toBe(true);
expect(s.message).toBe(game.explorerView.flavour.gate);
const explorer = viewOf(room, 'B').views.B;
expect(explorer.open.w).toBe(false);
expect(explorer.gates).toEqual(['w']);
expect(moveExplorer(game, t.ctx(), 'B', 'w')).toMatchObject({ ok: false, code: 'gate' });
expect(s).toMatchObject({ x: gate.x + 1, y: gate.y });
expect(viewOf(room, 'A').views.A.oneWay).toEqual(game.oneWay);
});
it('rejects a maze where a gate can trap the Explorer for good', () => {
const sealed = structuredClone(game);
// A dead-end pocket behind a gate, with no trap to fall out through.
sealed.grid = ['#####', '#S.E#', '#.###', '#.KK#', '#.#K#', '#####'];
sealed.lanterns = [
{ x: 2, y: 3, name: 'a' },
{ x: 3, y: 3, name: 'b' },
{ x: 3, y: 4, name: 'c' },
];
sealed.glyphs = [];
sealed.oneWay = [{ x: 1, y: 3, dir: 'e' }];
expect(validateGame(sealed).join('\n')).toMatch(/stuck for good/);
sealed.oneWay = [];
expect(validateGame(sealed)).toEqual([]);
});
});
describe('labyrinth: no compass, mirrored map (Mirror Maze)', () => {
const game = mirrorMaze();
it('turns forward/left/right/back into steps from the way the Explorer faces', () => {
expect((['f', 'r', 'b', 'l'] as const).map((rel) => toAbsolute('e', rel))).toEqual(['e', 's', 'w', 'n']);
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as LabyrinthState;
expect(s).toMatchObject({ x: 1, y: 1, facing: 'e' });
expect(moveExplorer(game, t.ctx(), 'B', 'e')).toMatchObject({ ok: false, code: 'bad_dir' }); // no compass
expect(moveExplorer(game, t.ctx(), 'B', 'l')).toMatchObject({ ok: false, code: 'wall' });
moveExplorer(game, t.ctx(), 'B', 'f');
moveExplorer(game, t.ctx(), 'B', 'f'); // (3,1), still facing east
expect(s).toMatchObject({ x: 3, y: 1, facing: 'e' });
moveExplorer(game, t.ctx(), 'B', 'r'); // right of east is south
expect(s).toMatchObject({ x: 3, y: 2, facing: 's' });
const explorer = viewOf(room, 'B').views.B;
expect(explorer.compass).toBe('relative');
expect(explorer.open).toEqual({ f: true, r: false, b: true, l: false });
expect(JSON.stringify(explorer)).not.toMatch(/"(facing|n|e|s|w|x|y|grid)"/);
});
it('serves the Navigator the map flipped left to right', () => {
const room = playingRoom(game);
const navigator = viewOf(room, 'A').views.A;
const width = game.grid[0].length;
expect(navigator.banner).toMatch(/traced from a mirror/);
expect(navigator.grid).toEqual(game.grid.map((row) => [...row].reverse().join('')));
expect(navigator.grid).not.toEqual(game.grid);
game.lanterns.forEach((l, i) => {
expect(navigator.lanterns[i]).toMatchObject({ x: width - 1 - l.x, y: l.y });
expect(navigator.grid[l.y][navigator.lanterns[i].x]).toBe('K');
});
game.glyphs.forEach((g, i) => expect(navigator.glyphs[i].x).toBe(width - 1 - g.x));
});
});
describe.each([catacombs(), mirrorMaze()].map((g) => [g.id, g] as const))('labyrinth: %s', (_id, game) => {
it('can be completed without a single trap', () => {
const room = playingRoom(game);
const t = clock(room);
const s = room.engine as LabyrinthState;
const state = (p: { x: number; y: number }, held: boolean[]) => `${p.x},${p.y},${held.map(Number).join('')}`;
// Breadth-first over (cell, lanterns held): gates make the order matter.
type Node = { x: number; y: number; held: boolean[]; path: Dir[] };
const queue: Node[] = [{ x: s.x, y: s.y, held: game.lanterns.map(() => false), path: [] }];
const seen = new Set([state(queue[0], queue[0].held)]);
let route: Dir[] | null = null;
while (queue.length && !route) {
const node = queue.shift()!;
for (const dir of Object.keys(DELTAS) as Dir[]) {
const next = { x: node.x + DELTAS[dir].x, y: node.y + DELTAS[dir].y };
const c = cellAt(game.grid, next.x, next.y);
if (c === '#' || c === 'T' || gateBlocks(game.oneWay, node.x, node.y, dir)) continue;
const held = node.held.map((h, i) => h || (game.lanterns[i].x === next.x && game.lanterns[i].y === next.y));
if (seen.has(state(next, held))) continue;
seen.add(state(next, held));
const path = [...node.path, dir];
if (c === 'E' && held.every(Boolean)) route = path;
queue.push({ ...next, held, path });
}
}
expect(route).not.toBeNull();
const relative = game.explorer.compass === 'relative';
for (const dir of route!) {
const move: MoveDir = relative ? (['f', 'r', 'b', 'l'] as const).find((rel) => toAbsolute(s.facing!, rel) === dir)! : dir;
expect(moveExplorer(game, t.ctx(), 'B', move).ok).toBe(true);
}
expect(room.phase).toBe('finished');
expect(s.falls).toBe(0);
expect(room.keys).toHaveLength(game.lanternsRequired);
expect(findCells(game.grid, 'K')).toHaveLength(game.lanternsRequired);
});
});
describe('story: per-game hint penalties and time limits', () => {
it('charges the hint penalty the game sets', () => {
const game = getGame('kestrel-heist', 'story');
const room = playingRoom(game);
const t = clock(room);
const ctx = t.ctx();
requestHint(game, ctx, game.chapters[0].lock.id);
expect(room.penaltySeconds).toBe(240);
expect(ctx.toasts[0].message).toBe('Hint 1 revealed (+4:00)');
expect(viewOf(room, 'A').views.A.chapters[0].lock.hintPenaltySeconds).toBe(240);
const classic = getGame('vineyard-hollow', 'story');
const other = playingRoom(classic);
requestHint(classic, clock(other).ctx(), classic.chapters[0].lock.id);
expect(other.penaltySeconds).toBe(120);
});
it('ends the game when the clock (elapsed + penalties) passes the limit', () => {
const game = getGame('deep-lab-nereid', 'story');
const limit = game.rules.timeLimitMinutes! * 60;
const room = playingRoom(game);
const t = clock(room);
expect(viewOf(room, 'A').timer).toMatchObject({ limitSeconds: limit, limitLabel: 'Water level' });
expect(tickStory(game, t.ctx((limit - 100) * 1000))).toBe(false);
requestHint(game, t.ctx(), game.chapters[0].lock.id); // +3:00 tips it over
expect(tickStory(game, t.ctx())).toBe(true);
expect(room.phase).toBe('finished');
expect(room.result).toEqual({ success: false, ending: game.finale.failEnding, reveal: null });
expect(tickStory(game, t.ctx())).toBe(false);
});
it('shows the reveal when an accusation game times out, and leaves untimed games alone', () => {
const game = getGame('kalahari-expedition', 'story');
if (game.finale.type !== 'accusation') throw new Error('expected accusation');
const room = playingRoom(game);
const t = clock(room);
expect(tickStory(game, t.ctx(game.rules.timeLimitMinutes! * 60_000))).toBe(true);
expect(room.result).toEqual({ success: false, ending: game.finale.failEnding, reveal: game.finale.reveal });
const untimed = getGame('vineyard-hollow', 'story');
const calm = playingRoom(untimed);
expect(tickStory(untimed, clock(calm).ctx(24 * 3600_000))).toBe(false);
expect(viewOf(calm, 'A').timer).toMatchObject({ limitSeconds: null, limitLabel: null });
});
it('plays a timed escape room through to the end inside the limit', () => {
const game = getGame('deep-lab-nereid', 'story');
if (game.finale.type !== 'escape') throw new Error('expected escape');
const room = playingRoom(game);
const t = clock(room);
for (const ch of game.chapters) {
expect(submitLock(game, t.ctx(), ch.lock.id, ch.lock.answers[0])).toMatchObject({ correct: true });
continueChapter(game, t.ctx());
}
expect((room.engine as StoryState).chapter).toBe(game.chapters.length);
expect(tickStory(game, t.ctx())).toBe(false);
submitLock(game, t.ctx(), game.finale.lock.id, 'surface');
expect(room.result).toEqual({ success: true, ending: game.finale.successEnding, reveal: null });
});
});