클루: 규칙·컴퓨터 상대·화면·테스트

- 규칙 모듈 packages/games/src/clue: 3~6명, 용의자 6·흉기 6·방 9, 봉투 3장, 나머지는 같은 장수로
  나누고 남는 카드는 공개(원작). 9개 방 + 복도를 거리 표로 단순화한 저택(비밀 통로 부엌↔서재,
  온실↔라운지), 주사위 2개 합만큼 이동해 닿는 방에 들어가거나 먼 방 쪽으로 걸어가기, 빠른 이동 옵션.
  추리 시 용의자 말·흉기 이동과 불려 온 사람의 제자리 추리, 다음 사람부터 반증(반증자가 직접 고름,
  보여 준 카드는 두 사람만), 고발(틀리면 탈락하되 반증은 계속, 모두 틀리면 무승부).
  카드 id(card-*)와 추리 이름을 나눠 view 누출 검사가 의미 있게, 이벤트에는 카드 없음.
  시간 초과는 차례를 통째로 자동 진행, 반증은 첫 카드 자동, 나가면 카드 공개.
- 컴퓨터 상대(bot.ts): 소거 노트(내 카드·공개·받은 카드 → 못 보여 준 사람·손패 수 → "셋 중 하나"
  제약·틀린 고발), 단계가 높을수록 깊게, 확실할 때만 고발, 모르는 카드로 추리, 모르는 방으로 이동.
- 화면 apps/web/src/games/clue: 저택 지도(말·흉기·거리·통로), 주사위·방 고르기, 추리/고발 칩,
  반증 카드 고르기, 내 카드·공개 카드, 추리 노트(localStorage, 방 코드+게임 번호), 추리 기록.
- 등록(GAMES, 카탈로그, BOT_GAMES, BOT_STRATEGIES, 화면 레지스트리, 아이콘·분류), 문서
  docs/games/clue.md, E2E 계획(PC 1 + 휴대폰 2, 끝까지).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-12 22:27:42 +09:00
parent b98775b0a6
commit c9f81804cf
21 changed files with 3171 additions and 2 deletions

View File

@@ -7,6 +7,7 @@
".": "./src/index.ts",
"./rummikub/rules": "./src/rummikub/rules.ts",
"./marble/board": "./src/marble/board.ts",
"./clue/board": "./src/clue/board.ts",
"./bots/luck": "./src/bots/luck.ts",
"./*": "./src/*/index.ts"
},

View File

@@ -31,6 +31,7 @@ import { cockroachPokerBot } from '../cockroach-poker/bot';
import { ninetyNineBot } from '../ninety-nine/bot';
import { mafiaBot } from '../mafia/bot';
import { appleBot } from '../apple/bot';
import { clueBot } from '../clue/bot';
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
@@ -60,6 +61,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
'las-vegas': lasVegasBot,
'cockroach-poker': cockroachPokerBot,
'ninety-nine': ninetyNineBot,
clue: clueBot,
};
/** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */

View File

@@ -0,0 +1,130 @@
/**
* 클루 cards and the simplified mansion map (docs/games/clue.md §3, §5.2). Pure data + distance helpers, no zod, so the
* screen can import it cheaply.
*/
// ---------------------------------------------------------------- cards
/** Suspects in the official turn order (스칼렛 first, then clockwise round the board). */
export const SUSPECTS = ['scarlet', 'mustard', 'white', 'green', 'peacock', 'plum'] as const;
export const WEAPONS = ['candlestick', 'dagger', 'pipe', 'revolver', 'rope', 'wrench'] as const;
export const ROOMS = ['kitchen', 'ballroom', 'conservatory', 'dining', 'billiard', 'library', 'lounge', 'hall', 'study'] as const;
export type Suspect = (typeof SUSPECTS)[number];
export type Weapon = (typeof WEAPONS)[number];
export type Room = (typeof ROOMS)[number];
export type Item = Suspect | Weapon | Room;
export type Category = 'suspect' | 'weapon' | 'room';
export const ITEMS: readonly Item[] = [...SUSPECTS, ...WEAPONS, ...ROOMS];
export const CATEGORY_ITEMS: Record<Category, readonly Item[]> = { suspect: SUSPECTS, weapon: WEAPONS, room: ROOMS };
export const SUSPECT_KO: Record<Suspect, string> = {
scarlet: '스칼렛',
mustard: '머스터드 대령',
white: '화이트 부인',
green: '그린 목사',
peacock: '피콕 부인',
plum: '플럼 교수',
};
export const WEAPON_KO: Record<Weapon, string> = {
candlestick: '촛대',
dagger: '단검',
pipe: '납 파이프',
revolver: '권총',
rope: '밧줄',
wrench: '스패너',
};
export const ROOM_KO: Record<Room, string> = {
kitchen: '부엌',
ballroom: '무도회장',
conservatory: '온실',
dining: '식당',
billiard: '당구장',
library: '도서실',
lounge: '라운지',
hall: '홀',
study: '서재',
};
export const ITEM_KO: Record<Item, string> = { ...SUSPECT_KO, ...WEAPON_KO, ...ROOM_KO };
export const categoryOf = (x: Item): Category =>
(SUSPECTS as readonly string[]).includes(x) ? 'suspect' : (WEAPONS as readonly string[]).includes(x) ? 'weapon' : 'room';
export const isItem = (x: unknown): x is Item => typeof x === 'string' && (ITEMS as readonly string[]).includes(x);
/**
* Card ids ('card-rope') differ from the item names said aloud in suggestions ('rope'), so a card id only ever appears
* in a view where the viewer may know who holds it: own hand, a card shown to / by the viewer, public cards, and
* everything after the game. The leak tests look for these ids.
*/
export const cardId = (x: Item): string => `card-${x}`;
export const itemOf = (id: string): Item => id.slice(5) as Item;
// ---------------------------------------------------------------- mansion (simplified map, docs §5.2)
/** Start squares in the hallway, one per suspect (near the same rooms as on the original board). */
export type StartNode = `start-${Suspect}`;
export type MapNode = Room | StartNode;
export const startOf = (x: Suspect): StartNode => `start-${x}`;
/** Corridor steps between neighbouring places; every other distance is the shortest path over these. */
export const CORRIDORS: readonly (readonly [MapNode, MapNode, number])[] = [
['kitchen', 'ballroom', 7],
['ballroom', 'conservatory', 4],
['conservatory', 'billiard', 7],
['billiard', 'library', 4],
['library', 'study', 7],
['study', 'hall', 4],
['hall', 'lounge', 8],
['lounge', 'dining', 4],
['dining', 'kitchen', 6],
['dining', 'ballroom', 7],
['ballroom', 'billiard', 6],
['dining', 'hall', 6],
['hall', 'library', 7],
['start-scarlet', 'lounge', 7],
['start-scarlet', 'hall', 7],
['start-mustard', 'lounge', 6],
['start-mustard', 'dining', 7],
['start-white', 'kitchen', 8],
['start-white', 'ballroom', 6],
['start-green', 'ballroom', 6],
['start-green', 'conservatory', 8],
['start-peacock', 'conservatory', 7],
['start-peacock', 'billiard', 6],
['start-plum', 'library', 6],
['start-plum', 'study', 8],
];
/** Official secret passages between opposite corner rooms. */
export const PASSAGES: Partial<Record<Room, Room>> = { kitchen: 'study', study: 'kitchen', conservatory: 'lounge', lounge: 'conservatory' };
const NODES: MapNode[] = [...ROOMS, ...SUSPECTS.map(startOf)];
/** All-pairs shortest corridor distance (Floyd–Warshall over `CORRIDORS`). */
export const DIST: Record<MapNode, Record<MapNode, number>> = (() => {
const d = Object.fromEntries(NODES.map((a) => [a, Object.fromEntries(NODES.map((b) => [b, a === b ? 0 : Infinity]))])) as Record<MapNode, Record<MapNode, number>>;
for (const [a, b, n] of CORRIDORS) d[a][b] = d[b][a] = Math.min(d[a][b], n);
for (const k of NODES) for (const i of NODES) for (const j of NODES) if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j];
return d;
})();
/** Where a suspect token is: standing on a place (room or start square), or out in a corridor between two places. */
export type Pos = { at: MapNode } | { from: MapNode; to: Room; moved: number };
/** Corridor steps from `p` to `room` (0 = already in it). */
export function distTo(p: Pos, room: Room): number {
if ('at' in p) return DIST[p.at][room];
const len = DIST[p.from][p.to];
return Math.min(p.moved + DIST[p.from][room], len - p.moved + DIST[p.to][room]);
}
/** Position after walking `steps` (< distance) along a shortest way from `p` towards `room`. */
export function walkToward(p: Pos, room: Room, steps: number): Pos {
if ('at' in p) return { from: p.at, to: room, moved: steps };
const len = DIST[p.from][p.to];
const back = p.moved + DIST[p.from][room];
const ahead = len - p.moved + DIST[p.to][room];
// Ending exactly on a place's door keeps the token in the corridor (moved 0 or = length): passing a room is not entering it.
if (ahead <= back) return steps <= len - p.moved ? { from: p.from, to: p.to, moved: p.moved + steps } : { from: p.to as MapNode, to: room, moved: steps - (len - p.moved) };
return steps <= p.moved ? { from: p.from, to: p.to, moved: p.moved - steps } : { from: p.from, to: room, moved: steps - p.moved };
}
export const roomAt = (p: Pos): Room | null => ('at' in p && (ROOMS as readonly string[]).includes(p.at) ? (p.at as Room) : null);

View File

