V1.0.0
Two Keys: co-op mystery games for couples. Eight games on four engines (story, defuse, sync, labyrinth), two-device and couch play, mobile-first UI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { loadAllFiles } from '../src/content/loader';
|
||||
import { gameSchema } from '../src/content/schemas';
|
||||
import { validateGame } from '../src/content/validate';
|
||||
import { CODE_ALPHABET, makeCode } from '../src/rooms/codes';
|
||||
import { ROOM_TTL_MS, RoomStore } from '../src/rooms/store';
|
||||
import { games, getGame, labyrinth, sync } from './helpers';
|
||||
|
||||
describe('content', () => {
|
||||
it('loads all 8 games with no validation errors', () => {
|
||||
const files = loadAllFiles();
|
||||
expect(files.flatMap((f) => f.errors.map((e) => `${f.file}: ${e}`))).toEqual([]);
|
||||
expect(files).toHaveLength(8);
|
||||
expect([...games.values()].map((g) => g.engine).sort()).toEqual(
|
||||
['defuse', 'labyrinth', 'story', 'story', 'story', 'story', 'story', 'sync'],
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a story chapter with no clue for one player', () => {
|
||||
const game = structuredClone(getGame('clockmakers-attic', 'story'));
|
||||
game.chapters[0].clues.B = [];
|
||||
expect(validateGame(game).join('\n')).toMatch(/at least one clue for B/);
|
||||
});
|
||||
|
||||
it('rejects a finale answer that is not an option, and a lock without 3 hints', () => {
|
||||
const game = structuredClone(getGame('vineyard-hollow', 'story'));
|
||||
if (game.finale.type !== 'accusation') throw new Error('expected accusation');
|
||||
game.finale.questions[0].answer = 'nobody';
|
||||
expect(validateGame(game).join('\n')).toMatch(/not one of the options/);
|
||||
|
||||
const raw = structuredClone(getGame('vineyard-hollow', 'story')) as any;
|
||||
raw.chapters[0].lock.hints.pop();
|
||||
expect(gameSchema.safeParse(raw).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a labyrinth whose lantern is only reachable through a trap', () => {
|
||||
const game = structuredClone(labyrinth());
|
||||
// Wall off (1,6)... the only trap-free way to the Listening lantern is via (3,6)/(3,7).
|
||||
game.grid[6] = '#######.#.#';
|
||||
expect(validateGame(game).join('\n')).toMatch(/not reachable/);
|
||||
});
|
||||
|
||||
it('rejects a labyrinth with ragged rows or the wrong number of lanterns', () => {
|
||||
const ragged = structuredClone(labyrinth());
|
||||
ragged.grid[1] = ragged.grid[1] + '#';
|
||||
expect(validateGame(ragged).join('\n')).toMatch(/same length/);
|
||||
|
||||
const fewer = structuredClone(labyrinth());
|
||||
fewer.grid[7] = '#...#.T.#.#';
|
||||
expect(validateGame(fewer).join('\n')).toMatch(/exactly 3 K/);
|
||||
});
|
||||
|
||||
it('rejects a sync bank with fewer than 15 questions', () => {
|
||||
const game = structuredClone(sync());
|
||||
game.match = game.match.slice(0, 14);
|
||||
expect(validateGame(game).join('\n')).toMatch(/at least 15/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rooms', () => {
|
||||
it('makes 5-char codes with no confusable characters', () => {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
const code = makeCode();
|
||||
expect(code).toMatch(/^[A-Z2-9]{5}$/);
|
||||
expect(code).not.toMatch(/[0O1I]/);
|
||||
}
|
||||
expect(CODE_ALPHABET).not.toMatch(/[0O1I]/);
|
||||
});
|
||||
|
||||
it('expires rooms after 24h idle', () => {
|
||||
const store = new RoomStore(null);
|
||||
const { room } = store.create('in-sync', 'duo', 0);
|
||||
expect(store.sweep(ROOM_TTL_MS - 1)).toBe(0);
|
||||
expect(store.sweep(ROOM_TTL_MS + 1)).toBe(1);
|
||||
expect(store.get(room.code)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
// End-to-end over real sockets: two clients complete The Clockmaker's Attic.
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { io as connect, type Socket } from 'socket.io-client';
|
||||
import type { JoinAck, RoomState, StoryView } from '@two-keys/shared';
|
||||
import { createApp } from '../src/app';
|
||||
|
||||
const app = createApp({ dataFile: null });
|
||||
let url = '';
|
||||
const sockets: Socket[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
url = `http://localhost:${await app.listen(0)}`;
|
||||
});
|
||||
afterAll(async () => {
|
||||
sockets.forEach((s) => s.close());
|
||||
await app.close();
|
||||
});
|
||||
|
||||
function client() {
|
||||
const socket = connect(url, { transports: ['websocket'], forceNew: true });
|
||||
sockets.push(socket);
|
||||
const seen: RoomState[] = [];
|
||||
let latest: RoomState | undefined;
|
||||
let wake = () => {};
|
||||
socket.on('room:state', (state: RoomState) => {
|
||||
latest = state;
|
||||
seen.push(state);
|
||||
wake();
|
||||
});
|
||||
return {
|
||||
socket,
|
||||
seen,
|
||||
get state() {
|
||||
return latest!;
|
||||
},
|
||||
ack: (event: string, payload: object) =>
|
||||
new Promise<JoinAck>((resolve) => socket.emit(event, payload, resolve)),
|
||||
/** Resolves once a received state satisfies the predicate. */
|
||||
async until(predicate: (s: RoomState) => boolean): Promise<RoomState> {
|
||||
const deadline = Date.now() + 5000;
|
||||
while (!(latest && predicate(latest))) {
|
||||
if (Date.now() > deadline) throw new Error('timed out waiting for room state');
|
||||
await new Promise<void>((resolve) => {
|
||||
wake = resolve;
|
||||
setTimeout(resolve, 100);
|
||||
});
|
||||
}
|
||||
return latest;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('two players over sockets', () => {
|
||||
it('create, join, pick roles, play Clockmaker\'s Attic to the end, and reconnect', async () => {
|
||||
const game = app.games.get('clockmakers-attic')!;
|
||||
if (game.engine !== 'story' || game.finale.type !== 'escape') throw new Error('unexpected game shape');
|
||||
|
||||
const a = client();
|
||||
const b = client();
|
||||
|
||||
const created = await a.ack('room:create', { gameId: game.id });
|
||||
if (!created.ok) throw new Error(created.message);
|
||||
expect(created.code).toMatch(/^[A-Z2-9]{5}$/);
|
||||
|
||||
a.socket.emit('room:pickRole', { role: 'A' });
|
||||
const joined = await b.ack('room:join', { code: created.code.toLowerCase() });
|
||||
if (!joined.ok) throw new Error(joined.message);
|
||||
await b.until((s) => s.you.seat === 'B'); // partner gets the other role
|
||||
|
||||
// A third player can't get in.
|
||||
const c = client();
|
||||
expect(await c.ack('room:join', { code: created.code })).toMatchObject({ ok: false, code: 'room_full' });
|
||||
expect(await c.ack('room:join', { code: 'ZZZZZ' })).toMatchObject({ ok: false, code: 'not_found' });
|
||||
|
||||
a.socket.emit('room:ready');
|
||||
b.socket.emit('room:ready');
|
||||
await a.until((s) => s.phase === 'playing');
|
||||
await b.until((s) => s.phase === 'playing');
|
||||
|
||||
for (const [i, chapter] of game.chapters.entries()) {
|
||||
// Either player can submit; alternate.
|
||||
const [me, partner] = i % 2 ? [b, a] : [a, b];
|
||||
me.socket.emit('lock:submit', { lockId: chapter.lock.id, value: chapter.lock.answers[0] });
|
||||
await partner.until((s) => s.keys.length === i + 1);
|
||||
partner.socket.emit('chapter:continue');
|
||||
await me.until((s) => (s.views[s.you.seat as 'A' | 'B'] as StoryView).currentChapter === i + 1);
|
||||
}
|
||||
|
||||
// Refresh mid-game: a new socket with the same token gets the same seat and progress.
|
||||
b.socket.close();
|
||||
await a.until((s) => s.partner?.online === false);
|
||||
const b2 = client();
|
||||
expect(await b2.ack('room:join', { code: created.code, playerToken: joined.playerToken })).toMatchObject({ ok: true });
|
||||
const restored = await b2.until((s) => s.phase === 'playing');
|
||||
expect(restored.you.seat).toBe('B');
|
||||
expect(restored.keys).toHaveLength(game.chapters.length);
|
||||
expect((restored.views.B as StoryView).finale?.type).toBe('escape');
|
||||
|
||||
b2.socket.emit('lock:submit', { lockId: game.finale.lock.id, value: 'forever' });
|
||||
const done = await a.until((s) => s.phase === 'finished');
|
||||
expect(done.result).toMatchObject({ success: true, keysEarned: 3, totalKeys: 3, hintsUsed: 0 });
|
||||
expect(done.result?.ending).toContain('FOREVER');
|
||||
|
||||
// Nothing A ever received contained B's clues, or any answers.
|
||||
const everything = JSON.stringify(a.seen);
|
||||
for (const chapter of game.chapters) {
|
||||
for (const clue of chapter.clues.B) expect(everything).not.toContain(JSON.stringify(clue.title));
|
||||
}
|
||||
expect(everything).not.toContain('"answers"');
|
||||
expect(everything).not.toContain(JSON.stringify(game.finale.clues.B[0].title));
|
||||
});
|
||||
|
||||
it('couch mode: one device holds both roles and sees both views', async () => {
|
||||
const solo = client();
|
||||
const created = await solo.ack('room:create', { gameId: 'labyrinth-of-lanterns', mode: 'couch' });
|
||||
if (!created.ok) throw new Error(created.message);
|
||||
solo.socket.emit('room:ready');
|
||||
const state = await solo.until((s) => s.phase === 'playing');
|
||||
expect(state.you.seat).toBe('both');
|
||||
expect(Object.keys(state.views).sort()).toEqual(['A', 'B']);
|
||||
|
||||
solo.socket.emit('maze:move', { dir: 'e', asRole: 'B' });
|
||||
await solo.until((s) => (s.views.B as { moves: number }).moves === 1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { Dir } from '@two-keys/shared';
|
||||
import {
|
||||
continueDefuse,
|
||||
defuseAction,
|
||||
generateDevice,
|
||||
isSolvable,
|
||||
remainingAt,
|
||||
solveButton,
|
||||
solveKeypad,
|
||||
solveWires,
|
||||
tickDefuse,
|
||||
timerText,
|
||||
type DefuseState,
|
||||
} from '../src/engines/defuse';
|
||||
import { DELTAS, cellAt, findCells, moveExplorer, type LabyrinthState } from '../src/engines/labyrinth';
|
||||
import { answerSync, continueSync, type SyncState } from '../src/engines/sync';
|
||||
import { clock, defuse, labyrinth, playingRoom, sync } from './helpers';
|
||||
|
||||
describe('defuse solver', () => {
|
||||
const game = defuse();
|
||||
|
||||
it.each(game.fixtures.wires)('wires fixture %#', (f) => {
|
||||
expect(solveWires(f.serial, f.wires)).toEqual(f.expect);
|
||||
});
|
||||
it.each(game.fixtures.button)('button fixture %#', (f) => {
|
||||
expect(solveButton(f)).toEqual(f.expect);
|
||||
});
|
||||
it.each(game.fixtures.keypad)('keypad fixture %#', (f) => {
|
||||
expect(solveKeypad(f.symbols, game.modules.keypad.columns)).toEqual(f.expect);
|
||||
});
|
||||
|
||||
it('never generates a device the solver cannot solve', () => {
|
||||
for (let seed = 1; seed <= 2000; seed++) {
|
||||
const device = generateDevice(game, 2, seed);
|
||||
expect(isSolvable(game, device), `seed ${seed}`).toBe(true);
|
||||
expect(device.serial).toMatch(/^[A-Z0-9]{5}\d$/);
|
||||
expect(device.wires!.colors.length).toBeGreaterThanOrEqual(3);
|
||||
expect(device.wires!.colors.length).toBeLessThanOrEqual(5);
|
||||
expect(device.keypad!.symbols).toHaveLength(4);
|
||||
}
|
||||
});
|
||||
|
||||
it('is deterministic per seed and only builds the modules of the level', () => {
|
||||
expect(generateDevice(game, 2, 42)).toEqual(generateDevice(game, 2, 42));
|
||||
const lvl1 = generateDevice(game, 0, 42);
|
||||
expect(lvl1.wires).toBeDefined();
|
||||
expect(lvl1.button).toBeUndefined();
|
||||
expect(lvl1.keypad).toBeUndefined();
|
||||
});
|
||||
|
||||
it('formats the timer like the device shows it', () => {
|
||||
expect(timerText(180)).toBe('3:00');
|
||||
expect(timerText(64.2)).toBe('1:05');
|
||||
expect(timerText(-3)).toBe('0:00');
|
||||
});
|
||||
});
|
||||
|
||||
describe('defuse level flow', () => {
|
||||
const game = defuse();
|
||||
|
||||
/** Solves whatever is on the device, using only the solver. */
|
||||
function solveAll(room: ReturnType<typeof playingRoom>, t: ReturnType<typeof clock>) {
|
||||
const s = room.engine as DefuseState;
|
||||
const d = s.device!;
|
||||
if (d.wires) defuseAction(game, t.ctx(100), 'A', 'wires', solveWires(d.serial, d.wires.colors));
|
||||
if (d.keypad) {
|
||||
for (const symbol of solveKeypad(d.keypad.symbols, game.modules.keypad.columns)!) {
|
||||
defuseAction(game, t.ctx(100), 'A', 'keypad', { type: 'press', symbol });
|
||||
}
|
||||
}
|
||||
if (d.button) {
|
||||
const solution = solveButton({ ...d.button, batteries: d.batteries });
|
||||
if (solution.type === 'tap') {
|
||||
defuseAction(game, t.ctx(100), 'A', 'button', { type: 'tap' });
|
||||
} else {
|
||||
defuseAction(game, t.ctx(100), 'A', 'button', { type: 'hold' });
|
||||
// Wait until the server's own timer shows the digit, then let go.
|
||||
for (let i = 0; i < 400; i++) {
|
||||
if (timerText(remainingAt(s, t.now)).includes(String(solution.releaseDigit))) break;
|
||||
t.ctx(500);
|
||||
}
|
||||
defuseAction(game, t.ctx(0), 'A', 'button', { type: 'release' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('clears all three levels for a key each and finishes the game', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
for (let level = 0; level < game.levels.length; level++) {
|
||||
expect(continueDefuse(game, t.ctx()).ok).toBe(true); // start
|
||||
solveAll(room, t);
|
||||
const s = room.engine as DefuseState;
|
||||
expect(s.strikes, `level ${level}`).toBe(0);
|
||||
expect(s.status).toBe('cleared');
|
||||
if (level < game.levels.length - 1) continueDefuse(game, t.ctx());
|
||||
}
|
||||
expect(room.keys).toEqual(game.levels.map((l) => l.keyName));
|
||||
expect(room.phase).toBe('finished');
|
||||
expect(room.result?.success).toBe(true);
|
||||
});
|
||||
|
||||
it('strikes speed the clock up by 25% and three strikes blow the level without losing keys', () => {
|
||||
const room = playingRoom(game);
|
||||
room.keys.push('Earlier Key');
|
||||
const t = clock(room);
|
||||
continueDefuse(game, t.ctx());
|
||||
const s = room.engine as DefuseState;
|
||||
const right = solveWires(s.device!.serial, s.device!.wires!.colors).index;
|
||||
const wrong = right === 1 ? 2 : 1;
|
||||
|
||||
defuseAction(game, t.ctx(), 'A', 'wires', { type: 'cut', index: wrong });
|
||||
expect(s.strikes).toBe(1);
|
||||
expect(s.clock!.speed).toBeCloseTo(1.25);
|
||||
const before = remainingAt(s, t.now);
|
||||
expect(before - remainingAt(s, t.now + 4000)).toBeCloseTo(5);
|
||||
|
||||
expect(defuseAction(game, t.ctx(), 'B', 'wires', { type: 'cut', index: right }).ok).toBe(false); // Expert can't cut
|
||||
defuseAction(game, t.ctx(), 'A', 'wires', { type: 'cut', index: wrong });
|
||||
defuseAction(game, t.ctx(), 'A', 'wires', { type: 'cut', index: wrong });
|
||||
expect(s.status).toBe('exploded');
|
||||
expect(s.failReason).toBe('strikes');
|
||||
expect(room.keys).toEqual(['Earlier Key']);
|
||||
|
||||
const oldSeed = s.seed;
|
||||
continueDefuse(game, t.ctx()); // retry → briefing with a new seed
|
||||
expect(s).toMatchObject({ status: 'ready', level: 0, strikes: 0, device: null });
|
||||
expect(s.seed).not.toBe(oldSeed);
|
||||
});
|
||||
|
||||
it('explodes when the clock runs out', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
continueDefuse(game, t.ctx());
|
||||
expect(tickDefuse(t.ctx(10_000))).toBe(false);
|
||||
expect(tickDefuse(t.ctx(game.levels[0].timeSeconds * 1000))).toBe(true);
|
||||
expect(room.engine).toMatchObject({ status: 'exploded', failReason: 'time' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('sync', () => {
|
||||
const game = sync();
|
||||
|
||||
it('awards a key for 3+ matches, offers one replay otherwise, and never repeats a question', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
const s = room.engine as SyncState;
|
||||
const seen: string[] = [];
|
||||
|
||||
const playRound = (matches: number) => {
|
||||
for (let i = 0; i < game.rules.questionsPerRound; i++) {
|
||||
const q = s.questions[s.q];
|
||||
seen.push(q.id);
|
||||
expect(answerSync(game, t.ctx(), 'A', q.id, 0).ok).toBe(true);
|
||||
expect(answerSync(game, t.ctx(), 'A', q.id, 1).ok).toBe(false); // locked in
|
||||
expect(continueSync(game, t.ctx()).ok).toBe(false); // partner still thinking
|
||||
expect(answerSync(game, t.ctx(), 'B', q.id, i < matches ? 0 : 1).ok).toBe(true);
|
||||
expect(s.status).toBe('reveal');
|
||||
continueSync(game, t.ctx());
|
||||
}
|
||||
expect(s.status).toBe('summary');
|
||||
};
|
||||
|
||||
continueSync(game, t.ctx()); // intro → first question
|
||||
playRound(2); // fail
|
||||
expect(s.earned).toBe(false);
|
||||
continueSync(game, t.ctx()); // replay with fresh questions
|
||||
expect(s).toMatchObject({ round: 0, attempt: 1, status: 'question' });
|
||||
playRound(1); // fail again: no more replays
|
||||
continueSync(game, t.ctx());
|
||||
expect(s).toMatchObject({ round: 1, attempt: 0, status: 'intro' });
|
||||
|
||||
continueSync(game, t.ctx());
|
||||
playRound(3);
|
||||
expect(room.keys).toEqual([game.rounds[1].keyName]);
|
||||
continueSync(game, t.ctx()); // earned → straight to round 3
|
||||
expect(s.round).toBe(2);
|
||||
|
||||
continueSync(game, t.ctx());
|
||||
playRound(5);
|
||||
continueSync(game, t.ctx());
|
||||
expect(room.phase).toBe('finished');
|
||||
expect(room.keys).toHaveLength(2);
|
||||
expect(new Set(seen).size).toBe(seen.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe('labyrinth', () => {
|
||||
const game = labyrinth();
|
||||
const walk = (room: ReturnType<typeof playingRoom>, t: ReturnType<typeof clock>, path: string) =>
|
||||
[...path].map((dir) => moveExplorer(game, t.ctx(), 'B', dir as Dir));
|
||||
|
||||
it('validates every move on the server', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
const s = room.engine as LabyrinthState;
|
||||
expect(s).toMatchObject({ x: 1, y: 1 });
|
||||
expect(moveExplorer(game, t.ctx(), 'B', 'n')).toMatchObject({ ok: false, code: 'wall' });
|
||||
expect(moveExplorer(game, t.ctx(), 'A', 'e')).toMatchObject({ ok: false, code: 'wrong_role' });
|
||||
expect(s).toMatchObject({ x: 1, y: 1, moves: 0 });
|
||||
expect(moveExplorer(game, t.ctx(), 'B', 'e').ok).toBe(true);
|
||||
expect(s).toMatchObject({ x: 2, y: 1, moves: 1 });
|
||||
});
|
||||
|
||||
it('sends the Explorer back to the start on a trap, with a penalty, keys kept', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
const s = room.engine as LabyrinthState;
|
||||
walk(room, t, 'ssss'); // (1,5)
|
||||
walk(room, t, 'ee'); // (3,5)
|
||||
const ctx = t.ctx();
|
||||
moveExplorer(game, ctx, 'B', 'e'); // (4,5) is a trap
|
||||
expect(s).toMatchObject({ x: 1, y: 1, falls: 1 });
|
||||
expect(room.penaltySeconds).toBe(60);
|
||||
expect(ctx.toasts).toEqual([{ to: 'A', message: expect.stringMatching(/fell into a trap/) }]);
|
||||
});
|
||||
|
||||
it('can be completed: three lanterns, then the exit', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
const s = room.engine as LabyrinthState;
|
||||
|
||||
// Breadth-first route planner over safe cells, standing in for a good Navigator.
|
||||
const goTo = (target: { x: number; y: number }) => {
|
||||
const start = `${s.x},${s.y}`;
|
||||
const prev = new Map<string, { from: string; dir: Dir }>();
|
||||
const queue = [{ x: s.x, y: s.y }];
|
||||
const seen = new Set([start]);
|
||||
while (queue.length) {
|
||||
const p = queue.shift()!;
|
||||
for (const dir of Object.keys(DELTAS) as Dir[]) {
|
||||
const n = { x: p.x + DELTAS[dir].x, y: p.y + DELTAS[dir].y };
|
||||
const c = cellAt(game.grid, n.x, n.y);
|
||||
if (c === '#' || c === 'T' || seen.has(`${n.x},${n.y}`)) continue;
|
||||
seen.add(`${n.x},${n.y}`);
|
||||
prev.set(`${n.x},${n.y}`, { from: `${p.x},${p.y}`, dir });
|
||||
queue.push(n);
|
||||
}
|
||||
}
|
||||
const path: Dir[] = [];
|
||||
for (let at = `${target.x},${target.y}`; at !== start; at = prev.get(at)!.from) path.unshift(prev.get(at)!.dir);
|
||||
for (const dir of path) expect(moveExplorer(game, t.ctx(), 'B', dir).ok).toBe(true);
|
||||
};
|
||||
|
||||
const [exit] = findCells(game.grid, 'E');
|
||||
goTo(exit);
|
||||
expect(room.phase).toBe('playing'); // locked without lanterns
|
||||
expect(s.message).toBe(game.explorerView.flavour.exitLocked);
|
||||
|
||||
for (const lantern of game.lanterns) goTo(lantern);
|
||||
expect(room.keys).toEqual(expect.arrayContaining(game.lanterns.map((l) => l.name)));
|
||||
goTo(exit);
|
||||
expect(room.phase).toBe('finished');
|
||||
expect(s.falls).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { loadGames } from '../src/content/loader';
|
||||
import type { DefuseGame, Game, LabyrinthGame, StoryGame, SyncGame } from '../src/content/schemas';
|
||||
import { initEngine } from '../src/engines/index';
|
||||
import { createCtx } from '../src/engines/types';
|
||||
import { RoomStore, type Room } from '../src/rooms/store';
|
||||
|
||||
export const games = loadGames();
|
||||
|
||||
export function getGame<E extends Game['engine']>(id: string, engine: E): Extract<Game, { engine: E }> {
|
||||
const game = games.get(id);
|
||||
if (!game || game.engine !== engine) throw new Error(`no ${engine} game "${id}"`);
|
||||
return game as Extract<Game, { engine: E }>;
|
||||
}
|
||||
|
||||
export const storyGames = [...games.values()].filter((g): g is StoryGame => g.engine === 'story');
|
||||
export const defuse = () => getGame('tick-tock-together', 'defuse') as DefuseGame;
|
||||
export const sync = () => getGame('in-sync', 'sync') as SyncGame;
|
||||
export const labyrinth = () => getGame('labyrinth-of-lanterns', 'labyrinth') as LabyrinthGame;
|
||||
|
||||
/** A room that is already in the `playing` phase for the given game. */
|
||||
export function playingRoom(game: Game, startedAt = 1_000_000): Room {
|
||||
const { room } = new RoomStore(null).create(game.id, 'duo', startedAt);
|
||||
room.players[0].seat = 'A';
|
||||
room.players.push({ token: 'b', seat: 'B', ready: true, viewing: null });
|
||||
room.phase = 'playing';
|
||||
room.startedAt = startedAt;
|
||||
room.engine = initEngine(game);
|
||||
return room;
|
||||
}
|
||||
|
||||
/** A clock for tests: every call to `ctx()` is 3 seconds later, clear of the rate limit. */
|
||||
export function clock(room: Room, start = 1_000_000) {
|
||||
let now = start;
|
||||
return {
|
||||
ctx: (advanceMs = 3000) => createCtx(room, (now += advanceMs)),
|
||||
get now() {
|
||||
return now;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { Role } from '@two-keys/shared';
|
||||
import type { Clue, Lock, StoryGame } from '../src/content/schemas';
|
||||
import { continueDefuse, defuseAction, solveButton, type DefuseState } from '../src/engines/defuse';
|
||||
import type { LabyrinthState } from '../src/engines/labyrinth';
|
||||
import { continueChapter, requestHint, submitLock, type StoryState } from '../src/engines/story';
|
||||
import { answerSync, continueSync, type SyncState } from '../src/engines/sync';
|
||||
import { buildState } from '../src/rooms/state';
|
||||
import type { Room } from '../src/rooms/store';
|
||||
import { clock, defuse, games, labyrinth, playingRoom, storyGames, sync } from './helpers';
|
||||
|
||||
const FORBIDDEN_KEYS = ['answers', 'answer', 'solution', 'fixtures', 'expect', 'failEnding', 'successEnding'];
|
||||
|
||||
function payload(room: Room, role: Role, now = 2_000_000): string {
|
||||
const player = room.players.find((p) => p.seat === role)!;
|
||||
return JSON.stringify(buildState(room, player, games.get(room.gameId)!, () => true, now));
|
||||
}
|
||||
|
||||
function keysOf(value: unknown, out = new Set<string>()): Set<string> {
|
||||
if (value && typeof value === 'object') {
|
||||
for (const [k, v] of Object.entries(value)) {
|
||||
if (!Array.isArray(value)) out.add(k);
|
||||
keysOf(v, out);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const locksOf = (game: StoryGame): Lock[] => [
|
||||
...game.chapters.map((c) => c.lock),
|
||||
...(game.finale.type === 'escape' ? [game.finale.lock] : []),
|
||||
];
|
||||
|
||||
const cluesFor = (game: StoryGame, role: Role): Clue[] => [
|
||||
...game.chapters.flatMap((c) => c.clues[role]),
|
||||
...(game.finale.type === 'escape' ? game.finale.clues[role] : []),
|
||||
];
|
||||
|
||||
describe.each(storyGames.map((g) => [g.id, g] as const))('sanitized story payloads: %s', (_id, game) => {
|
||||
// Walk the whole game, checking both players' payloads at every step.
|
||||
it('never contain answers, unrevealed hints, unearned text, or the other role\'s clues', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
const s = room.engine as StoryState;
|
||||
|
||||
const check = () => {
|
||||
for (const role of ['A', 'B'] as const) {
|
||||
const json = payload(room, role);
|
||||
const other: Role = role === 'A' ? 'B' : 'A';
|
||||
|
||||
for (const key of keysOf(JSON.parse(json))) expect(FORBIDDEN_KEYS, `${role} got key "${key}"`).not.toContain(key);
|
||||
|
||||
// The other role's private clues never arrive, in any chapter.
|
||||
const prefix = (c: Clue) => JSON.stringify(c.body).slice(1, 60);
|
||||
const mine = cluesFor(game, role).map(prefix);
|
||||
for (const clue of cluesFor(game, other)) {
|
||||
expect(json, `${role} can see ${other}'s clue ${clue.id}`).not.toContain(JSON.stringify(clue.title));
|
||||
// (Station Echo hands the same Morse chart to each player in turn.)
|
||||
if (!mine.includes(prefix(clue))) expect(json).not.toContain(prefix(clue));
|
||||
}
|
||||
|
||||
for (const lock of locksOf(game)) {
|
||||
const revealed = s.hints[lock.id] ?? 0;
|
||||
lock.hints.forEach((hint, i) => {
|
||||
if (i >= revealed) expect(json, `${role} got unrevealed hint ${i + 1} of ${lock.id}`).not.toContain(JSON.stringify(hint));
|
||||
});
|
||||
if (!s.solved.includes(lock.id) && lock.successText) {
|
||||
expect(json, `${role} got successText of unsolved ${lock.id}`).not.toContain(JSON.stringify(lock.successText));
|
||||
}
|
||||
// Lock objects carry no answer list at all. (Answer *words* may legitimately
|
||||
// appear inside a player's own clues, so those can't be grepped for.)
|
||||
const sent = (JSON.parse(json).views[role].chapters as { lock: object }[]).map((c) => c.lock);
|
||||
for (const l of sent) expect(Object.keys(l)).not.toContain('answers');
|
||||
}
|
||||
|
||||
// Signal patterns only ever ride on signal clues.
|
||||
const view = JSON.parse(json).views[role];
|
||||
const clues = [...view.chapters.flatMap((c: { clues: Clue[] }) => c.clues), ...(view.finale?.clues ?? [])];
|
||||
for (const clue of clues) if (clue.type !== 'signal') expect(clue.signal).toBeUndefined();
|
||||
|
||||
if (room.phase !== 'finished') {
|
||||
expect(json).not.toContain(JSON.stringify(game.finale.successEnding));
|
||||
if (game.finale.type === 'accusation') expect(json).not.toContain(JSON.stringify(game.finale.reveal));
|
||||
}
|
||||
// Future chapters are not sent ahead of time.
|
||||
expect(view.chapters.length).toBeLessThanOrEqual(Math.min(s.chapter, game.chapters.length - 1) + 1);
|
||||
}
|
||||
};
|
||||
|
||||
check();
|
||||
for (const ch of game.chapters) {
|
||||
requestHint(game, t.ctx(), ch.lock.id);
|
||||
check();
|
||||
submitLock(game, t.ctx(), ch.lock.id, 'wrong');
|
||||
check();
|
||||
submitLock(game, t.ctx(), ch.lock.id, ch.lock.answers[0]);
|
||||
check();
|
||||
continueChapter(game, t.ctx());
|
||||
check();
|
||||
}
|
||||
});
|
||||
|
||||
it('sends each player only their own and shared clues', () => {
|
||||
const room = playingRoom(game);
|
||||
const view = JSON.parse(payload(room, 'A')).views.A;
|
||||
const ids = view.chapters[0].clues.map((c: Clue) => c.id);
|
||||
const ch = game.chapters[0];
|
||||
expect(ids).toEqual([...ch.clues.A, ...ch.clues.shared].map((c) => c.id));
|
||||
expect(JSON.parse(payload(room, 'A')).views.B).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitized payloads: other engines', () => {
|
||||
it('defuse: the Technician never gets the manual, the Expert never gets the device', () => {
|
||||
const game = defuse();
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
continueDefuse(game, t.ctx());
|
||||
const s = room.engine as DefuseState;
|
||||
|
||||
const tech = payload(room, 'A', t.now);
|
||||
const expert = payload(room, 'B', t.now);
|
||||
expect(tech).not.toContain('Bomb Defusal Manual');
|
||||
expect(keysOf(JSON.parse(tech))).not.toContain('manual');
|
||||
expect(tech).toContain(s.device!.serial);
|
||||
|
||||
expect(expert).toContain('Bomb Defusal Manual');
|
||||
expect(expert).not.toContain(s.device!.serial);
|
||||
for (const key of ['device', 'serial', 'batteries', 'wires', 'modules', 'strip', 'seed']) {
|
||||
expect(keysOf(JSON.parse(expert)), `expert got "${key}"`).not.toContain(key);
|
||||
}
|
||||
for (const json of [tech, expert]) {
|
||||
for (const key of FORBIDDEN_KEYS) expect(keysOf(JSON.parse(json))).not.toContain(key);
|
||||
expect(keysOf(JSON.parse(json))).not.toContain('seed');
|
||||
}
|
||||
});
|
||||
|
||||
it('defuse: the strip colour is only sent while the button is held', () => {
|
||||
const game = defuse();
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
const s = room.engine as DefuseState;
|
||||
s.level = 1;
|
||||
// Find a seed whose button has to be held.
|
||||
for (s.seed = 1; ; s.seed++) {
|
||||
s.status = 'ready';
|
||||
continueDefuse(game, t.ctx());
|
||||
if (solveButton({ ...s.device!.button!, batteries: s.device!.batteries }).type === 'hold') break;
|
||||
}
|
||||
const button = () => JSON.parse(payload(room, 'A', t.now)).views.A.device.modules.find((m: { id: string }) => m.id === 'button');
|
||||
expect(button().strip).toBeNull();
|
||||
defuseAction(game, t.ctx(100), 'A', 'button', { type: 'hold' });
|
||||
expect(button()).toMatchObject({ holding: true, strip: s.device!.button!.strip });
|
||||
});
|
||||
|
||||
it('sync: the partner\'s answer is hidden until both have answered', () => {
|
||||
const game = sync();
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
continueSync(game, t.ctx());
|
||||
const q = (room.engine as SyncState).questions[0];
|
||||
answerSync(game, t.ctx(), 'A', q.id, 2);
|
||||
|
||||
const b = JSON.parse(payload(room, 'B')).views.B;
|
||||
expect(b).toMatchObject({ myAnswer: null, partnerAnswered: true, reveal: null });
|
||||
expect(JSON.parse(payload(room, 'A')).views.A).toMatchObject({ myAnswer: 2, partnerAnswered: false, reveal: null });
|
||||
|
||||
answerSync(game, t.ctx(), 'B', q.id, 1);
|
||||
expect(JSON.parse(payload(room, 'B')).views.B.reveal).toEqual({ A: 2, B: 1, match: false });
|
||||
});
|
||||
|
||||
it('labyrinth: the Explorer never gets the map, the Navigator never gets the position', () => {
|
||||
const game = labyrinth();
|
||||
const room = playingRoom(game);
|
||||
const s = room.engine as LabyrinthState;
|
||||
Object.assign(s, { x: 5, y: 3 }); // standing on the crescent moon
|
||||
|
||||
const explorer = JSON.parse(payload(room, 'B')).views.B;
|
||||
for (const key of ['grid', 'glyphs', 'lanterns', 'x', 'y', 'traps']) {
|
||||
expect(keysOf(explorer), `explorer got "${key}"`).not.toContain(key);
|
||||
}
|
||||
expect(explorer.glyphLabel).toMatch(/crescent moon/);
|
||||
expect(explorer.open).toEqual({ n: true, e: false, s: false, w: true });
|
||||
expect(JSON.stringify(explorer)).not.toContain('#');
|
||||
|
||||
const navigator = JSON.parse(payload(room, 'A')).views.A;
|
||||
expect(navigator.grid).toEqual(game.grid);
|
||||
// The only coordinates the Navigator has are the static map features.
|
||||
const { glyphs, lanterns, grid, ...rest } = navigator;
|
||||
expect(keysOf(rest)).not.toContain('x');
|
||||
expect(keysOf(rest)).not.toContain('y');
|
||||
expect(Object.keys(navigator)).not.toEqual(expect.arrayContaining(['open', 'glyphLabel', 'atExit', 'message']));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { Role } from '@two-keys/shared';
|
||||
import type { StoryGame } from '../src/content/schemas';
|
||||
import {
|
||||
agreeAccusation,
|
||||
continueChapter,
|
||||
proposeAccusation,
|
||||
requestHint,
|
||||
submitAccusation,
|
||||
submitLock,
|
||||
type StoryState,
|
||||
} from '../src/engines/story';
|
||||
import { computeResult } from '../src/rooms/state';
|
||||
import { clock, getGame, playingRoom, storyGames } from './helpers';
|
||||
|
||||
const correctAccusation = (game: StoryGame) => {
|
||||
if (game.finale.type !== 'accusation') throw new Error('not an accusation finale');
|
||||
return Object.fromEntries(game.finale.questions.map((q) => [q.id, q.answer]));
|
||||
};
|
||||
|
||||
describe.each(storyGames.map((g) => [g.id, g] as const))('story: %s', (_id, game) => {
|
||||
it('accepts every answer listed in the YAML, for every lock', () => {
|
||||
const locks = [...game.chapters.map((c) => c.lock), ...(game.finale.type === 'escape' ? [game.finale.lock] : [])];
|
||||
for (const lock of locks) {
|
||||
for (const answer of lock.answers) {
|
||||
// Fresh room fast-forwarded to this lock.
|
||||
const room = playingRoom(game);
|
||||
const s = room.engine as StoryState;
|
||||
const index = game.chapters.findIndex((c) => c.lock.id === lock.id);
|
||||
s.chapter = index === -1 ? game.chapters.length : index;
|
||||
const t = clock(room);
|
||||
expect(submitLock(game, t.ctx(), lock.id, answer), `${lock.id}: ${answer}`).toEqual({ ok: true, correct: true });
|
||||
// Sloppy formatting is fine too.
|
||||
const room2 = playingRoom(game);
|
||||
(room2.engine as StoryState).chapter = s.chapter;
|
||||
const sloppy = ` ${answer.toLowerCase().split('').join(' ')}! `;
|
||||
expect(submitLock(game, clock(room2).ctx(), lock.id, sloppy).ok && true).toBe(true);
|
||||
expect((room2.engine as StoryState).solved).toContain(lock.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('plays start to finish and earns one key per chapter', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
for (const ch of game.chapters) {
|
||||
expect(submitLock(game, t.ctx(), ch.lock.id, 'definitely wrong')).toEqual({ ok: true, correct: false });
|
||||
expect(submitLock(game, t.ctx(), ch.lock.id, ch.lock.answers[0])).toEqual({ ok: true, correct: true });
|
||||
expect(continueChapter(game, t.ctx()).ok).toBe(true);
|
||||
}
|
||||
expect(room.keys).toEqual(game.chapters.map((c) => c.lock.keyName));
|
||||
|
||||
if (game.finale.type === 'escape') {
|
||||
expect(submitLock(game, t.ctx(), game.finale.lock.id, game.finale.lock.answers[0])).toMatchObject({ correct: true });
|
||||
} else {
|
||||
expect(proposeAccusation(game, t.ctx(), 'A', correctAccusation(game)).ok).toBe(true);
|
||||
expect(submitAccusation(game, t.ctx()).ok).toBe(false); // not agreed yet
|
||||
expect(agreeAccusation(game, t.ctx(), 'A').ok).toBe(false); // can't agree with yourself
|
||||
expect(agreeAccusation(game, t.ctx(), 'B').ok).toBe(true);
|
||||
expect(submitAccusation(game, t.ctx())).toMatchObject({ correct: true });
|
||||
}
|
||||
expect(room.phase).toBe('finished');
|
||||
expect(room.result).toMatchObject({ success: true, ending: game.finale.successEnding });
|
||||
expect(room.wrongGuesses).toBe(game.chapters.length);
|
||||
expect(computeResult(room, game)).toMatchObject({ success: true, keysEarned: game.chapters.length });
|
||||
});
|
||||
});
|
||||
|
||||
describe('story rules', () => {
|
||||
const game = getGame('vineyard-hollow', 'story');
|
||||
const lock = game.chapters[0].lock;
|
||||
|
||||
it('rate-limits to one submission per 2s per lock', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
expect(submitLock(game, t.ctx(), lock.id, '0000')).toMatchObject({ ok: true, correct: false });
|
||||
expect(submitLock(game, t.ctx(500), lock.id, lock.answers[0])).toMatchObject({ ok: false, code: 'rate_limited' });
|
||||
expect(submitLock(game, t.ctx(2000), lock.id, lock.answers[0])).toMatchObject({ ok: true, correct: true });
|
||||
});
|
||||
|
||||
it('only accepts the lock that is currently open', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
const next = game.chapters[1].lock;
|
||||
expect(submitLock(game, t.ctx(), next.id, next.answers[0])).toMatchObject({ ok: false, code: 'lock_closed' });
|
||||
submitLock(game, t.ctx(), lock.id, lock.answers[0]);
|
||||
// Solved but not continued: neither lock is open.
|
||||
expect(submitLock(game, t.ctx(), next.id, next.answers[0])).toMatchObject({ ok: false });
|
||||
expect(continueChapter(game, t.ctx()).ok).toBe(true);
|
||||
expect(continueChapter(game, t.ctx()).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('reveals hints in order with a 2:00 penalty each', () => {
|
||||
const room = playingRoom(game);
|
||||
const t = clock(room);
|
||||
for (let tier = 1; tier <= 3; tier++) {
|
||||
expect(requestHint(game, t.ctx(), lock.id).ok).toBe(true);
|
||||
expect((room.engine as StoryState).hints[lock.id]).toBe(tier);
|
||||
}
|
||||
expect(requestHint(game, t.ctx(), lock.id).ok).toBe(false);
|
||||
expect(room.hintsUsed).toBe(3);
|
||||
expect(room.penaltySeconds).toBe(360);
|
||||
});
|
||||
|
||||
it('fails the case after maxAttempts wrong accusations without saying which part was wrong', () => {
|
||||
if (game.finale.type !== 'accusation') throw new Error('expected accusation');
|
||||
const room = playingRoom(game);
|
||||
(room.engine as StoryState).chapter = game.chapters.length;
|
||||
const t = clock(room);
|
||||
const wrong = { ...correctAccusation(game), who: 'clara' };
|
||||
|
||||
for (let attempt = 1; attempt <= game.finale.maxAttempts; attempt++) {
|
||||
const by: Role = attempt % 2 ? 'A' : 'B';
|
||||
expect(proposeAccusation(game, t.ctx(), by, { who: 'clara' }).ok).toBe(false); // incomplete
|
||||
proposeAccusation(game, t.ctx(), by, wrong);
|
||||
agreeAccusation(game, t.ctx(), by === 'A' ? 'B' : 'A');
|
||||
const ctx = t.ctx();
|
||||
expect(submitAccusation(game, ctx)).toMatchObject({ ok: true, correct: false });
|
||||
if (attempt < game.finale.maxAttempts) {
|
||||
expect(ctx.toasts.map((x) => x.message).join()).toMatch(/Not quite\. 1 attempt left/);
|
||||
expect(room.phase).toBe('playing');
|
||||
}
|
||||
}
|
||||
expect(room.phase).toBe('finished');
|
||||
expect(room.result).toEqual({ success: false, ending: game.finale.failEnding, reveal: game.finale.reveal });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user