Files
joke-app/packages/games/src/davinci-code/index.ts
EJClaw 0fe7e27eb2 다빈치 코드 조커 숨김·공개 타일 표시, 바퀴벌레 포커 내 빠른 말 표시, 난수를 ChaCha20으로
- 다빈치 코드: 조커를 놓는 단계(placeJoker)를 상대·관전자 화면에는 바로 전 단계로 보여 줌(서버 view)
- 다빈치 코드: 공개된 타일은 반 칸 위로 올리고 아래에 노란 줄, 숨은 타일은 제자리
- 바퀴벌레 포커: 내가 한 빠른 말도 내 자리 위 말풍선으로 표시
- 난수: 새 게임은 256비트 OS 시드 + ChaCha20(RFC 8439, 암호학적 생성기). 옛 게임(128비트)은 sfc32 그대로라 다시 보기 동일
- 테스트: RFC 테스트 벡터, 균등성(카이제곱), 상태 이어받기, 조커 단계 비공개

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 03:12:48 +09:00

804 lines
33 KiB
TypeScript

/**
* 다빈치 코드 (docs/games/davinci-code.md).
*
* Secret-id design: tile ids ('b5', 'wJ', ...) encode the number, so they only ever appear in a view
* for tiles the viewer may know (own tiles, revealed tiles, everything after the game ends). Other
* players' hidden tiles are sent as `{ color, revealed: false, wrong }` and addressed by position only.
*/
import { z } from 'zod';
import { fail, nextSeat, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine';
export type TColor = 'black' | 'white';
export type TileValue = number | 'joker';
export const COLORS: TColor[] = ['black', 'white'];
export const COLOR_KO: Record<TColor, string> = { black: '검은색', white: '흰색' };
export const MAX_N = 11;
// ---------------------------------------------------------------- options
export const davinciOptionsSchema = z.object({
jokers: z.boolean().default(false).meta({ title: '조커 사용(검정·흰색 각 1개, 숫자 대신 "-")' }),
tieOrder: z
.enum(['black-left', 'white-left'])
.default('black-left')
.meta({ title: '같은 숫자일 때 색 순서', labels: { 'black-left': '검정이 왼쪽', 'white-left': '흰색이 왼쪽' } }),
startTiles: z
.union([z.literal('auto'), z.literal(3), z.literal(4), z.literal(5)])
.default('auto')
.meta({ title: '시작 타일 수', labels: { auto: '자동(2·3명 4개, 4명 3개)', 3: '3개', 4: '4개', 5: '5개' } }),
chooseColors: z.boolean().default(true).meta({ title: '타일을 가져올 때 색 고르기(끄면 무작위)' }),
emptyPoolPenalty: z
.enum(['reveal-own', 'none'])
.default('reveal-own')
.meta({ title: '더미가 빈 뒤 틀렸을 때', labels: { 'reveal-own': '내 숨은 타일 1개 공개', none: '벌칙 없음' } }),
turnSeconds: z
.union([z.literal(20), z.literal(30), z.literal(45), z.literal(60)])
.default(30)
.meta({ title: '추리 제한 시간', labels: { 20: '20초', 30: '30초', 45: '45초', 60: '60초' } }),
deductionHelper: z.boolean().default(false).meta({ title: '가능한 숫자 후보 표시(초보 도움)' }),
});
export type DavinciOptions = z.infer<typeof davinciOptionsSchema>;
// ---------------------------------------------------------------- actions
const colorSchema = z.enum(['black', 'white']);
export const davinciActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('chooseStart'), black: z.number().int().min(0).max(12), white: z.number().int().min(0).max(12) }),
z.object({ type: z.literal('draw'), color: colorSchema.optional() }),
// Value range / integer checks live in validate so the player gets a Korean reason.
z.object({ type: z.literal('guess'), target: z.string().max(64), index: z.number().int().min(0).max(40), value: z.union([z.number(), z.literal('joker')]) }),
z.object({ type: z.literal('continue') }),
z.object({ type: z.literal('stop') }),
z.object({ type: z.literal('placeJoker'), index: z.number().int().min(0).max(40) }),
z.object({ type: z.literal('revealOwn'), index: z.number().int().min(0).max(40) }),
]);
export type DavinciClientAction = z.infer<typeof davinciActionSchema>;
/** Client actions plus system-only actions (timer / leaving), which are not in the schema. */
export type DavinciAction = DavinciClientAction | { type: 'timeout' } | { type: 'leave' };
// ---------------------------------------------------------------- state
export interface RowTile {
id: string;
revealed: boolean;
/** Values already guessed wrong for this tile (public). */
wrong: TileValue[];
}
export type DavinciPhase =
| { kind: 'chooseStart'; picks: Record<PlayerId, { black: number; white: number } | null> }
| { kind: 'draw' }
| { kind: 'guess' }
| { kind: 'afterCorrect' }
| { kind: 'placeJoker'; reveal: boolean }
| { kind: 'revealOwn' }
| { kind: 'finished' };
export type PhaseKind = DavinciPhase['kind'];
export interface DavinciGuess {
by: PlayerId;
target: PlayerId;
/** 0-based position in the target's row at the time of the guess. */
index: number;
color: TColor;
said: TileValue;
correct: boolean;
auto: boolean;
}
export interface DavinciFinal {
ranking: PlayerId[][];
winner: PlayerId;
summary: string;
reason: 'normal' | 'resign';
}
export interface DavinciState {
options: DavinciOptions;
seats: PlayerId[];
startCount: number;
/** Hidden from everyone; drawn from the front. */
pool: { black: string[]; white: string[] };
/** Jokers wait here until the start tiles are dealt (start tiles never contain a joker). */
jokerReserve: string[];
rows: Record<PlayerId, RowTile[]>;
phase: DavinciPhase;
current: PlayerId;
/** This turn's drawn tile (only the drawer knows the number). */
pending: string | null;
alive: Record<PlayerId, boolean>;
left: Record<PlayerId, boolean>;
eliminationOrder: PlayerId[];
stats: Record<PlayerId, { guesses: number; correct: number }>;
history: DavinciGuess[];
lastPlaced: { player: PlayerId; index: number; revealed: boolean } | null;
turnNo: number;
/** Consecutive turns with a timeout; at 3 the deadline drops to 5 s. */
idle: Record<PlayerId, number>;
idleTurn: Record<PlayerId, number>;
phaseStartedAt: number;
deadlineAt: number | null;
seq: number;
final: DavinciFinal | null;
}
// ---------------------------------------------------------------- view
export interface DavinciTileView {
color: TColor;
revealed: boolean;
/** Present only when the viewer may know it (own tile, revealed, or game over). */
n?: TileValue;
id?: string;
wrong: TileValue[];
/** deductionHelper: values still possible from the viewer's information. */
candidates?: TileValue[];
}
export interface DavinciView {
options: DavinciOptions;
me: PlayerId | null;
seats: PlayerId[];
phase: PhaseKind;
current: PlayerId;
startCount: number;
rows: Record<PlayerId, DavinciTileView[]>;
pool: { black: number; white: number };
pending: { color: TColor; n?: TileValue; id?: string } | null;
/** chooseStart: who has submitted (others' choices stay secret). */
picked: Record<PlayerId, boolean> | null;
myPick: { black: number; white: number } | null;
/** chooseStart: how many of each colour I may still take. */
pickLimits: { black: number; white: number } | null;
alive: Record<PlayerId, boolean>;
left: Record<PlayerId, boolean>;
eliminationOrder: PlayerId[];
stats: Record<PlayerId, { guesses: number; correct: number }>;
history: DavinciGuess[];
lastPlaced: DavinciState['lastPlaced'];
idle: Record<PlayerId, number>;
deadlineAt: number | null;
final: DavinciFinal | null;
}
// ---------------------------------------------------------------- tiles
const CHOOSE_START_MS = 15_000;
const SHORT_MS = 10_000;
const IDLE_MS = 5_000;
const IDLE_TURNS = 3;
export function tileOf(id: string): { color: TColor; n: TileValue } {
const color: TColor = id[0] === 'b' ? 'black' : 'white';
const rest = id.slice(1);
return { color, n: rest === 'J' ? 'joker' : Number(rest) };
}
const tileId = (color: TColor, n: TileValue) => `${color[0]}${n === 'joker' ? 'J' : n}`;
export const allTileIds = (jokers: boolean): string[] => [
...COLORS.flatMap((c) => Array.from({ length: MAX_N + 1 }, (_, n) => tileId(c, n))),
...(jokers ? COLORS.map((c) => tileId(c, 'joker')) : []),
];
/** Sort key of a numbered tile (lower = further left). */
export function sortKey(color: TColor, n: number, tieOrder: DavinciOptions['tieOrder']): number {
const first: TColor = tieOrder === 'black-left' ? 'black' : 'white';
return n * 2 + (color === first ? 0 : 1);
}
/** Server-computed slot for a numbered tile: right after the rightmost numbered tile that must precede it (jokers keep their place). */
export function insertIndex(row: readonly { color: TColor; n: TileValue }[], color: TColor, n: number, tieOrder: DavinciOptions['tieOrder']): number {
const k = sortKey(color, n, tieOrder);
let at = 0;
row.forEach((t, i) => {
if (t.n !== 'joker' && sortKey(t.color, t.n, tieOrder) < k) at = i + 1;
});
return at;
}
export function startCountFor(o: DavinciOptions, players: number): number {
return o.startTiles === 'auto' ? (players >= 4 ? 3 : 4) : o.startTiles;
}
const hiddenCount = (row: readonly RowTile[]) => row.reduce((a, t) => a + (t.revealed ? 0 : 1), 0);
const aliveSeats = (s: DavinciState) => s.seats.filter((p) => s.alive[p]);
const isValue = (v: unknown, jokers: boolean): v is TileValue =>
(v === 'joker' && jokers) || (typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= MAX_N);
// ---------------------------------------------------------------- deduction (public + own info only)
/**
* Values the viewer can still consider for `rows[target][index]`, computed from a view only
* (revealed numbers, the viewer's own numbers, colours, positions and wrong guesses).
* Sound: the true value is always included. Used by the helper and by the timeout auto-guess.
*/
export function candidatesFor(
rows: Record<PlayerId, DavinciTileView[]>,
pending: DavinciView['pending'],
target: PlayerId,
index: number,
o: Pick<DavinciOptions, 'jokers' | 'tieOrder'>,
): TileValue[] {
const row = rows[target] ?? [];
const tile = row[index];
if (!tile || tile.n !== undefined) return [];
const known = new Set<string>();
for (const r of Object.values(rows)) for (const t of r) if (t.n !== undefined) known.add(tileId(t.color, t.n));
if (pending?.n !== undefined) known.add(tileId(pending.color, pending.n));
let lo = -Infinity;
let hi = Infinity;
for (let i = index - 1; i >= 0; i--) {
const t = row[i]!;
if (t.n !== undefined && t.n !== 'joker') {
lo = sortKey(t.color, t.n, o.tieOrder);
break;
}
}
for (let i = index + 1; i < row.length; i++) {
const t = row[i]!;
if (t.n !== undefined && t.n !== 'joker') {
hi = sortKey(t.color, t.n, o.tieOrder);
break;
}
}
const out: TileValue[] = [];
for (let n = 0; n <= MAX_N; n++) {
if (known.has(tileId(tile.color, n)) || tile.wrong.includes(n)) continue;
const k = sortKey(tile.color, n, o.tieOrder);
if (k > lo && k < hi) out.push(n);
}
if (o.jokers && !known.has(tileId(tile.color, 'joker')) && !tile.wrong.includes('joker')) out.push('joker');
return out;
}
// ---------------------------------------------------------------- helpers
function refreshDeadline(s: DavinciState, now: number, phaseChanged: boolean): void {
if (!phaseChanged) return;
s.phaseStartedAt = now;
let ms: number | null;
switch (s.phase.kind) {
case 'finished':
ms = null;
break;
case 'chooseStart':
ms = CHOOSE_START_MS;
break;
case 'guess':
ms = s.options.turnSeconds * 1000;
break;
default:
ms = SHORT_MS;
}
if (ms !== null && s.phase.kind !== 'chooseStart' && (s.idle[s.current] ?? 0) >= IDLE_TURNS) ms = IDLE_MS;
s.deadlineAt = ms === null ? null : now + ms;
}
function insertTile(s: DavinciState, p: PlayerId, id: string, revealed: boolean, events: GameEvent[], at?: number): void {
const row = s.rows[p]!;
const t = tileOf(id);
const index = at ?? (t.n === 'joker' ? row.length : insertIndex(row.map((r) => tileOf(r.id)), t.color, t.n, s.options.tieOrder));
row.splice(index, 0, { id, revealed, wrong: [] });
s.lastPlaced = { player: p, index, revealed };
events.push(revealed ? { type: 'placed', player: p, index, revealed, color: t.color, n: t.n } : { type: 'placed', player: p, index, revealed, color: t.color });
}
function eliminate(s: DavinciState, p: PlayerId, events: GameEvent[]): void {
if (!s.alive[p]) return;
s.alive[p] = false;
s.eliminationOrder.push(p);
events.push({ type: 'eliminated', player: p });
}
/** Ends the game if only one player keeps hidden tiles. Returns true when finished. */
function checkFinish(s: DavinciState, events: GameEvent[], byLeave = false): boolean {
const alive = aliveSeats(s);
if (alive.length > 1) return false;
if (s.pending) {
const owner = s.current;
if (s.rows[owner]) insertTile(s, owner, s.pending, !s.alive[owner], events);
s.pending = null;
}
const winner = alive[0] ?? s.eliminationOrder[s.eliminationOrder.length - 1]!;
const ranking: PlayerId[][] = [[winner], ...[...s.eliminationOrder].reverse().filter((p) => p !== winner).map((p) => [p])];
// Players who never got tiles (left during the start choice) are ranked last, in seat order.
for (const p of s.seats) if (!ranking.some((g) => g.includes(p))) ranking.push([p]);
const left = hiddenCount(s.rows[winner] ?? []);
const others = s.seats.length - 1;
const reason: DavinciFinal['reason'] = byLeave ? 'resign' : 'normal';
const st = s.stats[winner]!;
const summary =
reason === 'resign'
? `마지막 상대가 나가서 게임이 끝났어요. (추리 ${st.guesses}번 중 ${st.correct}번 맞힘)`
: `숨은 타일 ${left}개가 끝까지 풀리지 않아 이겼어요! (상대 ${others}명 탈락 · 추리 ${st.guesses}번 중 ${st.correct}번 맞힘)`;
s.final = { ranking, winner, summary, reason };
s.phase = { kind: 'finished' };
events.push({ type: 'gameEnded', winner });
return true;
}
function endTurn(s: DavinciState, events: GameEvent[]): void {
s.pending = null;
if (checkFinish(s, events)) return;
const i = s.seats.indexOf(s.current);
s.current = s.seats[nextSeat(i, s.seats.length, (j) => !s.alive[s.seats[j]!])]!;
s.turnNo += 1;
s.phase = s.pool.black.length + s.pool.white.length > 0 ? { kind: 'draw' } : { kind: 'guess' };
events.push({ type: 'turn', player: s.current });
}
/** After the start tiles are dealt: sort rows, shuffle the jokers into the pool, start the first turn. */
function afterDeal(s: DavinciState, rng: Rng, events: GameEvent[]): void {
for (const p of s.seats) {
s.rows[p]!.sort((a, b) => {
const x = tileOf(a.id);
const y = tileOf(b.id);
return sortKey(x.color, x.n as number, s.options.tieOrder) - sortKey(y.color, y.n as number, s.options.tieOrder);
});
}
for (const j of s.jokerReserve) {
const pile = s.pool[tileOf(j).color];
pile.splice(rng.int(pile.length + 1), 0, j);
}
s.jokerReserve = [];
if (!s.alive[s.current]) s.current = s.seats[nextSeat(s.seats.indexOf(s.current), s.seats.length, (j) => !s.alive[s.seats[j]!])]!;
s.phase = { kind: 'draw' };
events.push({ type: 'dealt', counts: Object.fromEntries(s.seats.map((p) => [p, s.rows[p]!.length])) });
events.push({ type: 'turn', player: s.current });
}
/** chooseStart: once every remaining player has chosen, deal from the front of each colour pile. */
function dealIfReady(s: DavinciState, rng: Rng, events: GameEvent[]): void {
const ph = s.phase;
if (ph.kind !== 'chooseStart' || !s.seats.every((p) => !s.alive[p] || ph.picks[p])) return;
for (const p of s.seats) {
const pick = ph.picks[p];
if (!pick || !s.alive[p]) continue;
const ids = [...s.pool.black.splice(0, pick.black), ...s.pool.white.splice(0, pick.white)];
s.rows[p] = ids.map((id) => ({ id, revealed: false, wrong: [] }));
}
afterDeal(s, rng, events);
}
function pickLimits(s: DavinciState): { black: number; white: number } {
const lim = { black: s.pool.black.length, white: s.pool.white.length };
if (s.phase.kind === 'chooseStart') {
for (const pick of Object.values(s.phase.picks)) {
if (!pick) continue;
lim.black -= pick.black;
lim.white -= pick.white;
}
}
return lim;
}
/** Timeout choice for the start: as even as possible (odd → one more black), within what is left. */
export function autoPick(s: DavinciState): { black: number; white: number } {
const n = s.startCount;
const lim = pickLimits(s);
let black = Math.min(Math.ceil(n / 2), lim.black);
let white = n - black;
if (white > lim.white) {
white = lim.white;
black = n - white;
}
return { black, white };
}
/**
* Deterministic auto-guess (§8.5) from the player's own view only: the living opponent with the fewest
* hidden tiles (ties: clockwise from me), their leftmost hidden tile, the smallest possible value.
*/
export function autoGuess(s: DavinciState, player: PlayerId): { type: 'guess'; target: PlayerId; index: number; value: TileValue } {
const v = davinci.view(s, player);
const me = v.seats.indexOf(player);
const order = v.seats.map((_, k) => v.seats[(me + 1 + k) % v.seats.length]!).filter((p) => p !== player && v.alive[p]);
let target = order[0]!;
let best = Infinity;
for (const p of order) {
const h = v.rows[p]!.filter((t) => !t.revealed).length;
if (h > 0 && h < best) {
best = h;
target = p;
}
}
const index = v.rows[target]!.findIndex((t) => !t.revealed);
const cands = candidatesFor(v.rows, v.pending, target, index, v.options);
const nums = cands.filter((c): c is number => c !== 'joker');
const value: TileValue = nums.length ? Math.min(...nums) : cands.length ? 'joker' : 0;
return { type: 'guess', target, index, value };
}
/** The concrete action a timeout stands for in the current state (docs §8.5). */
export function autoAction(s: DavinciState, player: PlayerId): DavinciClientAction {
switch (s.phase.kind) {
case 'chooseStart':
return { type: 'chooseStart', ...autoPick(s) };
case 'draw':
if (!s.options.chooseColors) return { type: 'draw' };
return { type: 'draw', color: s.pool.white.length > s.pool.black.length ? 'white' : 'black' };
case 'guess':
return autoGuess(s, player);
case 'afterCorrect':
return { type: 'stop' };
case 'placeJoker':
return { type: 'placeJoker', index: s.rows[player]!.length };
case 'revealOwn':
return { type: 'revealOwn', index: s.rows[player]!.findIndex((t) => !t.revealed) };
case 'finished':
throw new Error('davinci: no auto action after the game');
}
}
function waiting(s: DavinciState): PlayerId[] {
if (s.phase.kind === 'finished') return [];
if (s.phase.kind === 'chooseStart') {
const picks = s.phase.picks;
return s.seats.filter((p) => s.alive[p] && !picks[p]);
}
return [s.current];
}
function validateClient(s: DavinciState, actor: PlayerId, a: DavinciClientAction): Validation {
const o = s.options;
const ph = s.phase;
if (a.type === 'chooseStart') {
if (ph.kind !== 'chooseStart') return fail('지금은 시작 타일을 고를 때가 아니에요.');
if (ph.picks[actor]) return fail('이미 골랐어요.');
if (a.black + a.white !== s.startCount) return fail(`시작 타일 ${s.startCount}개를 골라 주세요.`);
const lim = pickLimits(s);
if (a.black > lim.black) return fail(lim.black === 0 ? '검은색 타일이 더 이상 없어요.' : `검은색은 ${lim.black}개까지 고를 수 있어요.`);
if (a.white > lim.white) return fail(lim.white === 0 ? '흰색 타일이 더 이상 없어요.' : `흰색은 ${lim.white}개까지 고를 수 있어요.`);
return ok;
}
if (ph.kind === 'chooseStart') return fail('먼저 시작 타일을 골라 주세요.');
if (s.current !== actor) return fail('지금은 내 차례가 아니에요.');
switch (a.type) {
case 'draw': {
if (ph.kind !== 'draw') return fail('지금은 타일을 가져올 때가 아니에요.');
if (!o.chooseColors) return a.color ? fail('이 방은 색을 고르지 않고 무작위로 가져와요.') : ok;
if (!a.color) return fail('가져올 색을 골라 주세요.');
if (s.pool[a.color].length === 0) return fail(`${COLOR_KO[a.color]} 타일이 더 이상 없어요.`);
return ok;
}
case 'guess': {
if (ph.kind !== 'guess') return fail('지금은 추리할 때가 아니에요.');
if (a.target === actor) return fail('자기 타일은 고를 수 없어요.');
if (!s.seats.includes(a.target)) return fail('이 게임의 플레이어가 아니에요.');
if (!s.alive[a.target]) return fail('이미 탈락한 사람의 타일이에요.');
const t = s.rows[a.target]![a.index];
if (!t) return fail('그 자리에는 타일이 없어요.');
if (t.revealed) return fail('이미 공개된 타일이에요.');
if (a.value === 'joker' && !o.jokers) return fail('이 방은 조커를 쓰지 않아요.');
if (!isValue(a.value, o.jokers)) return fail('0부터 11 사이 숫자를 골라 주세요.');
return ok;
}
case 'continue':
if (ph.kind !== 'afterCorrect') return fail('맞힌 뒤에만 계속할 수 있어요.');
return aliveSeats(s).some((p) => p !== actor) ? ok : fail('남은 상대가 없어요.');
case 'stop':
return ph.kind === 'afterCorrect' ? ok : fail('맞힌 뒤에만 멈출 수 있어요.');
case 'placeJoker':
if (ph.kind !== 'placeJoker') return fail('지금은 조커를 놓을 때가 아니에요.');
return a.index >= 0 && a.index <= s.rows[actor]!.length ? ok : fail('그 자리에는 놓을 수 없어요.');
case 'revealOwn': {
if (ph.kind !== 'revealOwn') return fail('지금은 내 타일을 공개할 때가 아니에요.');
const t = s.rows[actor]![a.index];
if (!t) return fail('그 자리에는 타일이 없어요.');
return t.revealed ? fail('이미 공개된 타일이에요.') : ok;
}
}
}
function applyClient(s: DavinciState, actor: PlayerId, a: DavinciClientAction, rng: Rng, events: GameEvent[], auto: boolean): void {
switch (a.type) {
case 'chooseStart': {
const ph = s.phase as Extract<DavinciPhase, { kind: 'chooseStart' }>;
ph.picks[actor] = { black: a.black, white: a.white };
events.push({ type: 'picked', player: actor });
dealIfReady(s, rng, events);
break;
}
case 'draw': {
let color = a.color;
if (!color) {
const nb = s.pool.black.length;
color = rng.int(nb + s.pool.white.length) < nb ? 'black' : 'white';
}
s.pending = s.pool[color].shift()!;
s.phase = { kind: 'guess' };
events.push({ type: 'drawn', player: actor, color });
break;
}
case 'guess': {
const t = s.rows[a.target]![a.index]!;
const real = tileOf(t.id);
const correct = real.n === a.value;
s.stats[actor]!.guesses += 1;
s.history.push({ by: actor, target: a.target, index: a.index, color: real.color, said: a.value, correct, auto });
events.push({ type: 'guessed', by: actor, target: a.target, index: a.index, value: a.value, correct });
if (correct) {
t.revealed = true;
s.stats[actor]!.correct += 1;
events.push({ type: 'revealed', player: a.target, index: a.index, color: real.color, n: real.n });
if (hiddenCount(s.rows[a.target]!) === 0) eliminate(s, a.target, events);
if (!checkFinish(s, events)) s.phase = { kind: 'afterCorrect' };
} else {
t.wrong.push(a.value);
if (s.pending) {
if (tileOf(s.pending).n === 'joker') s.phase = { kind: 'placeJoker', reveal: true };
else {
insertTile(s, actor, s.pending, true, events);
endTurn(s, events);
}
} else if (s.options.emptyPoolPenalty === 'reveal-own') s.phase = { kind: 'revealOwn' };
else endTurn(s, events);
}
break;
}
case 'continue':
s.phase = { kind: 'guess' };
break;
case 'stop':
if (s.pending && tileOf(s.pending).n === 'joker') s.phase = { kind: 'placeJoker', reveal: false };
else {
if (s.pending) insertTile(s, actor, s.pending, false, events);
endTurn(s, events);
}
break;
case 'placeJoker': {
const reveal = (s.phase as Extract<DavinciPhase, { kind: 'placeJoker' }>).reveal;
insertTile(s, actor, s.pending!, reveal, events, a.index);
endTurn(s, events);
break;
}
case 'revealOwn': {
const t = s.rows[actor]![a.index]!;
t.revealed = true;
const real = tileOf(t.id);
events.push({ type: 'revealed', player: actor, index: a.index, color: real.color, n: real.n, own: true });
if (hiddenCount(s.rows[actor]!) === 0) eliminate(s, actor, events);
endTurn(s, events);
break;
}
}
}
function applyLeave(s: DavinciState, actor: PlayerId, rng: Rng, events: GameEvent[]): void {
s.left[actor] = true;
events.push({ type: 'left', player: actor });
if (!s.alive[actor]) return;
if (s.phase.kind === 'chooseStart') {
// Leaving before the deal: out without tiles; the others are dealt as soon as they have all chosen.
delete s.phase.picks[actor];
eliminate(s, actor, events);
if (!checkFinish(s, events, true)) dealIfReady(s, rng, events);
return;
}
// Leaving in play: the leaver is out and their tiles are opened.
for (const t of s.rows[actor]!) t.revealed = true;
if (s.current === actor && s.pending) {
insertTile(s, actor, s.pending, true, events);
s.pending = null;
}
eliminate(s, actor, events);
if (checkFinish(s, events, true)) return;
if (s.current === actor) endTurn(s, events);
}
// ---------------------------------------------------------------- definition
export const davinci: GameDefinition<DavinciState, DavinciAction, DavinciView, DavinciOptions> = {
id: 'davinci-code',
nameKo: '다빈치 코드',
minPlayers: 2,
maxPlayers: 4,
stateVersion: 1,
defaultOptions: davinciOptionsSchema.parse({}),
optionsSchema: davinciOptionsSchema as unknown as z.ZodType<DavinciOptions>,
actionSchema: davinciActionSchema as unknown as z.ZodType<DavinciAction>,
setup({ players, options, rng, now }) {
if (players.length < 2 || players.length > 4) throw new Error(`davinci-code: ${players.length} players not allowed`);
const startCount = startCountFor(options, players.length);
const per = <T>(f: (p: PlayerId) => T) => Object.fromEntries(players.map((p) => [p, f(p)])) as Record<PlayerId, T>;
const first = players[rng.int(players.length)]!;
const numbered = allTileIds(false);
const jokers = options.jokers ? COLORS.map((c) => tileId(c, 'joker')) : [];
const s: DavinciState = {
options,
seats: [...players],
startCount,
pool: { black: [], white: [] },
jokerReserve: jokers,
rows: per(() => []),
phase: { kind: 'chooseStart', picks: per(() => null) },
current: first,
pending: null,
alive: per(() => true),
left: per(() => false),
eliminationOrder: [],
stats: per(() => ({ guesses: 0, correct: 0 })),
history: [],
lastPlaced: null,
turnNo: 0,
idle: per(() => 0),
idleTurn: per(() => -1),
phaseStartedAt: now,
deadlineAt: null,
seq: 0,
final: null,
};
const events: GameEvent[] = [];
if (options.chooseColors) {
for (const c of COLORS) s.pool[c] = rng.shuffle(numbered.filter((id) => tileOf(id).color === c));
} else {
const deck = rng.shuffle(numbered);
for (const p of players) s.rows[p] = deck.splice(0, startCount).map((id) => ({ id, revealed: false, wrong: [] }));
for (const c of COLORS) s.pool[c] = deck.filter((id) => tileOf(id).color === c);
afterDeal(s, rng, events);
}
refreshDeadline(s, now, true);
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.alive[actor]) return fail('탈락해서 더 할 수 없어요.');
if (a.type === 'timeout') return waiting(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.');
return validateClient(s, actor, a);
},
apply(prev, actor, a, { rng, now }) {
const s = structuredClone(prev);
const events: GameEvent[] = [];
const before = s.phase.kind;
if (a.type === 'leave') applyLeave(s, actor, rng, events);
else if (a.type === 'timeout') {
const concrete = autoAction(s, actor);
const v = validateClient(s, actor, concrete);
if (!v.ok) throw new Error(`davinci: auto action rejected: ${v.reason}`);
if (s.phase.kind !== 'chooseStart' && s.idleTurn[actor] !== s.turnNo) {
s.idleTurn[actor] = s.turnNo;
s.idle[actor] = (s.idle[actor] ?? 0) + 1;
}
events.push({ type: 'timeout', player: actor });
applyClient(s, actor, concrete, rng, events, true);
} else {
s.idle[actor] = 0;
applyClient(s, actor, a, rng, events, false);
}
s.seq += 1;
// The start choice has one shared deadline; every other step restarts the clock.
refreshDeadline(s, now, !(before === 'chooseStart' && s.phase.kind === 'chooseStart'));
return { state: s, events };
},
view(s, viewer) {
const me = viewer && s.seats.includes(viewer) ? viewer : null;
const over = s.phase.kind === 'finished';
const rows: Record<PlayerId, DavinciTileView[]> = {};
for (const p of s.seats) {
rows[p] = s.rows[p]!.map((t) => {
const known = over || t.revealed || p === me;
if (!known) return { color: tileOf(t.id).color, revealed: false, wrong: [...t.wrong] };
const real = tileOf(t.id);
return { color: real.color, revealed: t.revealed, n: real.n, id: t.id, wrong: [...t.wrong] };
});
}
let pending: DavinciView['pending'] = null;
if (s.pending) {
const real = tileOf(s.pending);
pending = s.current === me ? { color: real.color, n: real.n, id: s.pending } : { color: real.color };
}
if (s.options.deductionHelper && !over) {
for (const p of s.seats) {
if (p === me) continue;
rows[p]!.forEach((t, i) => {
if (t.n === undefined) t.candidates = candidatesFor(rows, pending, p, i, s.options);
});
}
}
const ph = s.phase;
const choosing = ph.kind === 'chooseStart';
return {
options: s.options,
me,
seats: s.seats,
// Placing a drawn joker is secret: the others see the step before it (after 멈추기 → still deciding; after a
// wrong guess → still guessing), never "조커를 넣는 중".
phase: ph.kind === 'placeJoker' && me !== s.current ? (ph.reveal ? 'guess' : 'afterCorrect') : ph.kind,
current: s.current,
startCount: s.startCount,
rows,
pool: { black: s.pool.black.length, white: s.pool.white.length },
pending,
picked: choosing ? Object.fromEntries(s.seats.map((p) => [p, !!ph.picks[p]])) : null,
myPick: choosing && me ? (ph.picks[me] ?? null) : null,
pickLimits: choosing ? pickLimits(s) : null,
alive: s.alive,
left: s.left,
eliminationOrder: s.eliminationOrder,
stats: s.stats,
history: s.history,
lastPlaced: s.lastPlaced,
idle: s.idle,
deadlineAt: s.deadlineAt,
final: s.final,
};
},
activePlayers: waiting,
deadline(s) {
return s.phase.kind === 'finished' ? null : s.deadlineAt;
},
timeoutPlayers: waiting,
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 (!s.seats.includes(p) || !s.alive[p] || s.phase.kind === 'finished') return [];
const out: DavinciAction[] = [];
const ph = s.phase;
if (ph.kind === 'chooseStart') {
if (ph.picks[p]) return [];
const lim = pickLimits(s);
for (let b = 0; b <= s.startCount; b++) {
const w = s.startCount - b;
if (b <= lim.black && w <= lim.white) out.push({ type: 'chooseStart', black: b, white: w });
}
return out;
}
if (s.current !== p) return [];
switch (ph.kind) {
case 'draw':
if (!s.options.chooseColors) return [{ type: 'draw' }];
return COLORS.filter((c) => s.pool[c].length > 0).map((color) => ({ type: 'draw', color }));
case 'guess': {
const values: TileValue[] = [...Array.from({ length: MAX_N + 1 }, (_, n) => n), ...(s.options.jokers ? ['joker' as const] : [])];
for (const target of s.seats) {
if (target === p || !s.alive[target]) continue;
s.rows[target]!.forEach((t, index) => {
if (!t.revealed) for (const value of values) out.push({ type: 'guess', target, index, value });
});
}
return out;
}
case 'afterCorrect':
return [{ type: 'continue' }, { type: 'stop' }];
case 'placeJoker':
return Array.from({ length: s.rows[p]!.length + 1 }, (_, index) => ({ type: 'placeJoker', index }));
case 'revealOwn':
return s.rows[p]!.flatMap((t, index) => (t.revealed ? [] : [{ type: 'revealOwn' as const, index }]));
}
},
/** Ids of `player`'s hidden tiles and pending tile, plus the pool (secret to everyone). */
secretsOf(s, player) {
const pool = [...s.pool.black, ...s.pool.white, ...s.jokerReserve];
if (s.phase.kind === 'finished') return pool;
const own = (s.rows[player] ?? []).filter((t) => !t.revealed).map((t) => t.id);
if (s.current === player && s.pending) own.push(s.pending);
return [...own, ...pool];
},
};