@@ -0,0 +1,202 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { ITEMS, SUSPECTS, cardId, clue, type ClueAction, type ClueOptions, type ClueState, type Item, type Room } from './index';
import { deduce, solved, type Owner } from './bot';
/** A game with A to move and hands / case file as written. */
function rigged(hands: Record<string, Item[]>, solution = { suspect: 'plum', weapon: 'rope', room: 'study' } as ClueState['solution'], opts: Partial<ClueOptions> = {}): ClueState {
const players = Object.keys(hands);
const s = clue.setup({ players, options: clue.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
s.solution = solution;
s.hands = Object.fromEntries(players.map((p) => [p, hands[p]!.map(cardId)]));
const used = new Set([...Object.values(hands).flat(), solution.suspect, solution.weapon, solution.room]);
s.publicCards = ITEMS.filter((x) => !used.has(x)).map(cardId);
s.current = players[0]!;
s.suspectOf = Object.fromEntries(players.map((p, i) => [p, SUSPECTS[i]!]));
return s;
}
const apply = (s: ClueState, p: string, a: ClueAction) => {
const v = clue.validate(s, p, a);
if (!v.ok) throw new Error(v.reason);
return clue.apply(s, p, a, { rng: SeededRng.fromSeed(seedN(9)), now: 1 }).state;
};
const decide = (s: ClueState, p: string, seed = 1, level?: number) => {
const r = SeededRng.fromSeed(seedN(seed));
return decideBotAction(clue, s, p, { now: 1, random: () => r.next(), level }) as ClueAction;
};
const owners = (n: ReturnType<typeof deduce>, x: Item) => [...n[x]].sort();
// 3 players, 6 cards each, nothing face up. Case file: plum / rope / study.
const HANDS: Record<string, Item[]> = {
A: ['scarlet', 'mustard', 'candlestick', 'kitchen', 'ballroom', 'conservatory'],
B: ['white', 'dagger', 'pipe', 'dining', 'billiard', 'library'],
C: ['green', 'peacock', 'revolver', 'wrench', 'lounge', 'hall'],
};
describe('clue bot notes', () => {
test('own cards, cards shown to me, the last unknown of a kind', () => {
let s = rigged(HANDS);
// A asks green / rope / kitchen in the kitchen: B passes, C shows green.
s.pos.scarlet = { at: 'kitchen' };
s.phase = { kind: 'suggest', room: 'kitchen' };
s = apply(s, 'A', { type: 'suggest', suspect: 'green', weapon: 'rope' });
s = apply(s, 'C', { type: 'show', card: cardId('green') });
const n = deduce(clue.view(s, 'A'), 'A', 1);
expect(owners(n, 'scarlet')).toEqual(['A']);
expect(owners(n, 'green')).toEqual(['C']);
expect(owners(n, 'white')).toEqual(['B', 'C', 'env']);
// Depth 1 ignores who passed; depth 2 knows B has none of the three.
expect(owners(n, 'rope')).toEqual(['B', 'C', 'env']);
expect(owners(deduce(clue.view(s, 'A'), 'A', 2), 'rope')).toEqual(['C', 'env']);
});
test('depth 3: "one of these three" with the other two ruled out pins the card', () => {
let s = rigged(HANDS);
// B asks plum / dagger / hall and C shows one of them (hall); A only sees that C answered.
s.current = 'B';
s.pos.white = { at: 'hall' };
s.phase = { kind: 'suggest', room: 'hall' };
s = apply(s, 'B', { type: 'suggest', suspect: 'plum', weapon: 'dagger' });
expect(s.phase).toEqual({ kind: 'refute', refuter: 'C' });
s = apply(s, 'C', { type: 'show', card: cardId('hall') });
// A learns elsewhere that B holds the dagger and that plum is not C's (C passed on plum).
s.suggestions.push({ by: 'A', suspect: 'plum', weapon: 'dagger', room: 'kitchen', passed: [], refuter: 'B', shown: cardId('dagger'), auto: false, turnNo: 3 });
s.suggestions.push({ by: 'A', suspect: 'plum', weapon: 'candlestick', room: 'kitchen', passed: ['B', 'C'], refuter: null, shown: null, auto: false, turnNo: 4 });
const v = clue.view(s, 'A');
expect(owners(deduce(v, 'A', 2), 'hall')).toEqual(['B', 'C', 'env']);
expect(owners(deduce(v, 'A', 3), 'hall')).toEqual(['C']);
// Nobody had plum: it is in the envelope.
expect(owners(deduce(v, 'A', 2), 'plum')).toEqual(['env']);
});
test('stays sound: the true owner is never ruled out, at any depth, through whole bot games', () => {
for (let g = 0; g < 12; g++) {
const n = 3 + (g % 4);
const players = Array.from({ length: n }, (_, i) => `bot:${i}:x`);
const rng = SeededRng.fromSeed(seedN(300 + g));
const ch = SeededRng.fromSeed(seedN(400 + g));
let s = clue.setup({ players, options: clue.defaultOptions, rng, now: 0 });
for (let step = 0; step < 4000 && !clue.result(s); step++) {
const p = clue.activePlayers(s)[0]!;
if (step % 5 === 0) {
for (const depth of [1, 2, 3] as const) {
const notes = deduce(clue.view(s, p), p, depth);
for (const x of ITEMS) {
const card = cardId(x);
const truth: Owner | null = s.publicCards.includes(card)
? null
: x === s.solution.suspect || x === s.solution.weapon || x === s.solution.room
? 'env'
: players.find((q) => s.hands[q]!.includes(card))!;
if (truth !== null && !notes[x].has(truth)) throw new Error(`depth ${depth}: ${x} ruled out for ${truth}`);
}
}
}
const a = decideBotAction(clue, s, p, { now: step, random: () => ch.next(), level: [5, 30, 55][g % 3] });
s = clue.apply(s, p, a as ClueAction, { rng, now: step }).state;
}
expect(clue.result(s)).not.toBeNull();
}
});
});
describe('clue bot play', () => {
test('accuses as soon as the case is certain, never before (default strength)', () => {
const s = rigged(HANDS);
// A has seen every card except plum / rope / study.
const shownTo = (by: string, refuter: string, x: Item, room: Room) =>
({ by, suspect: 'scarlet', weapon: 'candlestick', room, passed: [], refuter, shown: cardId(x), auto: false, turnNo: 1 }) as ClueState['suggestions'][number];
const others: Item[] = [...HANDS.B!, ...HANDS.C!];
s.suggestions = others.map((x) => shownTo('A', HANDS.B!.includes(x) ? 'B' : 'C', x, 'kitchen'));
expect(solved(deduce(clue.view(s, 'A'), 'A'))).toEqual({ suspect: 'plum', weapon: 'rope', room: 'study' });
expect(decide(s, 'A')).toEqual({ type: 'accuse', suspect: 'plum', weapon: 'rope', room: 'study' });
// One card short: no accusation.
s.suggestions.pop();
expect(decide(s, 'A').type).not.toBe('accuse');
});
test('suggests cards it knows nothing about; heads for unknown rooms', () => {
const s = rigged(HANDS);
s.pos.scarlet = { at: 'kitchen' };
s.phase = { kind: 'suggest', room: 'kitchen' };
for (let seed = 1; seed <= 8; seed++) {
const a = decide(s, 'A', seed) as Extract<ClueAction, { type: 'suggest' }>;
expect(a.type).toBe('suggest');
expect(HANDS.A).not.toContain(a.suspect);
expect(HANDS.A).not.toContain(a.weapon);
}
// Quick mode: goes to a room it has not ruled out (not one of its own three).
const f = rigged(HANDS, undefined, { movement: 'free' });
for (let seed = 1; seed <= 8; seed++) {
const a = decide(f, 'A', seed) as Extract<ClueAction, { type: 'go' }>;
expect(a.type).toBe('go');
expect(HANDS.A).not.toContain(a.room);
}
// In the kitchen (own card) a corner passage to the unknown study is taken.
const k = rigged(HANDS);
k.pos.scarlet = { at: 'kitchen' };
expect(decide(k, 'A')).toEqual({ type: 'passage' });
});
test('shows the asker a card they have already seen from it', () => {
let s = rigged(HANDS);
s.suggestions.push({ by: 'A', suspect: 'white', weapon: 'rope', room: 'kitchen', passed: [], refuter: 'B', shown: cardId('library'), auto: false, turnNo: 0 });
s.pos.scarlet = { at: 'library' };
s.phase = { kind: 'suggest', room: 'library' };
s = apply(s, 'A', { type: 'suggest', suspect: 'white', weapon: 'dagger' });
expect(s.phase).toEqual({ kind: 'refute', refuter: 'B' });
for (let seed = 1; seed <= 5; seed++) expect(decide(s, 'B', seed)).toEqual({ type: 'show', card: cardId('library') });
});
test('bots-only games end with a correct accusation; the strongest never accuses wrongly', () => {
for (const movement of ['dice', 'free'] as const) {
for (let g = 0; g < 6; g++) {
const n = 3 + (g % 4);
const players = Array.from({ length: n }, (_, i) => `bot:${i}:x`);
const rng = SeededRng.fromSeed(seedN(700 + g));
const ch = SeededRng.fromSeed(seedN(800 + g));
let s = clue.setup({ players, options: clue.optionsSchema.parse({ movement }), rng, now: 0 });
let steps = 0;
for (; steps < 6000 && !clue.result(s); steps++) {
const p = clue.activePlayers(s)[0]!;
s = clue.apply(s, p, decideBotAction(clue, s, p, { now: steps, random: () => ch.next(), level: 60 }) as ClueAction, { rng, now: steps }).state;
}
const r = clue.result(s)!;
expect(r).not.toBeNull();
expect(s.accusations.every((a) => a.correct)).toBe(true);
expect(r.ranking[0]).toHaveLength(1);
}
}
});
test('a strong computer beats two weak ones more often than its share', () => {
let wins = 0;
const G = 24;
for (let g = 0; g < G; g++) {
const players = ['bot:0:x', 'bot:1:x', 'bot:2:x'];
const strong = players[g % 3]!;
const rng = SeededRng.fromSeed(seedN(900 + g));
const ch = SeededRng.fromSeed(seedN(950 + g));
let s = clue.setup({ players, options: clue.defaultOptions, rng, now: 0 });
for (let steps = 0; steps < 6000 && !clue.result(s); steps++) {
const p = clue.activePlayers(s)[0]!;
const a = decideBotAction(clue, s, p, { now: steps, random: () => ch.next(), level: p === strong ? 60 : 5 });
s = clue.apply(s, p, a as ClueAction, { rng, now: steps }).state;
}
if (clue.result(s)?.ranking[0]?.[0] === strong && clue.result(s)!.ranking[0]!.length === 1) wins++;
}
expect(wins).toBeGreaterThan(G / 2);
});
test('with a person who only times out and with every level, games finish', () => {
for (const level of [1, 30, 60]) {
for (let seed = 1; seed <= 3; seed++) {
const r = botPlayout(clue as never, { players: ['human', 'bot:1:x', 'bot:2:x', 'bot:3:x'], seed: seedN(seed * 11 + level), isBot: (p) => p.startsWith('bot:'), maxSteps: 20_000, level });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
}
}
});
});

View File

@@ -0,0 +1,194 @@
/**
* 클루 computer player: a detective's notebook kept from its own view only — own cards, public cards, cards shown to
* it, who could not answer a suggestion, "someone showed one of these three" and wrong accusations. Higher levels use
* more of it (docs/games/clue.md §8.7):
* 1~20 단순 소거: own / public / shown cards, and "the last unknown card of a kind is in the envelope".
* 21~40 + who could not answer, and hand sizes (a full hand owns nothing else).
* 41~60 + "one of these three" constraints and wrong accusations.
* It accuses only when the case file is certain (the weakest sometimes gambles on one of two answers), suggests the
* cards it knows least about, and heads for rooms it has not ruled out.
*/
import type { PlayerId } from '@bg/engine';
import type { BotStrategy } from '../bots/types';
import { best, pick, randomPolicy } from '../bots/policy';
import {
CATEGORY_ITEMS,
ITEMS,
PASSAGES,
ROOMS,
SUSPECTS,
WEAPONS,
categoryOf,
itemOf,
roomAt,
type Category,
type ClueAction,
type ClueView,
type Item,
type Room,
type Suspect,
type Weapon,
} from './index';
/** Who may hold a card: a player or the case file. */
export type Owner = PlayerId | 'env';
export type Notes = Record<Item, Set<Owner>>;
export type Depth = 1 | 2 | 3;
export const depthFor = (level: number | undefined): Depth => (level === undefined || level > 40 ? 3 : level > 20 ? 2 : 1);
/**
* Possible owners of every card that is not face up (public cards get an empty set). Sound: the true owner always
* stays in the set, whatever the depth.
*/
export function deduce(v: ClueView, me: PlayerId, depth: Depth = 3): Notes {
const holders = v.seats.filter((p) => !v.left[p]);
const pub = new Set(v.publicCards.map(itemOf));
const mine = new Set((v.myHand ?? []).map(itemOf));
const notes = {} as Notes;
for (const x of ITEMS) notes[x] = pub.has(x) ? new Set() : mine.has(x) ? new Set([me]) : new Set<Owner>([...holders.filter((p) => p !== me), 'env']);
const constraints: { p: PlayerId; items: Item[] }[] = [];
const notAll: Item[][] = [];
for (const sg of v.suggestions) {
const three: Item[] = [sg.suspect, sg.weapon, sg.room];
if (sg.shown) {
if (sg.by === me && sg.refuter) notes[itemOf(sg.shown)] = new Set([sg.refuter]);
} else if (sg.refuter && sg.refuter !== me) constraints.push({ p: sg.refuter, items: three });
if (depth >= 2) for (const p of sg.passed) for (const x of three) notes[x].delete(p);
}
for (const a of v.accusations) if (!a.correct) notAll.push([a.suspect, a.weapon, a.room]);
const assigned = (x: Item) => (notes[x].size === 1 ? [...notes[x]][0]! : null);
for (let round = 0; round < 30; round++) {
const before = ITEMS.map((x) => notes[x].size).join();
// A kind's card in the envelope rules the others out; the last one that can be there is there.
for (const cat of ['suspect', 'weapon', 'room'] as Category[]) {
const items = CATEGORY_ITEMS[cat];
const inEnv = items.filter((x) => assigned(x) === 'env');
if (inEnv.length) for (const x of items) if (x !== inEnv[0]) notes[x].delete('env');
const can = items.filter((x) => notes[x].has('env'));
if (can.length === 1) notes[can[0]!] = new Set(['env']);
}
if (depth >= 2) {
for (const p of holders) {
if (p === me) continue;
const has = ITEMS.filter((x) => assigned(x) === p);
const could = ITEMS.filter((x) => notes[x].has(p));
const size = v.handCounts[p] ?? 0;
if (has.length >= size) {
for (const x of could) if (assigned(x) !== p) notes[x].delete(p);
} else if (could.length === size) {
for (const x of could) notes[x] = new Set([p]);
}
}
}
if (depth >= 3) {
for (const c of constraints) {
if (c.items.some((x) => assigned(x) === c.p)) continue;
const left = c.items.filter((x) => notes[x].has(c.p));
if (left.length === 1) notes[left[0]!] = new Set([c.p]);
}
for (const three of notAll) {
const inEnv = three.filter((x) => assigned(x) === 'env');
if (inEnv.length === 2) for (const x of three) if (!inEnv.includes(x)) notes[x].delete('env');
}
}
// A card with no owner left means the notes contradict themselves (cannot happen with sound rules); stop here.
if (ITEMS.some((x) => !pub.has(x) && notes[x].size === 0)) break;
if (ITEMS.map((x) => notes[x].size).join() === before) break;
}
return notes;
}
/** Cards of a kind that may still be in the envelope. */
export const envCandidates = <T extends Item>(notes: Notes, items: readonly T[]): T[] => items.filter((x) => notes[x].has('env'));
/** The case file if the notes pin it down. */
export function solved(notes: Notes): { suspect: Suspect; weapon: Weapon; room: Room } | null {
const s = envCandidates(notes, SUSPECTS);
const w = envCandidates(notes, WEAPONS);
const r = envCandidates(notes, ROOMS);
return s.length === 1 && w.length === 1 && r.length === 1 ? { suspect: s[0]!, weapon: w[0]!, room: r[0]! } : null;
}
/** How useful a card is to name in a suggestion: unknown cards first, then ones nobody can show (mine / the envelope). */
function askValue(notes: Notes, x: Item, me: PlayerId): number {
const o = notes[x];
if (o.size > 1) return 10 + o.size + (o.has('env') ? 2 : 0);
if (o.has('env') || o.has(me)) return 4;
return 0;
}
/** Is a room worth suggesting in? Unknown rooms most, then rooms whose card nobody else can show. */
const roomValue = (notes: Notes, r: Room, me: PlayerId) => askValue(notes, r, me);
function accuseIfReady(notes: Notes, level: number | undefined, random: () => number): ClueAction | null {
const sol = solved(notes);
if (sol) return { type: 'accuse', ...sol };
// 쉬움 computers sometimes trust a hunch when only two answers are left.
if (level !== undefined && level <= 20) {
const s = envCandidates(notes, SUSPECTS);
const w = envCandidates(notes, WEAPONS);
const r = envCandidates(notes, ROOMS);
if (s.length * w.length * r.length === 2 && random() < 0.35) return { type: 'accuse', suspect: pick(s, random), weapon: pick(w, random), room: pick(r, random) };
}
return null;
}
/** Chance to ignore the notes for one choice (a person's lapse). */
const slipChance = (level: number | undefined) => (level === undefined ? 0 : Math.max(0, 0.3 - level * 0.005));
export const clueBot: BotStrategy<ClueView, ClueAction> = (input) => {
const { me, view: v, legal, random, level } = input;
const ph = v.phase;
if (ph.kind === 'refute') {
// Show a card this suggester has already seen from me if possible (gives nothing new away), otherwise one I've shown before.
const cards = ph.canShow ?? [];
if (!cards.length) return randomPolicy(input);
const asker = v.suggestions[v.suggestions.length - 1]!.by;
const shownTo = (c: string, who?: PlayerId) => v.suggestions.filter((x) => x.refuter === me && x.shown === c && (!who || x.by === who)).length;
const card = best(cards, (c) => shownTo(c, asker) * 10 + shownTo(c) + (categoryOf(itemOf(c)) === 'room' ? 0.5 : 0), random);
return { type: 'show', card };
}
const notes = deduce(v, me, depthFor(level));
const slip = random() < slipChance(level);
const accuse = ph.kind === 'moveTo' ? null : accuseIfReady(notes, level, random);
if (accuse) return accuse;
const pos = v.pos[v.suspectOf[me]!];
const here = roomAt(pos);
const value = (r: Room) => (slip ? random() * 10 : roomValue(notes, r, me));
switch (ph.kind) {
case 'move': {
if (here && v.movedIn[me] && value(here) >= 10) return { type: 'stay' };
if (v.options.movement === 'free') {
const rooms = ROOMS.filter((r) => r !== here);
return { type: 'go', room: best(rooms, value, random) };
}
const through = here ? PASSAGES[here] : undefined;
if (through && value(through) >= 10) return { type: 'passage' };
return { type: 'roll' };
}
case 'moveTo': {
const d = v.distances!;
const sum = v.dice ? v.dice[0] + v.dice[1] : 0;
const rooms = ROOMS.filter((r) => r !== here);
const reach = rooms.filter((r) => d[r] <= sum);
const top = Math.max(...rooms.map(value));
const goodReach = reach.filter((r) => value(r) >= Math.min(top, 10));
if (goodReach.length) return { type: 'go', room: best(goodReach, (r) => value(r) - d[r] * 0.01, random) };
// Nothing worth it in reach: head for the nearest room worth visiting (or step into any room if none is far).
const worth = rooms.filter((r) => value(r) >= Math.min(top, 10));
const target = best(worth, (r) => -d[r], random);
if (d[target] > sum) return { type: 'walk', room: target };
return reach.length ? { type: 'go', room: best(reach, value, random) } : { type: 'walk', room: target };
}
case 'suggest': {
const ask = (xs: readonly Item[]) => best(xs, (x) => (slip ? random() : askValue(notes, x, me)), random);
return { type: 'suggest', suspect: ask(SUSPECTS) as Suspect, weapon: ask(WEAPONS) as Weapon };
}
case 'afterSuggest':
return { type: 'end' };
default:
break;
}
return legal.length ? randomPolicy(input) : { type: 'end' };
};

View File

@@ -0,0 +1,438 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, playoutSeeds, randomPlayout, seedN, type GameEvent } from '@bg/engine';
import {
DIST,
ITEMS,
PASSAGES,
ROOMS,
SUSPECTS,
WEAPONS,
cardId,
clue,
distTo,
walkToward,
type ClueAction,
type ClueOptions,
type ClueState,
type Item,
type Pos,
type Room,
} from './index';
const P3 = ['A', 'B', 'C'];
let clock = 1_700_000_000_000;
function make(players = P3, opts: Partial<ClueOptions> = {}, seed = 1): ClueState {
return clue.setup({ players, options: clue.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: clock });
}
/** A game with A to move, every token at its start, and hands / case file as written. */
function rigged(hands: Record<string, Item[]>, solution = { suspect: 'plum', weapon: 'rope', room: 'study' } as ClueState['solution'], opts: Partial<ClueOptions> = {}): ClueState {
const players = Object.keys(hands);
const s = make(players, opts);
s.solution = solution;
s.hands = Object.fromEntries(players.map((p) => [p, hands[p]!.map(cardId)]));
const used = new Set([...Object.values(hands).flat(), solution.suspect, solution.weapon, solution.room]);
s.publicCards = ITEMS.filter((x) => !used.has(x)).map(cardId);
s.current = players[0]!;
s.suspectOf = Object.fromEntries(players.map((p, i) => [p, SUSPECTS[i]!]));
return s;
}
function act(s: ClueState, actor: string, a: ClueAction, seed = 7): { state: ClueState; events: GameEvent[] } {
const v = clue.validate(s, actor, a);
if (!v.ok) throw new Error(`rejected ${JSON.stringify(a)} by ${actor}: ${v.reason}`);
clock += 1000;
return clue.apply(s, actor, a, { rng: SeededRng.fromSeed(seedN(seed)), now: clock });
}
const go = (s: ClueState, actor: string, a: ClueAction) => act(s, actor, a).state;
const reason = (s: ClueState, actor: string, a: ClueAction) => {
const v = clue.validate(s, actor, a);
return v.ok ? 'ok' : v.reason;
};
/** Puts `actor` straight into `room`, ready to suggest. */
function inRoom(s: ClueState, actor: string, room: Room): ClueState {
const t = structuredClone(s);
t.pos[t.suspectOf[actor]!] = { at: room };
t.current = actor;
t.phase = { kind: 'suggest', room };
return t;
}
describe('setup', () => {
test.each([
[3, 6, 0],
[4, 4, 2],
[5, 3, 3],
[6, 3, 0],
])('%i players: %i cards each, %i face up, case file out of the deal', (n, each, open) => {
for (let seed = 1; seed <= 20; seed++) {
const players = ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n);
const s = make(players, {}, seed);
for (const p of players) expect(s.hands[p]).toHaveLength(each);
expect(s.publicCards).toHaveLength(open);
const all = [...Object.values(s.hands).flat(), ...s.publicCards, cardId(s.solution.suspect), cardId(s.solution.weapon), cardId(s.solution.room)];
expect(new Set(all).size).toBe(21);
expect(SUSPECTS).toContain(s.solution.suspect);
expect(WEAPONS).toContain(s.solution.weapon);
expect(ROOMS).toContain(s.solution.room);
// The first player is 스칼렛; the suspects follow clockwise.
expect(s.suspectOf[s.current]).toBe('scarlet');
const i = players.indexOf(s.current);
expect(s.suspectOf[players[(i + 1) % n]!]).toBe('mustard');
expect(new Set(Object.values(s.weaponAt)).size).toBe(6);
for (const x of SUSPECTS) expect(s.pos[x]).toEqual({ at: `start-${x}` });
}
});
test('2 or 7 players are refused', () => {
expect(() => make(['A', 'B'])).toThrow();
expect(() => make(['A', 'B', 'C', 'D', 'E', 'F', 'G'])).toThrow();
});
});
describe('mansion', () => {
test('distances are symmetric, rooms 4~16 steps apart, passages join opposite corners', () => {
for (const a of ROOMS)
for (const b of ROOMS) {
expect(DIST[a][b]).toBe(DIST[b][a]);
if (a !== b) expect(DIST[a][b]).toBeGreaterThanOrEqual(4);
expect(DIST[a][b]).toBeLessThan(20);
}
expect(PASSAGES.kitchen).toBe('study');
expect(PASSAGES.lounge).toBe('conservatory');
expect(DIST.kitchen.study).toBeGreaterThan(12); // the passage is the only quick way
});
test('walking k steps towards a room brings it exactly k steps closer', () => {
const r = SeededRng.fromSeed(seedN(3));
for (let i = 0; i < 2000; i++) {
let p: Pos = { at: i % 2 ? ROOMS[r.int(9)]! : `start-${SUSPECTS[r.int(6)]!}` };
for (let hop = 0; hop < 4; hop++) {
const target = ROOMS[r.int(9)]!;
const d = distTo(p, target);
if (d <= 2) break;
const k = 1 + r.int(d - 1);
const q = walkToward(p, target, k);
expect(distTo(q, target)).toBe(d - k);
p = q;
}
}
});
});
describe('moving', () => {
test('roll → enter a room in reach (not the one I left) or walk towards a far one', () => {
let s = rigged({ A: ['scarlet'], B: ['mustard'], C: ['white'] });
expect(reason(s, 'A', { type: 'go', room: 'lounge' })).toBe('먼저 주사위를 굴려 주세요.');
expect(reason(s, 'A', { type: 'passage' })).toBe('여기에는 비밀 통로가 없어요.');
expect(reason(s, 'B', { type: 'roll' })).toBe('지금은 내 차례가 아니에요.');
s = go(s, 'A', { type: 'roll' });
expect(s.phase.kind).toBe('moveTo');
const sum = s.dice![0] + s.dice![1];
const pos = s.pos.scarlet;
for (const room of ROOMS) {
const d = distTo(pos, room);
expect(reason(s, 'A', { type: 'go', room })).toBe(d <= sum ? 'ok' : `${{ kitchen: '부엌', ballroom: '무도회장', conservatory: '온실', dining: '식당', billiard: '당구장', library: '도서실', lounge: '라운지', hall: '홀', study: '서재' }[room]}까지 ${d}칸이라 이번에는 닿지 않아요.`);
expect(reason(s, 'A', { type: 'walk', room })).toBe(d > sum ? 'ok' : '닿는 방이에요. 바로 들어가 주세요.');
}
// Walking ends the turn in the corridor.
const far = ROOMS.find((r) => distTo(pos, r) > sum)!;
const w = go(s, 'A', { type: 'walk', room: far });
expect(w.current).toBe('B');
expect('at' in w.pos.scarlet).toBe(false);
expect(distTo(w.pos.scarlet, far)).toBe(distTo(pos, far) - sum);
});
test('secret passage from a corner room; no re-entering the room I am in', () => {
let s = rigged({ A: ['scarlet'], B: ['mustard'], C: ['white'] });
s.pos.scarlet = { at: 'kitchen' };
s = go(s, 'A', { type: 'passage' });
expect(s.phase).toEqual({ kind: 'suggest', room: 'study' });
expect(s.pos.scarlet).toEqual({ at: 'study' });
let t = rigged({ A: ['scarlet'], B: ['mustard'], C: ['white'] });
t.pos.scarlet = { at: 'hall' };
t = go(t, 'A', { type: 'roll' });
expect(reason(t, 'A', { type: 'go', room: 'hall' })).toBe('방금 있던 방에는 다시 들어갈 수 없어요. 다른 방을 골라 주세요.');
});
test('quick mode: go anywhere at once, no dice', () => {
let s = rigged({ A: ['scarlet'], B: ['mustard'], C: ['white'] }, undefined, { movement: 'free' });
expect(reason(s, 'A', { type: 'roll' })).toBe('이 방은 주사위 없이 바로 이동해요.');
s = go(s, 'A', { type: 'go', room: 'study' });
expect(s.phase).toEqual({ kind: 'suggest', room: 'study' });
expect(clue.view(s, 'A').distances).toBeNull();
});
});
describe('suggestions', () => {
// Solution plum / rope / study. B holds green+dagger, C holds candlestick+library.
const hands = { A: ['scarlet', 'wrench', 'kitchen'], B: ['green', 'dagger', 'hall'], C: ['candlestick', 'library', 'mustard'] } as Record<string, Item[]>;
test('the named suspect and weapon come into the room; the next player with a card must show one', () => {
let s = inRoom(rigged(hands), 'A', 'library');
const r = act(s, 'A', { type: 'suggest', suspect: 'mustard', weapon: 'rope' });
s = r.state;
expect(s.pos.mustard).toEqual({ at: 'library' });
expect(s.weaponAt.rope).toBe('library');
expect(s.movedIn.B).toBe(true); // B plays 머스터드
// B has none of mustard / rope / library → passes; C has two → C chooses.
expect(s.phase).toEqual({ kind: 'refute', refuter: 'C' });
expect(s.suggestions[0]!.passed).toEqual(['B']);
expect(clue.activePlayers(s)).toEqual(['C']);
expect(clue.view(s, 'C').phase).toEqual({ kind: 'refute', refuter: 'C', canShow: [cardId('mustard'), cardId('library')] });
expect(clue.view(s, 'A').phase).toEqual({ kind: 'refute', refuter: 'C' });
expect(reason(s, 'C', { type: 'show', card: cardId('candlestick') })).toBe('추리에 나온 카드 중 내가 가진 카드를 골라 주세요.');
expect(reason(s, 'A', { type: 'end' })).toBe('다른 사람이 카드를 보여 주는 중이에요.');
const shown = act(s, 'C', { type: 'show', card: cardId('library') });
s = shown.state;
expect(s.phase.kind).toBe('afterSuggest');
expect(s.current).toBe('A');
// Only A and C see which card; events never carry it.
expect(clue.view(s, 'A').suggestions[0]!.shown).toBe(cardId('library'));
expect(clue.view(s, 'C').suggestions[0]!.shown).toBe(cardId('library'));
expect(clue.view(s, 'B').suggestions[0]!.shown).toBeUndefined();
expect(clue.view(s, null).suggestions[0]!.shown).toBeUndefined();
expect(clue.view(s, 'B').suggestions[0]!.refuter).toBe('C');
for (const e of [...r.events, ...shown.events]) expect(JSON.stringify(e)).not.toContain('card-');
s = go(s, 'A', { type: 'end' });
expect(s.current).toBe('B');
});
test('moved in by a suggestion: may suggest there on the next turn without moving', () => {
let s = inRoom(rigged(hands), 'A', 'library');
expect(reason(s, 'A', { type: 'end' })).toBe('ok');
s = go(s, 'A', { type: 'suggest', suspect: 'mustard', weapon: 'rope' });
s = go(s, 'C', { type: 'show', card: cardId('mustard') });
s = go(s, 'A', { type: 'end' });
expect(s.current).toBe('B');
expect(clue.legalActions!(s, 'B')).toContainEqual({ type: 'stay' });
s = go(s, 'B', { type: 'stay' });
expect(s.phase).toEqual({ kind: 'suggest', room: 'library' });
s = go(s, 'B', { type: 'end' });
// The right expires after that turn.
expect(s.movedIn.B).toBe(false);
});
test('nobody can answer: everyone passes, the suggester decides', () => {
let s = inRoom(rigged(hands), 'A', 'study');
s = go(s, 'A', { type: 'suggest', suspect: 'plum', weapon: 'rope' });
expect(s.phase.kind).toBe('afterSuggest');
expect(s.suggestions[0]).toMatchObject({ passed: ['B', 'C'], refuter: null, shown: null });
});
test('my own cards in a suggestion do not stop the others from being asked', () => {
let s = inRoom(rigged(hands), 'A', 'kitchen');
s = go(s, 'A', { type: 'suggest', suspect: 'scarlet', weapon: 'wrench' });
expect(s.suggestions[0]!.passed).toEqual(['B', 'C']);
});
});
describe('accusations', () => {
const hands = { A: ['scarlet', 'wrench', 'kitchen'], B: ['green', 'dagger', 'hall'], C: ['candlestick', 'library', 'mustard'] } as Record<string, Item[]>;
test('right: wins at once, anywhere on my turn', () => {
const s = rigged(hands);
const r = act(s, 'A', { type: 'accuse', suspect: 'plum', weapon: 'rope', room: 'study' });
const res = clue.result(r.state)!;
expect(res.ranking).toEqual([['A'], ['B', 'C']]);
expect(res.summary).toContain('플럼 교수 · 밧줄 · 서재');
expect(res.scoreText).toBeUndefined();
expect(clue.view(r.state, 'B').solution).toEqual({ suspect: 'plum', weapon: 'rope', room: 'study' });
});
test('wrong: out of turns but still shows cards; all wrong → nobody wins', () => {
let s = rigged(hands);
s = go(s, 'A', { type: 'accuse', suspect: 'green', weapon: 'rope', room: 'study' });
expect(s.out.A).toBe(true);
expect(s.current).toBe('B');
expect(clue.view(s, 'B').solution).toBeNull();
// B suggests cards only A holds (C passes): A is out but must still show one.
s = inRoom(s, 'B', 'kitchen');
s = go(s, 'B', { type: 'suggest', suspect: 'plum', weapon: 'wrench' });
expect(s.phase).toEqual({ kind: 'refute', refuter: 'A' });
expect(s.suggestions[0]!.passed).toEqual(['C']);
expect(clue.legalActions!(s, 'A')).toEqual([
{ type: 'show', card: cardId('wrench') },
{ type: 'show', card: cardId('kitchen') },
]);
s = go(s, 'A', { type: 'show', card: cardId('kitchen') });
expect(reason(s, 'A', { type: 'roll' })).toBe('고발이 틀려서 이제 카드 보여 주기만 할 수 있어요.');
s = go(s, 'B', { type: 'accuse', suspect: 'plum', weapon: 'rope', room: 'hall' });
expect(s.current).toBe('C'); // A is skipped
s = go(s, 'C', { type: 'accuse', suspect: 'plum', weapon: 'dagger', room: 'study' });
const res = clue.result(s)!;
expect(res.ranking).toEqual([['A', 'B', 'C']]);
expect(res.summary).toContain('아무도 못 이겼어요');
});
});
describe('timer and leaving', () => {
const hands = { A: ['scarlet', 'wrench', 'kitchen'], B: ['green', 'dagger', 'hall'], C: ['candlestick', 'library', 'mustard'] } as Record<string, Item[]>;
test('one timeout plays the whole turn (roll, nearest room, no suggestion)', () => {
const s = rigged(hands);
const t = go(s, 'A', { type: 'timeout' });
expect(t.current).toBe('B');
expect(t.suggestions).toHaveLength(0);
expect(t.idle.A).toBe(1);
expect(t.deadlineAt).toBe(clock + 60_000);
});
test('refute timeout shows the first matching card; refute clock is 20 s', () => {
let s = inRoom(rigged(hands), 'A', 'library');
s = go(s, 'A', { type: 'suggest', suspect: 'mustard', weapon: 'rope' });
expect(s.deadlineAt).toBe(clock + 20_000);
s = go(s, 'C', { type: 'timeout' });
expect(s.suggestions[0]).toMatchObject({ refuter: 'C', shown: cardId('mustard'), auto: true });
expect(s.idle.C).toBe(0);
});
test('three missed turns shorten the clock; when everyone left in the game is away it ends', () => {
let s = rigged(hands);
s.out.B = true;
s.out.C = true;
for (let i = 0; i < 2; i++) s = go(s, 'A', { type: 'timeout' });
expect(s.current).toBe('A');
expect(s.phase.kind).toBe('move');
s = go(s, 'A', { type: 'timeout' });
expect(clue.result(s)!.reason).toBe('timeout');
let t = rigged(hands);
for (let i = 0; i < 9; i++) t = go(t, t.current, { type: 'timeout' });
expect(clue.result(t)!.reason).toBe('timeout');
// A and B are away, C still plays: the game goes on, A's and B's turns get the short clock.
let u = rigged(hands);
for (let i = 0; i < 3; i++) {
u = go(u, 'A', { type: 'timeout' });
u = go(u, 'B', { type: 'timeout' });
u = go(u, 'C', { type: 'roll' });
u = go(u, 'C', clue.legalActions!(u, 'C').find((a) => a.type === 'walk' || a.type === 'go')!);
if (u.phase.kind === 'suggest') u = go(u, 'C', { type: 'end' });
}
expect(u.phase.kind).toBe('move');
expect(u.current).toBe('A');
expect(u.deadlineAt).toBe(clock + 10_000);
});
test('leaving: cards go face up, the answer chain and turns go on, the last one in the room wins', () => {
let s = inRoom(rigged(hands), 'A', 'library');
s = go(s, 'A', { type: 'suggest', suspect: 'green', weapon: 'rope' });
expect(s.phase).toEqual({ kind: 'refute', refuter: 'B' });
s = go(s, 'B', { type: 'leave' });
expect(s.publicCards).toEqual(expect.arrayContaining([cardId('green'), cardId('dagger'), cardId('hall')]));
expect(s.phase).toEqual({ kind: 'refute', refuter: 'C' });
s = go(s, 'C', { type: 'show', card: cardId('library') });
s = go(s, 'A', { type: 'end' });
expect(s.current).toBe('C');
s = go(s, 'C', { type: 'leave' });
const res = clue.result(s)!;
expect(res.ranking[0]).toEqual(['A']);
expect(res.reason).toBe('resign');
});
});
// ---------------------------------------------------------------- random games
/** Random but varied: pick an action type first (accusations rarely), then one of that type. */
function variedPick(legal: ClueAction[], r: SeededRng): ClueAction {
const types = [...new Set(legal.map((a) => a.type))];
const weighted = types.flatMap((t) => (t === 'accuse' ? (r.int(12) === 0 ? [t] : []) : [t, t]));
const t = weighted.length ? weighted[r.int(weighted.length)]! : types[r.int(types.length)]!;
const xs = legal.filter((a) => a.type === t);
return xs[r.int(xs.length)]!;
}
/** What `viewer` may know: own hand, face-up cards, cards shown to or by them (everything once the game is over). */
function allowedCards(s: ClueState, viewer: string | null): Set<string> {
if (s.phase.kind === 'finished') return new Set(ITEMS.map(cardId));
const out = new Set(s.publicCards);
if (viewer) {
for (const c of s.hands[viewer] ?? []) out.add(c);
for (const sg of s.suggestions) if (sg.shown && (sg.by === viewer || sg.refuter === viewer)) out.add(sg.shown);
}
return out;
}
function checkViews(s: ClueState) {
for (const viewer of [...s.seats, null]) {
const json = JSON.stringify(clue.view(s, viewer));
const ok = allowedCards(s, viewer);
for (const x of ITEMS) if (!ok.has(cardId(x)) && json.includes(`"${cardId(x)}"`)) throw new Error(`view of ${viewer} leaks ${cardId(x)}`);
if (s.phase.kind !== 'finished' && json.includes('"solution":{')) throw new Error('case file leaks');
}
}
function conserved(s: ClueState) {
const all = [...Object.values(s.hands).flat(), ...s.publicCards.filter((c) => !Object.values(s.hands).flat().includes(c)), cardId(s.solution.suspect), cardId(s.solution.weapon), cardId(s.solution.room)];
if (new Set(all).size !== 21 || all.length !== 21) throw new Error(`cards not conserved: ${all.length}`);
}
describe('random games', () => {
const N = playoutSeeds(300);
test(`${N} varied games: legal, conserved, no leaks in views or events, onTimeout always valid`, () => {
let finished = 0;
let refutes = 0;
for (let g = 0; g < N; g++) {
const n = 3 + (g % 4);
const players = ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n);
const opts = clue.optionsSchema.parse({ movement: g % 3 === 2 ? 'free' : 'dice' });
const rng = SeededRng.fromSeed(seedN(1000 + g));
const ch = SeededRng.fromSeed(seedN(5000 + g));
let s = clue.setup({ players, options: opts, rng, now: 0 });
for (let step = 0; step < 3000 && !clue.result(s); step++) {
checkViews(s);
conserved(s);
const actor = clue.activePlayers(s)[0]!;
expect(clue.validate(s, actor, clue.onTimeout(s, actor)).ok).toBe(true);
const r = ch.int(25);
let a: ClueAction;
if (r === 0) a = clue.onTimeout(s, actor);
else if (r === 1 && step > 30) a = { type: 'leave' };
else a = variedPick(clue.legalActions!(s, actor), ch);
const v = clue.validate(s, actor, a);
if (!v.ok) throw new Error(`legal action rejected: ${v.reason} ${JSON.stringify(a)}`);
if (s.phase.kind === 'refute') refutes++;
const out = clue.apply(s, actor, a, { rng, now: step * 1000 });
const hidden = new Set(ITEMS.map(cardId));
if (out.state.phase.kind !== 'finished') for (const e of out.events) for (const c of hidden) if (JSON.stringify(e).includes(`"${c}"`)) throw new Error(`event leaks ${c}`);
s = out.state;
}
checkViews(s);
if (clue.result(s)) finished++;
}
expect(finished).toBe(N);
expect(refutes).toBeGreaterThan(N);
});
test('engine random playouts (secretsOf leak check, JSON round trip)', () => {
for (let i = 0; i < playoutSeeds(60); i++) {
const n = 3 + (i % 4);
const r = randomPlayout(clue, { players: ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n), seed: seedN(i + 1), maxApplyMs: 50 });
expect(r.finished).toBe(true);
}
});
test('deterministic for the same seed and actions', () => {
const run = () => {
const rng = SeededRng.fromSeed(seedN(42));
const ch = SeededRng.fromSeed(seedN(43));
let s = clue.setup({ players: P3, options: clue.defaultOptions, rng, now: 0 });
for (let i = 0; i < 200 && !clue.result(s); i++) {
const actor = clue.activePlayers(s)[0]!;
s = clue.apply(s, actor, variedPick(clue.legalActions!(s, actor), ch), { rng, now: i }).state;
}
return JSON.stringify(s);
};
expect(run()).toBe(run());
});
test('secretsOf: unshown hand cards and the case file; nothing after the end', () => {
let s = inRoom(rigged({ A: ['scarlet', 'wrench', 'kitchen'], B: ['green', 'dagger', 'hall'], C: ['candlestick', 'library', 'mustard'] }), 'A', 'hall');
expect(clue.secretsOf!(s, 'B')).toEqual([cardId('green'), cardId('dagger'), cardId('hall'), cardId('plum'), cardId('rope'), cardId('study')]);
s = go(s, 'A', { type: 'suggest', suspect: 'green', weapon: 'rope' });
s = go(s, 'B', { type: 'show', card: cardId('green') });
expect(clue.secretsOf!(s, 'B')).not.toContain(cardId('green'));
s = go(s, 'A', { type: 'accuse', suspect: 'plum', weapon: 'rope', room: 'study' });
expect(clue.secretsOf!(s, 'B')).toEqual([]);
});
});

