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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 08:44:28 +02:00
co-authored by Claude Opus 5.5
parent bbe44e84c4
commit 6669be11e5
35 changed files with 921 additions and 215 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@two-keys/server",
"version": "1.1.0",
"version": "1.2.0",
"private": true,
"type": "module",
"scripts": {
+3
View File
@@ -133,6 +133,9 @@ export function storyView(game: StoryGame, s: StoryState, role: Role): StoryView
totalChapters: total,
awaitingContinue: s.awaitingContinue,
finale,
pins: [...(s.pins?.[role] ?? [])],
// Only a count: which clues the partner starred would hint at what they hold.
partnerPins: s.pins?.[otherRole(role)]?.length ?? 0,
};
}
+29 -4
View File
@@ -1,5 +1,6 @@
import { SYNC_ROUND_TYPES, normalizeAnswer } from '@two-keys/shared';
import {
OVERTIME_TABLES,
buttonSolution,
solveKeypad,
solveMorse,
@@ -100,6 +101,10 @@ function validateDefuse(game: DefuseGame): string[] {
});
fixtures.passwords.forEach((f, i) => {
const p = modules.passwords;
if (p && (f.columns.length !== p.columnsCount || f.columns.some((c) => c.length !== p.lettersPerColumn))) {
errors.push(`passwords fixture ${i + 1}: needs ${p.columnsCount} columns of exactly ${p.lettersPerColumn} letters`);
}
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'}`);
});
@@ -129,6 +134,19 @@ function validateDefuse(game: DefuseGame): string[] {
}
if (new Set(entries.map(([, f]) => f)).size !== entries.length) errors.push('two morse words share a frequency');
}
if (ruleset === 'overtime') {
// The manual's tables must be the ones the solver was written against.
const t = OVERTIME_TABLES;
if (!same(modules.keypad.columns, t.keypadColumns)) errors.push("keypad columns don't match the Overtime solver's");
if (!same([...(modules.passwords?.words ?? [])].sort(), [...t.passwordWords].sort())) {
errors.push("password word list doesn't match the Overtime solver's");
}
const morse = modules.morse?.words ?? {};
if (Object.keys(morse).length !== Object.keys(t.morseFrequencies).length) errors.push("morse word list doesn't match the Overtime solver's");
for (const [word, freq] of Object.entries(morse)) {
if (t.morseFrequencies[word] !== freq) errors.push(`morse word "${word}" should be on ${t.morseFrequencies[word] ?? 'no frequency'}, the YAML says ${freq}`);
}
}
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');
@@ -159,8 +177,14 @@ function validateSync(game: SyncGame): string[] {
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 q of game.rank) {
if (q.items.length !== 4) errors.push(`rank question ${q.id}: needs exactly 4 items, has ${q.items.length}`);
}
for (const r of game.rounds) {
if (r.type === 'predict' && !r.subject) errors.push(`round ${r.id}: predict rounds need a subject`);
if (r.type === 'rank' && r.subjectPattern && r.subjectPattern.length !== game.rules.questionsPerRound) {
errors.push(`round ${r.id}: subjectPattern should name a subject for each of the ${game.rules.questionsPerRound} questions`);
}
if (pointsForKey(game, r) > game.rules.questionsPerRound) errors.push(`round ${r.id}: pointsForKey is more than questionsPerRound`);
}
return errors;
@@ -184,14 +208,15 @@ function validateLabyrinth(game: LabyrinthGame): string[] {
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`);
const c = cellAt(grid, g.x, g.y);
if (c === '#' || c === 'T') errors.push(`glyph "${g.glyph}" at (${g.x},${g.y}) is on a ${c === '#' ? 'wall' : 'trap'}`);
}
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`);
}
const ends = [cellAt(grid, g.x, g.y), cellAt(grid, g.x + through.x, g.y + through.y)];
if (ends.includes('#')) errors.push(`one-way gate at (${g.x},${g.y}) ${g.dir} opens into a wall`);
if (ends.includes('T')) errors.push(`one-way gate at (${g.x},${g.y}) ${g.dir} sits on a trap`);
}
if (starts.length === 1) {
+32 -2
View File
@@ -171,6 +171,31 @@ export function solveKeypad(symbols: string[], columns: string[][]): string[] |
return matches[0].filter((s) => symbols.includes(s));
}
/**
* The Overtime manual's tables, as the reference solver has them. The YAML carries its own copy
* (the generator reads that one); validation checks the two agree.
*/
export const OVERTIME_TABLES = {
keypadColumns: [
['heart', 'star', 'moon', 'sun', 'club', 'flower', 'key'],
['umbrella', 'heart', 'plane', 'music', 'star', 'anchor', 'crown'],
['diamond', 'sun', 'spade', 'umbrella', 'flower', 'music', 'bolt'],
['anchor', 'spade', 'club', 'plane', 'moon', 'diamond', 'key'],
['crown', 'bolt', 'heart', 'diamond', 'plane', 'sun', 'cloud'],
['cloud', 'music', 'key', 'spade', 'club', 'crown', 'star'],
],
passwordWords: [
'ADORE', 'ANGEL', 'BLISS', 'BLUSH', 'CANDY', 'CHARM', 'CRUSH', 'DANCE', 'DREAM', 'FLAME', 'FLIRT',
'HEART', 'HONEY', 'LOVER', 'MATCH', 'PEACH', 'RINGS', 'ROSES', 'SMILE', 'SPARK', 'SUGAR', 'SWEET',
'TEDDY', 'TRUST', 'TULIP', 'UNITY', 'WALTZ', 'BLOOM', 'CHOSE', 'PEARL', 'VOWED', 'QUEEN',
],
morseFrequencies: {
HUG: '3.505', KISS: '3.515', LOVE: '3.522', DATE: '3.532', RING: '3.535', ROSE: '3.542', WINE: '3.545',
DUET: '3.552', DANCE: '3.555', HEART: '3.565', SWEET: '3.572', HONEY: '3.575', CUDDLE: '3.582',
SPARK: '3.592', VOWS: '3.595', BLISS: '3.600',
} as Record<string, string>,
};
// ---------- Generator ----------
export function mulberry32(seed: number): () => number {
@@ -251,8 +276,13 @@ export function generateDevice(game: DefuseGame, levelIndex: number, seed: numbe
solved: false,
};
} else if (id === 'keypad') {
const column = pick(mods.keypad.columns);
device.keypad = { symbols: shuffle(shuffle(column).slice(0, 4)), pressed: [], solved: false };
// Re-roll until exactly one column holds all four symbols.
let symbols: string[] = [];
for (let attempt = 0; attempt < 200; attempt++) {
symbols = shuffle(pick(mods.keypad.columns)).slice(0, 4);
if (solveKeypad(symbols, mods.keypad.columns)) break;
}
device.keypad = { symbols, pressed: [], solved: false };
} else if (id === 'passwords' && mods.passwords) {
const { words, lettersPerColumn } = mods.passwords;
// Re-roll until exactly one listed word can be spelled.
+22
View File
@@ -19,6 +19,8 @@ export interface StoryState {
agreed: boolean;
attempts: number;
};
/** Starred clue ids per role. The partner only ever learns how many. */
pins?: Partial<Record<Role, string[]>>;
}
export function initStory(): StoryState {
@@ -30,6 +32,7 @@ export function initStory(): StoryState {
wrong: {},
lastSubmit: {},
finale: { proposal: null, agreed: false, attempts: 0 },
pins: {},
};
}
@@ -53,6 +56,7 @@ export function tickStory(game: StoryGame, ctx: Ctx): boolean {
false,
finale.failEnding ?? "**Time's up.** The clock beat you this time. Run it back?",
finale.type === 'accusation' ? finale.reveal : null,
true,
);
return true;
}
@@ -109,6 +113,24 @@ export function requestHint(game: StoryGame, ctx: Ctx, lockId: string): ActionRe
return OK;
}
/** Every clue id this role can see so far. */
export function visibleClueIds(game: StoryGame, s: StoryState, role: Role): string[] {
const chapters = game.chapters.slice(0, Math.min(s.chapter, game.chapters.length - 1) + 1);
const ids = chapters.flatMap((ch) => [...ch.clues[role], ...ch.clues.shared].map((c) => c.id));
if (atFinale(game, s) && game.finale.type === 'escape') ids.push(...game.finale.clues[role].map((c) => c.id));
return ids;
}
/** Stars or un-stars one of your own clues. */
export function togglePin(game: StoryGame, ctx: Ctx, role: Role, clueId: string): ActionResult {
const s = state(ctx);
if (!visibleClueIds(game, s, role).includes(clueId)) return fail('no_clue', "You don't have that clue.");
const pins = (s.pins ??= {});
const mine = pins[role] ?? [];
pins[role] = mine.includes(clueId) ? mine.filter((id) => id !== clueId) : [...mine, clueId];
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.');
+3 -3
View File
@@ -2,7 +2,7 @@ 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;
export const TELEPATHY_MAX_LENGTH = 30;
type Round = SyncGame['rounds'][number];
@@ -91,8 +91,8 @@ export function normalizeWord(input: string): string {
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;
const text = answer.trim();
return text.length > TELEPATHY_MAX_LENGTH || normalizeAnswer(text) === '' ? null : text;
}
if (type === 'rank') {
const count = question.items?.length ?? 0;
+3 -3
View File
@@ -14,7 +14,7 @@ export interface Ctx {
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;
finish(success: boolean, ending?: string | null, reveal?: string | null, outOfTime?: boolean): void;
}
export function createCtx(room: Room, now = Date.now()): Ctx {
@@ -26,10 +26,10 @@ export function createCtx(room: Room, now = Date.now()): Ctx {
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) {
finish(success, ending = null, reveal = null, outOfTime = false) {
room.phase = 'finished';
room.finishedAt = now;
room.result = { success, ending, reveal };
room.result = { success, ending, reveal, outOfTime };
},
};
}
+5
View File
@@ -12,6 +12,7 @@ export function computeResult(room: Room, game: Game): GameResult | null {
const elapsedSeconds = Math.round((room.finishedAt - room.startedAt) / 1000);
const finalSeconds = elapsedSeconds + room.penaltySeconds;
const keys = totalKeys(game);
const outOfTime = room.result.outOfTime ?? false;
return {
success: room.result.success,
elapsedSeconds,
@@ -28,7 +29,11 @@ export function computeResult(room: Room, game: Game): GameResult | null {
estimatedMinutes: game.estimatedMinutes,
keysEarned: room.keys.length,
totalKeys: keys,
outOfTime,
}),
outOfTime,
// Difficulty 5, finished without a single hint.
nightmareSurvivors: room.result.success && game.difficulty >= 5 && room.hintsUsed === 0,
ending: room.result.ending,
reveal: room.result.reveal,
};
+1 -1
View File
@@ -28,7 +28,7 @@ export interface Room {
wrongGuesses: number;
/** Engine-specific state, owned by the game's engine. */
engine: unknown;
result: { success: boolean; ending: string | null; reveal: string | null } | null;
result: { success: boolean; ending: string | null; reveal: string | null; outOfTime?: boolean } | null;
}
export const ROOM_TTL_MS = 24 * 60 * 60 * 1000;
+22 -2
View File
@@ -1,7 +1,16 @@
import { randomUUID } from 'node:crypto';
import type { Server, Socket } from 'socket.io';
import { z } from 'zod';
import { DEFUSE_MODULES, PING_EMOJIS, otherRole, type JoinAck, type Phase, type Role } from '@two-keys/shared';
import {
DEFUSE_MODULES,
PING_EMOJIS,
otherRole,
type JoinAck,
type MoveDir,
type Phase,
type RelDir,
type Role,
} from '@two-keys/shared';
import type { Game } from '../content/schemas';
import { defuseAction, tickDefuse } from '../engines/defuse';
import { continueGame, initEngine } from '../engines/index';
@@ -13,6 +22,7 @@ import {
submitAccusation,
submitLock,
tickStory,
togglePin,
} from '../engines/story';
import { TELEPATHY_MAX_LENGTH, answerSync } from '../engines/sync';
import { createCtx, fail, type ActionResult, type Ctx } from '../engines/types';
@@ -31,6 +41,7 @@ const schemas = {
pickRole: z.object({ role }),
lockSubmit: z.object({ lockId: z.string(), value: z.string().max(200), ...asRole }),
hint: z.object({ lockId: z.string(), ...asRole }),
pin: z.object({ clueId: z.string().max(100), ...asRole }),
propose: z.object({ answers: z.record(z.string()), ...asRole }),
defuse: z.object({
moduleId: z.enum(DEFUSE_MODULES),
@@ -53,7 +64,12 @@ const schemas = {
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 }),
move: z.object({
dir: z
.enum(['n', 'e', 's', 'w', 'f', 'l', 'r', 'b', 'forward', 'left', 'right', 'back'])
.transform((d): MoveDir => (d.length > 1 ? (d[0] as RelDir) : (d as MoveDir))),
...asRole,
}),
notepad: z.object({ text: z.string() }),
ping: z.object({ emoji: z.enum(PING_EMOJIS), ...asRole }),
view: z.object({ label: z.string().max(80) }),
@@ -220,6 +236,10 @@ export function registerHandlers(io: Server, games: Map<string, Game>, store: Ro
game.engine === 'story' ? requestHint(game, ctx, data.lockId) : fail('wrong_engine', 'No hints here.'),
);
on('clue:pin', schemas.pin, 'playing', ({ game, data, role, ctx }) =>
game.engine === 'story' ? togglePin(game, ctx, role, data.clueId) : fail('wrong_engine', 'No clues here.'),
);
on('chapter:continue', empty, 'playing', ({ game, ctx }) => continueGame(game, ctx));
on('finale:propose', schemas.propose, 'playing', ({ game, data, role, ctx }) =>
+3 -3
View File
@@ -436,7 +436,7 @@ describe('story: per-game hint penalties and time limits', () => {
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(room.result).toEqual({ success: false, ending: game.finale.failEnding, reveal: null, outOfTime: true });
expect(tickStory(game, t.ctx())).toBe(false);
});
@@ -446,7 +446,7 @@ describe('story: per-game hint penalties and time limits', () => {
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 });
expect(room.result).toEqual({ success: false, ending: game.finale.failEnding, reveal: game.finale.reveal, outOfTime: true });
const untimed = getGame('vineyard-hollow', 'story');
const calm = playingRoom(untimed);
@@ -466,6 +466,6 @@ describe('story: per-game hint penalties and time limits', () => {
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 });
expect(room.result).toEqual({ success: true, ending: game.finale.successEnding, reveal: null, outOfTime: false });
});
});
+264
View File
@@ -0,0 +1,264 @@
// GAMES-NEW.md requirements for games 9–18 that the other suites don't already cover:
// sanitized payloads for every new game, Evidence Locker pins, "Out of time" and
// Nightmare Survivors results, one-shot accusations, and the extra content checks.
import { describe, expect, it } from 'vitest';
import type { Role } from '@two-keys/shared';
import type { Game } from '../src/content/schemas';
import { validateGame } from '../src/content/validate';
import { continueDefuse, type DefuseState } from '../src/engines/defuse';
import type { LabyrinthState } from '../src/engines/labyrinth';
import {
agreeAccusation,
continueChapter,
proposeAccusation,
submitAccusation,
submitLock,
tickStory,
togglePin,
} from '../src/engines/story';
import { TELEPATHY_MAX_LENGTH, answerSync, continueSync, 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 NEW_GAMES = [
'dead-air',
'masquerade-montague',
'kalahari-expedition',
'alchemists-vault',
'deep-lab-nereid',
'kestrel-heist',
'tick-tock-overtime',
'in-sync-deep-cuts',
'drowned-catacombs',
'mirror-maze',
];
const FORBIDDEN_KEYS = ['answers', 'answer', 'solution', 'fixtures', 'expect', 'seed', 'sequence', 'facing', 'word'];
const stateOf = (room: Room, role: Role, now = 2_000_000) => {
const player = room.players.find((p) => p.seat === role)!;
return buildState(room, player, games.get(room.gameId)!, () => true, now);
};
const json = (room: Room, role: Role, now?: number) => JSON.stringify(stateOf(room, role, 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;
}
/** Moves each new game a little way in, so there is real state to leak. */
function started(game: Game) {
const room = playingRoom(game);
const t = clock(room);
if (game.engine === 'defuse') {
(room.engine as DefuseState).level = game.levels.length - 1; // every module at once
continueDefuse(game, t.ctx());
}
if (game.engine === 'sync') {
continueSync(game, t.ctx());
const q = (room.engine as SyncState).questions[0];
answerSync(game, t.ctx(), 'A', q.id, 'Lighthouse');
}
return { room, t };
}
describe.each(NEW_GAMES.map((id) => [id, games.get(id)!] as const))('sanitized payloads: %s', (_id, game) => {
it('never carry answers, fixtures or solver state for either role', () => {
expect(game).toBeDefined();
const { room, t } = started(game);
for (const role of ['A', 'B'] as const) {
const keys = keysOf(JSON.parse(json(room, role, t.now)));
for (const key of FORBIDDEN_KEYS) expect(keys, `${role} got "${key}"`).not.toContain(key);
}
});
if (game.engine === 'defuse') {
it('keeps the device from the Expert and the manual from the Technician', () => {
const { room, t } = started(game);
const tech = json(room, 'A', t.now);
const expert = json(room, 'B', t.now);
expect(keysOf(JSON.parse(tech))).not.toContain('manual');
for (const key of ['device', 'indicators', 'serial', 'modules']) expect(keysOf(JSON.parse(expert))).not.toContain(key);
// Fixture answers don't ride along in any form.
for (const f of game.fixtures.passwords) expect(expert + tech).not.toContain(JSON.stringify(f.columns));
});
}
if (game.engine === 'sync') {
it('keeps a typed word and a ranking private until both are in', () => {
const { room } = started(game);
expect(json(room, 'B')).not.toContain('Lighthouse');
expect(stateOf(room, 'B').views.B).toMatchObject({ partnerAnswered: true, reveal: null });
});
}
if (game.engine === 'labyrinth') {
it("never sends the Explorer the map or where they are, or the Navigator the Explorer's position", () => {
const { room } = started(game);
const s = room.engine as LabyrinthState;
const explorer = JSON.parse(json(room, 'B')).views.B;
for (const key of ['grid', 'glyphs', 'lanterns', 'oneWay', 'x', 'y', 'facing']) expect(keysOf(explorer)).not.toContain(key);
// With no compass, not even a compass letter.
if (game.explorer.compass === 'relative') expect(JSON.stringify(explorer)).not.toMatch(/"[nesw]"/);
const navigator = JSON.parse(json(room, 'A')).views.A;
const { glyphs: _g, lanterns: _l, oneWay: _o, grid, ...rest } = navigator;
expect(keysOf(rest)).not.toContain('x');
if (game.navigatorView.mapTransform === 'mirror-x') {
// Only the mirrored map is ever served.
expect(grid).toEqual(game.grid.map((row) => [...row].reverse().join('')));
expect(grid).not.toEqual(game.grid);
} else {
expect(grid).toEqual(game.grid);
}
expect(s.x).toBeGreaterThan(0);
});
}
});
describe('story: Evidence Locker pins', () => {
const game = getGame('kalahari-expedition', 'story');
it('stars your own clues; your partner only sees how many', () => {
const room = playingRoom(game);
const t = clock(room);
const [mine] = game.chapters[0].clues.A;
const [theirs] = game.chapters[0].clues.B;
expect(togglePin(game, t.ctx(), 'A', theirs.id).ok).toBe(false);
expect(togglePin(game, t.ctx(), 'A', game.chapters[1].clues.A[0].id).ok).toBe(false); // not dealt yet
expect(togglePin(game, t.ctx(), 'A', mine.id).ok).toBe(true);
expect(stateOf(room, 'A').views.A).toMatchObject({ pins: [mine.id], partnerPins: 0 });
const b = stateOf(room, 'B').views.B;
expect(b).toMatchObject({ pins: [], partnerPins: 1 });
expect(JSON.stringify(b)).not.toContain(mine.id);
togglePin(game, t.ctx(), 'A', mine.id);
expect(stateOf(room, 'B').views.B).toMatchObject({ partnerPins: 0 });
});
});
describe('story: one-shot, four-question accusations', () => {
const game = getGame('masquerade-montague', 'story');
if (game.finale.type !== 'accusation') throw new Error('expected accusation');
const finale = game.finale;
function atFinale() {
const room = playingRoom(game);
const t = clock(room);
for (const ch of game.chapters) {
submitLock(game, t.ctx(), ch.lock.id, ch.lock.answers[0]);
continueChapter(game, t.ctx());
}
return { room, t };
}
it('has four questions and a single attempt', () => {
expect(finale.questions).toHaveLength(4);
expect(finale.maxAttempts).toBe(1);
});
it('a wrong accusation goes straight to the fail ending and the reveal', () => {
const { room, t } = atFinale();
const wrong = Object.fromEntries(finale.questions.map((q) => [q.id, q.options.find((o) => o.id !== q.answer)!.id]));
proposeAccusation(game, t.ctx(), 'A', wrong);
agreeAccusation(game, t.ctx(), 'B');
expect(submitAccusation(game, t.ctx())).toMatchObject({ correct: false });
expect(room.phase).toBe('finished');
expect(room.result).toMatchObject({ success: false, ending: finale.failEnding, reveal: finale.reveal });
});
it('the right one wins', () => {
const { room, t } = atFinale();
proposeAccusation(game, t.ctx(), 'B', Object.fromEntries(finale.questions.map((q) => [q.id, q.answer])));
agreeAccusation(game, t.ctx(), 'A');
expect(submitAccusation(game, t.ctx())).toMatchObject({ correct: true });
expect(room.result?.success).toBe(true);
});
});
describe('results', () => {
it('a time limit running out shows "Out of time", not a rank', () => {
const game = getGame('kestrel-heist', 'story');
const room = playingRoom(game);
const t = clock(room);
tickStory(game, t.ctx(game.rules.timeLimitMinutes! * 60_000));
expect(stateOf(room, 'A').result).toMatchObject({ success: false, outOfTime: true, rank: 'Out of time', nightmareSurvivors: false });
});
it('a difficulty-5 game with zero hints earns Nightmare Survivors', () => {
const game = getGame('kestrel-heist', 'story');
expect(game.difficulty).toBe(5);
const room = playingRoom(game);
const t = clock(room);
for (const ch of game.chapters) {
submitLock(game, t.ctx(), ch.lock.id, ch.lock.answers[0]);
continueChapter(game, t.ctx());
}
if (game.finale.type !== 'escape') throw new Error('expected escape');
submitLock(game, t.ctx(), game.finale.lock.id, game.finale.lock.answers[0]);
expect(stateOf(room, 'A').result).toMatchObject({ success: true, outOfTime: false, nightmareSurvivors: true });
// Not for an easier game.
const easy = getGame('alchemists-vault', 'story');
const other = playingRoom(easy);
const t2 = clock(other);
for (const ch of easy.chapters) {
submitLock(easy, t2.ctx(), ch.lock.id, ch.lock.answers[0]);
continueChapter(easy, t2.ctx());
}
if (easy.finale.type !== 'escape') throw new Error('expected escape');
submitLock(easy, t2.ctx(), easy.finale.lock.id, easy.finale.lock.answers[0]);
expect(stateOf(other, 'A').result).toMatchObject({ success: true, nightmareSurvivors: false });
});
});
describe('sync: telepathy input', () => {
it(`rejects empty answers and anything over ${TELEPATHY_MAX_LENGTH} characters`, () => {
const game = getGame('in-sync-deep-cuts', 'sync');
const room = playingRoom(game);
const t = clock(room);
continueSync(game, t.ctx());
const q = (room.engine as SyncState).questions[0];
expect(answerSync(game, t.ctx(), 'A', q.id, '').ok).toBe(false);
expect(answerSync(game, t.ctx(), 'A', q.id, 'x'.repeat(TELEPATHY_MAX_LENGTH + 1)).ok).toBe(false);
expect(answerSync(game, t.ctx(), 'A', q.id, 'x'.repeat(TELEPATHY_MAX_LENGTH)).ok).toBe(true);
});
});
describe('content validation additions', () => {
const clone = <T>(game: T): T => structuredClone(game);
it('rejects a rank question without exactly 4 items', () => {
const game = clone(getGame('in-sync-deep-cuts', 'sync'));
game.rank[0].items = game.rank[0].items.slice(0, 3);
expect(validateGame(game).join('\n')).toMatch(/exactly 4 items/);
});
it("rejects Overtime tables that don't match the solver's", () => {
const game = clone(getGame('tick-tock-overtime', 'defuse'));
game.modules.passwords!.words[0] = 'ZEBRA';
game.modules.morse!.words.HUG = '3.506';
const errors = validateGame(game).join('\n');
expect(errors).toMatch(/password word list/);
expect(errors).toMatch(/morse word "HUG" should be on 3.505/);
});
it('rejects a password fixture column without 6 letters', () => {
const game = clone(getGame('tick-tock-overtime', 'defuse'));
game.fixtures.passwords[0].columns[0] = 'XAPUD';
expect(validateGame(game).join('\n')).toMatch(/exactly 6 letters/);
});
it('rejects a glyph on a trap', () => {
const game = clone(getGame('mirror-maze', 'labyrinth'));
const [trap] = game.grid.flatMap((row, y) => [...row].flatMap((c, x) => (c === 'T' ? [{ x, y }] : [])));
game.glyphs[0] = { ...game.glyphs[0], ...trap };
expect(validateGame(game).join('\n')).toMatch(/is on a trap/);
});
});
+1 -1
View File
@@ -122,6 +122,6 @@ describe('story rules', () => {
}
}
expect(room.phase).toBe('finished');
expect(room.result).toEqual({ success: false, ending: game.finale.failEnding, reveal: game.finale.reveal });
expect(room.result).toEqual({ success: false, ending: game.finale.failEnding, reveal: game.finale.reveal, outOfTime: false });
});
});