View File

@@ -0,0 +1,506 @@
/**
* 클루 (docs/games/clue.md).
*
* Secret-id design: cards are 'card-<item>' while suggestions and accusations name items ('rope'), so a card id only
* appears in a view where the viewer may know that card's place (own hand, a card shown to or by the viewer, public
* cards, everything after the game). The case file (사건 봉투) stays out of every view until the game ends.
*/
import { fail, nextSeat, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Validation } from '@bg/engine';
import {
ITEMS,
PASSAGES,
ROOMS,
ROOM_KO,
SUSPECTS,
SUSPECT_KO,
WEAPONS,
WEAPON_KO,
cardId,
clueActionSchema,
clueOptionsSchema,
distTo,
roomAt,
startOf,
walkToward,
type ClueAction,
type ClueClientAction,
type ClueFinal,
type ClueOptions,
type ClueState,
type ClueView,
type PhaseView,
type Pos,
type Room,
type Suggestion,
type Suspect,
type Weapon,
} from './types';
import type { z } from 'zod';
export * from './types';
export const MIN_PLAYERS = 3;
export const MAX_PLAYERS = 6;
const REFUTE_MS = 20_000;
const IDLE_MS = 10_000;
const IDLE_TURNS = 3;
// ---------------------------------------------------------------- helpers
const per = <T>(players: PlayerId[], f: (p: PlayerId) => T) => Object.fromEntries(players.map((p) => [p, f(p)])) as Record<PlayerId, T>;
const diceSum = (s: ClueState) => (s.dice ? s.dice[0] + s.dice[1] : 0);
const ownTurnPhase = (s: ClueState) => s.phase.kind === 'move' || s.phase.kind === 'moveTo' || s.phase.kind === 'suggest' || s.phase.kind === 'afterSuggest';
/** Still takes turns. */
const playing = (s: ClueState, p: PlayerId) => !s.out[p] && !s.left[p];
export const tripleKo = (x: { suspect: Suspect; weapon: Weapon; room: Room }) => `${SUSPECT_KO[x.suspect]} · ${WEAPON_KO[x.weapon]} · ${ROOM_KO[x.room]}`;
/** The suggester's matching cards in `p`'s hand. */
export function matchingCards(s: ClueState, p: PlayerId, sg: Pick<Suggestion, 'suspect' | 'weapon' | 'room'>): string[] {
const want = new Set([cardId(sg.suspect), cardId(sg.weapon), cardId(sg.room)]);
return ITEMS.map(cardId).filter((c) => want.has(c) && (s.hands[p] ?? []).includes(c));
}
function refreshDeadline(s: ClueState, now: number): void {
if (s.phase.kind === 'finished') {
s.deadlineAt = null;
return;
}
if (s.phase.kind === 'refute') {
s.deadlineAt = now + REFUTE_MS;
return;
}
s.deadlineAt = now + ((s.idle[s.current] ?? 0) >= IDLE_TURNS ? IDLE_MS : s.options.turnSeconds * 1000);
}
function finish(s: ClueState, winner: PlayerId | null, reason: ClueFinal['reason'], events: GameEvent[]): void {
const answer = tripleKo(s.solution);
// "…서재였어요" / "…식당이었어요"
const last = answer.charCodeAt(answer.length - 1);
const was = last >= 0xac00 && last <= 0xd7a3 && (last - 0xac00) % 28 !== 0 ? '이었어요' : '였어요';
const ranking = winner ? [[winner], s.seats.filter((p) => p !== winner)] : [[...s.seats]];
let summary: string;
if (winner && reason === 'resign') summary = `다른 사람이 모두 나가서 게임이 끝났어요. 정답은 ${answer}${was}.`;
else if (winner) summary = `고발이 맞았어요! 정답은 ${answer}${was}. (추리 ${s.suggestions.filter((x) => x.by === winner).length}번)`;
else if (reason === 'timeout') summary = `남은 사람이 모두 자리를 비워 아무도 못 맞히고 끝났어요. 정답은 ${answer}${was}.`;
else summary = `모두 고발이 틀려서 아무도 못 이겼어요. 정답은 ${answer}${was}.`;
s.final = { winner, ranking, summary, reason };
s.phase = { kind: 'finished' };
s.dice = null;
events.push({ type: 'gameEnded', winner });
}
/** Ends the game when nobody is left to play (or only one person is still in the room). Returns true when finished. */
function checkFinish(s: ClueState, events: GameEvent[]): boolean {
if (s.phase.kind === 'finished') return true;
const present = s.seats.filter((p) => !s.left[p]);
if (present.length === 1 && s.seats.length > 1 && !s.out[present[0]!]) {
finish(s, present[0]!, 'resign', events);
return true;
}
const active = s.seats.filter((p) => playing(s, p));
if (active.length === 0) {
finish(s, null, 'normal', events);
return true;
}
return false;
}
function endTurn(s: ClueState, events: GameEvent[]): void {
s.movedIn[s.current] = false;
s.dice = null;
if (checkFinish(s, events)) return;
const active = s.seats.filter((p) => playing(s, p));
// Everybody still in the game let the clock run out three turns in a row: nobody is playing any more.
if (active.every((p) => (s.idle[p] ?? 0) >= IDLE_TURNS)) {
finish(s, null, 'timeout', events);
return;
}
const i = s.seats.indexOf(s.current);
s.current = s.seats[nextSeat(i, s.seats.length, (j) => !playing(s, s.seats[j]!))]!;
s.turnNo += 1;
s.phase = { kind: 'move' };
events.push({ type: 'turn', player: s.current });
}
/** Asks the players after the suggester in turn, starting after `after`; stops at the first one holding a card. */
function continueRefute(s: ClueState, after: PlayerId, events: GameEvent[]): void {
const sg = s.suggestions[s.suggestions.length - 1]!;
const n = s.seats.length;
const from = s.seats.indexOf(after);
for (let k = 1; k < n; k++) {
const p = s.seats[(from + k) % n]!;
if (p === sg.by) break;
if (s.left[p]) continue;
if (matchingCards(s, p, sg).length) {
s.phase = { kind: 'refute', refuter: p };
events.push({ type: 'refuting', player: p });
return;
}
sg.passed.push(p);
events.push({ type: 'passed', player: p });
}
s.phase = { kind: 'afterSuggest' };
events.push({ type: 'noRefute', by: sg.by });
}
function moveToken(s: ClueState, who: Suspect, room: Room): boolean {
if (roomAt(s.pos[who]) === room) return false;
s.pos[who] = { at: room };
return true;
}
function enter(s: ClueState, actor: PlayerId, room: Room, how: string, events: GameEvent[]): void {
s.pos[s.suspectOf[actor]!] = { at: room };
s.phase = { kind: 'suggest', room };
events.push({ type: 'entered', player: actor, room, how });
}
// ---------------------------------------------------------------- automatic actions (timer)
/** Nearest room from `p` other than `except` (ties: map order). */
function nearestRoom(p: Pos, except: Room | null): Room {
let best: Room = ROOMS.find((r) => r !== except)!;
for (const r of ROOMS) if (r !== except && distTo(p, r) < distTo(p, best)) best = r;
return best;
}
/** The concrete action a timeout stands for (docs §8.5): move on to the nearest room without suggesting, show the first matching card. */
export function autoAction(s: ClueState, player: PlayerId): ClueClientAction {
const ph = s.phase;
const pos = s.pos[s.suspectOf[player]!];
switch (ph.kind) {
case 'move':
return s.options.movement === 'dice' ? { type: 'roll' } : { type: 'go', room: nearestRoom(pos, roomAt(pos)) };
case 'moveTo': {
const here = roomAt(pos);
const reach = ROOMS.filter((r) => r !== here && distTo(pos, r) <= diceSum(s));
if (reach.length) return { type: 'go', room: reach.reduce((a, b) => (distTo(pos, b) < distTo(pos, a) ? b : a)) };
return { type: 'walk', room: nearestRoom(pos, here) };
}
case 'suggest':
case 'afterSuggest':
return { type: 'end' };
case 'refute':
return { type: 'show', card: matchingCards(s, player, s.suggestions[s.suggestions.length - 1]!)[0]! };
case 'finished':
throw new Error('clue: no auto action after the game');
}
}
// ---------------------------------------------------------------- validate / apply
function validateClient(s: ClueState, actor: PlayerId, a: ClueClientAction): Validation {
const ph = s.phase;
if (a.type === 'show') {
if (ph.kind !== 'refute') return fail('지금은 카드를 보여 줄 때가 아니에요.');
if (ph.refuter !== actor) return fail('지금은 내가 카드를 보여 줄 차례가 아니에요.');
if (!matchingCards(s, actor, s.suggestions[s.suggestions.length - 1]!).includes(a.card)) return fail('추리에 나온 카드 중 내가 가진 카드를 골라 주세요.');
return ok;
}
if (s.out[actor]) return fail('고발이 틀려서 이제 카드 보여 주기만 할 수 있어요.');
if (s.current !== actor) return fail('지금은 내 차례가 아니에요.');
if (ph.kind === 'refute') return fail('다른 사람이 카드를 보여 주는 중이에요.');
const pos = s.pos[s.suspectOf[actor]!];
const here = roomAt(pos);
const dice = s.options.movement === 'dice';
switch (a.type) {
case 'roll':
if (ph.kind !== 'move') return fail('지금은 주사위를 굴릴 때가 아니에요.');
return dice ? ok : fail('이 방은 주사위 없이 바로 이동해요.');
case 'passage': {
if (ph.kind !== 'move') return fail('비밀 통로는 차례를 시작할 때만 쓸 수 있어요.');
if (!dice) return fail('이 방은 아무 방이나 바로 갈 수 있어요.');
return here && PASSAGES[here] ? ok : fail('여기에는 비밀 통로가 없어요.');
}
case 'stay':
if (ph.kind !== 'move') return fail('지금은 고를 수 없어요.');
if (!here || !s.movedIn[actor]) return fail('다른 사람의 추리로 방에 불려 왔을 때만 그 자리에서 추리할 수 있어요.');
return ok;
case 'go': {
if (a.room === here) return fail('방금 있던 방에는 다시 들어갈 수 없어요. 다른 방을 골라 주세요.');
if (!dice) return ph.kind === 'move' ? ok : fail('지금은 이동할 때가 아니에요.');
if (ph.kind !== 'moveTo') return fail(ph.kind === 'move' ? '먼저 주사위를 굴려 주세요.' : '지금은 이동할 때가 아니에요.');
const d = distTo(pos, a.room);
return d <= diceSum(s) ? ok : fail(`${ROOM_KO[a.room]}까지 ${d}칸이라 이번에는 닿지 않아요.`);
}
case 'walk': {
if (!dice || ph.kind !== 'moveTo') return fail('지금은 복도를 걸어갈 때가 아니에요.');
if (a.room === here) return fail('지금 있는 방이에요.');
return distTo(pos, a.room) > diceSum(s) ? ok : fail('닿는 방이에요. 바로 들어가 주세요.');
}
case 'suggest':
return ph.kind === 'suggest' ? ok : fail('방에 들어갔을 때만 추리할 수 있어요.');
case 'accuse':
return ownTurnPhase(s) ? ok : fail('지금은 고발할 수 없어요.');
case 'end':
return ph.kind === 'suggest' || ph.kind === 'afterSuggest' ? ok : fail('먼저 이동해 주세요.');
}
}
function applyClient(s: ClueState, actor: PlayerId, a: ClueClientAction, events: GameEvent[], rng: { int(n: number): number }, auto: boolean): void {
const me = s.suspectOf[actor]!;
switch (a.type) {
case 'roll':
s.dice = [rng.int(6) + 1, rng.int(6) + 1];
s.phase = { kind: 'moveTo' };
events.push({ type: 'rolled', player: actor, dice: s.dice });
break;
case 'passage':
enter(s, actor, PASSAGES[roomAt(s.pos[me])!]!, 'passage', events);
break;
case 'stay':
enter(s, actor, roomAt(s.pos[me])!, 'stay', events);
break;
case 'go':
enter(s, actor, a.room, 'go', events);
break;
case 'walk':
s.pos[me] = walkToward(s.pos[me], a.room, diceSum(s));
events.push({ type: 'walked', player: actor, toward: a.room });
endTurn(s, events);
break;
case 'suggest': {
const room = (s.phase as Extract<ClueState['phase'], { kind: 'suggest' }>).room;
// The named suspect's token and the weapon are brought into the room (official rule).
if (moveToken(s, a.suspect, room)) {
const owner = s.seats.find((p) => s.suspectOf[p] === a.suspect);
if (owner && owner !== actor) s.movedIn[owner] = true;
}
s.weaponAt[a.weapon] = room;
s.suggestions.push({ by: actor, suspect: a.suspect, weapon: a.weapon, room, passed: [], refuter: null, shown: null, auto: false, turnNo: s.turnNo });
events.push({ type: 'suggested', by: actor, suspect: a.suspect, weapon: a.weapon, room });
continueRefute(s, actor, events);
break;
}
case 'show': {
const sg = s.suggestions[s.suggestions.length - 1]!;
sg.refuter = actor;
sg.shown = a.card;
sg.auto = auto;
s.phase = { kind: 'afterSuggest' };
// Public: who showed a card to whom, never which one.
events.push({ type: 'refuted', by: actor, to: sg.by });
break;
}
case 'accuse': {
const sol = s.solution;
const correct = a.suspect === sol.suspect && a.weapon === sol.weapon && a.room === sol.room;
s.accusations.push({ by: actor, suspect: a.suspect, weapon: a.weapon, room: a.room, correct, turnNo: s.turnNo });
events.push({ type: 'accused', by: actor, suspect: a.suspect, weapon: a.weapon, room: a.room, correct });
if (correct) finish(s, actor, 'normal', events);
else {
s.out[actor] = true;
endTurn(s, events);
}
break;
}
case 'end':
endTurn(s, events);
break;
}
}
function applyLeave(s: ClueState, actor: PlayerId, events: GameEvent[]): void {
s.left[actor] = true;
events.push({ type: 'left', player: actor });
// Their cards go face up so the case stays solvable.
for (const c of s.hands[actor] ?? []) if (!s.publicCards.includes(c)) s.publicCards.push(c);
const ph = s.phase;
if (checkFinish(s, events)) return;
if (ph.kind === 'refute' && ph.refuter === actor) {
continueRefute(s, actor, events);
return;
}
if (s.current === actor) endTurn(s, events);
}
// ---------------------------------------------------------------- definition
export const clue: GameDefinition<ClueState, ClueAction, ClueView, ClueOptions> = {
id: 'clue',
nameKo: '클루',
minPlayers: MIN_PLAYERS,
maxPlayers: MAX_PLAYERS,
stateVersion: 1,
defaultOptions: clueOptionsSchema.parse({}),
optionsSchema: clueOptionsSchema as unknown as z.ZodType<ClueOptions>,
actionSchema: clueActionSchema as unknown as z.ZodType<ClueAction>,
setup({ players, options, rng, now, gameNo }) {
if (players.length < MIN_PLAYERS || players.length > MAX_PLAYERS) throw new Error(`clue: ${players.length} players not allowed`);
const n = players.length;
// Scarlet moves first (official); the first player is drawn and the suspects follow clockwise from them.
const first = rng.int(n);
const suspectOf = per(players, (p) => SUSPECTS[(players.indexOf(p) - first + n) % n]!);
const solution = { suspect: SUSPECTS[rng.int(6)]!, weapon: WEAPONS[rng.int(6)]!, room: ROOMS[rng.int(9)]! };
const rest = rng.shuffle(ITEMS.filter((x) => x !== solution.suspect && x !== solution.weapon && x !== solution.room).map(cardId));
// Everyone gets the same number of cards; the leftovers lie face up for all (official rule).
const each = Math.floor(rest.length / n);
const hands = per(players, (p) => rest.slice(players.indexOf(p) * each, (players.indexOf(p) + 1) * each));
const publicCards = rest.slice(n * each);
const roomsForWeapons = rng.shuffle([...ROOMS]);
const s: ClueState = {
options,
seats: [...players],
gameNo: gameNo ?? 1,
suspectOf,
solution,
hands,
publicCards,
pos: Object.fromEntries(SUSPECTS.map((x) => [x, { at: startOf(x) }])) as Record<Suspect, Pos>,
weaponAt: Object.fromEntries(WEAPONS.map((w, i) => [w, roomsForWeapons[i]!])) as Record<Weapon, Room>,
current: players[first]!,
phase: { kind: 'move' },
dice: null,
movedIn: per(players, () => false),
out: per(players, () => false),
left: per(players, () => false),
suggestions: [],
accusations: [],
turnNo: 0,
idle: per(players, () => 0),
idleTurn: per(players, () => -1),
deadlineAt: null,
seq: 0,
final: null,
};
refreshDeadline(s, now);
return s;
},
validate(s, actor, a) {
if (!s.seats.includes(actor)) return fail('이 게임의 플레이어가 아니에요.');
if (s.phase.kind === 'finished') return fail('게임이 이미 끝났어요.');
if (a.type === 'leave') return s.left[actor] ? fail('이미 나간 플레이어예요.') : ok;
if (s.left[actor]) return fail('이미 나간 플레이어예요.');
if (a.type === 'timeout') return activeOf(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.');
return validateClient(s, actor, a);
},
apply(prev, actor, a, { rng, now }) {
const s = structuredClone(prev);
const events: GameEvent[] = [];
if (a.type === 'leave') applyLeave(s, actor, events);
else if (a.type === 'timeout') {
events.push({ type: 'timeout', player: actor });
if (s.phase.kind !== 'refute' && s.idleTurn[actor] !== s.turnNo) {
s.idleTurn[actor] = s.turnNo;
s.idle[actor] = (s.idle[actor] ?? 0) + 1;
}
// One timeout plays out the rest of the step: on the player's own turn, the whole turn (move, no suggestion).
const turn = s.turnNo;
do {
const concrete = autoAction(s, actor);
const v = validateClient(s, actor, concrete);
if (!v.ok) throw new Error(`clue: auto action rejected: ${v.reason}`);
applyClient(s, actor, concrete, events, rng, true);
} while (s.turnNo === turn && s.current === actor && ownTurnPhase(s));
} else {
s.idle[actor] = 0;
applyClient(s, actor, a, events, rng, false);
}
s.seq += 1;
refreshDeadline(s, now);
return { state: s, events };
},
view(s, viewer) {
const me = viewer && s.seats.includes(viewer) ? viewer : null;
const over = s.phase.kind === 'finished';
const ph = s.phase;
let phase: PhaseView;
if (ph.kind === 'refute') {
phase = { kind: 'refute', refuter: ph.refuter };
if (me === ph.refuter) phase.canShow = matchingCards(s, me, s.suggestions[s.suggestions.length - 1]!);
} else phase = { ...ph };
const mover = s.pos[s.suspectOf[s.current]!];
const distances =
s.options.movement === 'dice' && (ph.kind === 'move' || ph.kind === 'moveTo')
? (Object.fromEntries(ROOMS.map((r) => [r, distTo(mover, r)])) as Record<Room, number>)
: null;
return {
options: s.options,
me,
seats: s.seats,
gameNo: s.gameNo,
suspectOf: s.suspectOf,
current: s.current,
phase,
dice: s.dice,
pos: s.pos,
weaponAt: s.weaponAt,
distances,
myHand: me ? [...s.hands[me]!] : null,
handCounts: per(s.seats, (p) => s.hands[p]!.length),
publicCards: [...s.publicCards],
movedIn: s.movedIn,
out: s.out,
left: s.left,
suggestions: s.suggestions.map(({ shown, ...rest }) => (shown && (over || me === rest.by || me === rest.refuter) ? { ...rest, shown } : rest)),
accusations: s.accusations,
turnNo: s.turnNo,
idle: s.idle,
deadlineAt: s.deadlineAt,
solution: over ? s.solution : null,
hands: over ? s.hands : null,
final: s.final,
};
},
activePlayers: activeOf,
deadline(s) {
return s.phase.kind === 'finished' ? null : s.deadlineAt;
},
onTimeout() {
return { type: 'timeout' };
},
onLeave(s, player) {
if (!s.seats.includes(player) || s.left[player] || s.phase.kind === 'finished') return null;
return { type: 'leave' };
},
result(s): GameResult | null {
if (!s.final) return null;
return { ranking: s.final.ranking, summary: s.final.summary, reason: s.final.reason };
},
legalActions(s, p) {
if (!activeOf(s).includes(p)) return [];
const ph = s.phase;
if (ph.kind === 'refute') return matchingCards(s, p, s.suggestions[s.suggestions.length - 1]!).map((card) => ({ type: 'show', card }));
const all: ClueAction[] = [];
const pos = s.pos[s.suspectOf[p]!];
const here = roomAt(pos);
if (ph.kind === 'move') {
if (s.options.movement === 'dice') all.push({ type: 'roll' });
else for (const room of ROOMS) if (room !== here) all.push({ type: 'go', room });
if (s.options.movement === 'dice' && here && PASSAGES[here]) all.push({ type: 'passage' });
if (here && s.movedIn[p]) all.push({ type: 'stay' });
} else if (ph.kind === 'moveTo') {
for (const room of ROOMS) if (room !== here) all.push(distTo(pos, room) <= diceSum(s) ? { type: 'go', room } : { type: 'walk', room });
} else if (ph.kind === 'suggest') {
for (const suspect of SUSPECTS) for (const weapon of WEAPONS) all.push({ type: 'suggest', suspect, weapon });
all.push({ type: 'end' });
} else if (ph.kind === 'afterSuggest') all.push({ type: 'end' });
for (const suspect of SUSPECTS) for (const weapon of WEAPONS) for (const room of ROOMS) all.push({ type: 'accuse', suspect, weapon, room });
return all;
},
/** Card ids nobody else may see yet: `player`'s cards never shown to anyone, and the case file. */
secretsOf(s, player) {
if (s.phase.kind === 'finished') return [];
const shown = new Set(s.suggestions.map((x) => x.shown).filter(Boolean));
const own = s.left[player] ? [] : (s.hands[player] ?? []).filter((c) => !shown.has(c));
return [...own, cardId(s.solution.suspect), cardId(s.solution.weapon), cardId(s.solution.room)];
},
};
function activeOf(s: ClueState): PlayerId[] {
if (s.phase.kind === 'finished') return [];
if (s.phase.kind === 'refute') return [s.phase.refuter];
return [s.current];
}

View File

@@ -0,0 +1,169 @@
/** 클루 options, actions, state and view types (docs/games/clue.md §2, §8); cards and the map live in board.ts. */
import { z } from 'zod';
import type { PlayerId } from '@bg/engine';
import { ROOMS, SUSPECTS, WEAPONS, type Pos, type Room, type Suspect, type Weapon } from './board';
export * from './board';
// ---------------------------------------------------------------- options
const lit = <T extends string | number>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
export const clueOptionsSchema = z.object({
movement: z
.enum(['dice', 'free'])
.default('dice')
.meta({ title: '이동 방식', labels: { dice: '주사위 2개로 복도 이동(원작처럼)', free: '빠르게(아무 방이나 바로 이동)' } }),
turnSeconds: lit(30, 45, 60, 90)
.default(60)
.meta({ title: '차례 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', 90: '90초' } }),
});
export type ClueOptions = z.infer<typeof clueOptionsSchema>;
// ---------------------------------------------------------------- actions
const suspectSchema = z.enum(SUSPECTS);
const weaponSchema = z.enum(WEAPONS);
const roomSchema = z.enum(ROOMS);
export const clueActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('roll') }),
z.object({ type: z.literal('passage') }),
z.object({ type: z.literal('stay') }),
z.object({ type: z.literal('go'), room: roomSchema }),
z.object({ type: z.literal('walk'), room: roomSchema }),
z.object({ type: z.literal('suggest'), suspect: suspectSchema, weapon: weaponSchema }),
z.object({ type: z.literal('show'), card: z.string().max(32) }),
z.object({ type: z.literal('accuse'), suspect: suspectSchema, weapon: weaponSchema, room: roomSchema }),
z.object({ type: z.literal('end') }),
]);
export type ClueClientAction = z.infer<typeof clueActionSchema>;
/** Client actions plus system-only actions (timer / leaving), which are not in the schema. */
export type ClueAction = ClueClientAction | { type: 'timeout' } | { type: 'leave' };
// ---------------------------------------------------------------- state
export type CluePhase =
/** Start of the turn: roll (or go anywhere in the quick mode), take a secret passage, stay after being moved in, or accuse. */
| { kind: 'move' }
/** Dice rolled: enter a room within reach or walk towards one. */
| { kind: 'moveTo' }
/** In a room: suggest a suspect + weapon there (or skip), or accuse. */
| { kind: 'suggest'; room: Room }
/** `refuter` must show the suggester one of the matching cards. */
| { kind: 'refute'; refuter: PlayerId }
/** Suggestion answered: accuse or end the turn. */
| { kind: 'afterSuggest' }
| { kind: 'finished' };
export type PhaseKind = CluePhase['kind'];
export interface Suggestion {
by: PlayerId;
suspect: Suspect;
weapon: Weapon;
room: Room;
/** Players asked in turn who had none of the three cards. */
passed: PlayerId[];
refuter: PlayerId | null;
/** The card shown (secret: only `by` and `refuter` see it). */
shown: string | null;
/** The card was picked by the timer. */
auto: boolean;
turnNo: number;
}
export interface Accusation {
by: PlayerId;
suspect: Suspect;
weapon: Weapon;
room: Room;
correct: boolean;
turnNo: number;
}
export interface ClueFinal {
winner: PlayerId | null;
ranking: PlayerId[][];
summary: string;
reason: 'normal' | 'resign' | 'timeout';
}
export interface ClueState {
options: ClueOptions;
seats: PlayerId[];
gameNo: number;
/** The suspect each player plays (their token on the map). */
suspectOf: Record<PlayerId, Suspect>;
/** The case file (사건 봉투): item names. Secret until the end. */
solution: { suspect: Suspect; weapon: Weapon; room: Room };
/** Card ids per player. */
hands: Record<PlayerId, string[]>;
/** Face-up cards: the deal's leftovers, plus the hands of players who left. */
publicCards: string[];
pos: Record<Suspect, Pos>;
weaponAt: Record<Weapon, Room>;
current: PlayerId;
phase: CluePhase;
dice: [number, number] | null;
/** Token moved into a room by someone's suggestion since the player's last turn (may suggest there without moving). */
movedIn: Record<PlayerId, boolean>;
/** Made a wrong accusation: no more turns, but still shows cards. */
out: Record<PlayerId, boolean>;
left: Record<PlayerId, boolean>;
suggestions: Suggestion[];
accusations: Accusation[];
turnNo: number;
/** Consecutive own turns ended by the timer; at 3 the clock drops to 10 s. */
idle: Record<PlayerId, number>;
idleTurn: Record<PlayerId, number>;
deadlineAt: number | null;
seq: number;
final: ClueFinal | null;
}
// ---------------------------------------------------------------- view
export interface SuggestionView extends Omit<Suggestion, 'shown'> {
/** Present only for the suggester and the refuter. */
shown?: string;
}
export type PhaseView =
| { kind: 'move' }
| { kind: 'moveTo' }
| { kind: 'suggest'; room: Room }
/** `canShow`: the refuter's matching cards (only in the refuter's own view). */
| { kind: 'refute'; refuter: PlayerId; canShow?: string[] }
| { kind: 'afterSuggest' }
| { kind: 'finished' };
export interface ClueView {
options: ClueOptions;
me: PlayerId | null;
seats: PlayerId[];
gameNo: number;
suspectOf: Record<PlayerId, Suspect>;
current: PlayerId;
phase: PhaseView;
dice: [number, number] | null;
pos: Record<Suspect, Pos>;
weaponAt: Record<Weapon, Room>;
/** Dice mode, the mover's move steps: corridor steps from the current player's token to every room. */
distances: Record<Room, number> | null;
/** My cards (card ids); null for spectators. */
myHand: string[] | null;
handCounts: Record<PlayerId, number>;
publicCards: string[];
movedIn: Record<PlayerId, boolean>;
out: Record<PlayerId, boolean>;
left: Record<PlayerId, boolean>;
suggestions: SuggestionView[];
accusations: Accusation[];
turnNo: number;
idle: Record<PlayerId, number>;
deadlineAt: number | null;
/** After the game: the case file and every hand. */
solution: ClueState['solution'] | null;
hands: Record<PlayerId, string[]> | null;
final: ClueFinal | null;
}

View File

@@ -26,6 +26,7 @@ import { dobble } from './dobble';
import { catchmind } from './catchmind';
import { mafia } from './mafia';
import { apple } from './apple';
import { clue } from './clue';
export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -55,4 +56,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[catchmind.id]: catchmind,
[mafia.id]: mafia,
[apple.id]: apple,
[clue.id]: clue,
};

View File

@@ -4,7 +4,7 @@ import { randomPlayout, seedN } from '@bg/engine';
import { GAMES } from './index';
/** Games without a score (win/lose only, or survival) leave `scoreText` out. */
const NO_SCORE = new Set(['omok', 'chess', 'quoridor', 'davinci-code', 'ninety-nine', 'bang', 'mafia', 'cockroach-poker']);
const NO_SCORE = new Set(['omok', 'chess', 'quoridor', 'davinci-code', 'ninety-nine', 'bang', 'mafia', 'cockroach-poker', 'clue']);
/** Options under which the game keeps score (원카드: only the 색깔 카드 mode has points). */
const SCORED_OPTIONS: Record<string, object> = { 'one-card': { mode: 'uno-style' } };

View File

@@ -51,6 +51,7 @@ export const BOT_GAMES: readonly string[] = [
'ninety-nine',
'mafia',
'apple',
'clue',
];
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1). */

View File

@@ -38,6 +38,7 @@ export const CATALOG: CatalogEntry[] = [
{ id: 'catchmind', nameKo: '그림 맞히기', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '한 사람이 그림을 그리면 나머지가 채팅으로 정답을 맞혀요!', available: true },
{ id: 'apple', nameKo: '사과 게임', minPlayers: 1, maxPlayers: 8, minutes: '1~3', level: '쉬움', blurb: '합이 10이 되게 사과를 드래그! 2분 동안 누가 더 많이 지울까 · 혼자서도 OK', available: true },
{ id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },
{ id: 'clue', nameKo: '클루', minPlayers: 3, maxPlayers: 6, minutes: '30~50', level: '보통', blurb: '저택 살인 사건! 질문과 소거법으로 범인·흉기·장소를 맞혀요', available: true },
];
export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);