M7: 달무티 규칙·화면·테스트

- 규칙 모듈 packages/games/src/dalmuti: 80장(광대 2장) 덱, 첫 신분 뽑기(동점 재뽑기),
  신분 순서 분배, 혁명 확인 단계(혁명/대혁명), 세금 자동 이동과 돌려주기, 트릭 진행
  (광대 와일드·13, passLocksOut), 라운드 종료와 순위 점수/마지막 라운드 순위,
  시간 초과 자동 행동(리드: 가장 큰 숫자 전부, 따라 내기: 패스, 세금: 가장 큰 숫자),
  연속 3회 시간 초과 시 5초 마감, 나가도 탈락 없이 자동 진행, view 정보 숨김
- 테스트: 문서 10절 시나리오 전부 + 1,000 시드 무작위 대국(카드 보존, 유출 검사,
  onTimeout 합법, 결정성) + 엔진 randomPlayout
- 화면 apps/web/src/games/dalmuti: 자체 카드 그림, 숫자별 묶음 선택·장수 조절·광대 섞기,
  내기/패스, 바닥 기준 표시, 신분 자리, 혁명 확인·세금 교환 화면, 규칙·옵션
- 등록: GAMES, catalog, registry, GAME_ICON
- E2E: PC 방장 + 휴대폰 3명, 1라운드 끝까지 진행 후 2라운드 세금 교환 화면 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-05 14:49:44 +09:00
parent 559fb8507c
commit dfe4ce1ca4
9 changed files with 2855 additions and 0 deletions

View File

@@ -0,0 +1,678 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, randomPlayout, seedN, type PlayerId, type RngState } from '@bg/engine';
import {
FULL_DECK,
allCardIds,
dalmuti,
deckFor,
drawFirstRanks,
finalOf,
type DCard,
type DalmutiAction,
type DalmutiOptions,
type DalmutiState,
type DalmutiView,
} from './index';
// ---------------------------------------------------------------- helpers
const BY_ID = new Map(FULL_DECK.map((c) => [c.id, c]));
const card = (id: string): DCard => {
const c = BY_ID.get(id);
if (!c) throw new Error(`no card ${id}`);
return c;
};
/** k-th copy of number n ("c7-2"). */
const C = (n: number, k = 1) => `c${n}-${k}`;
const J1 = 'j1';
const J2 = 'j2';
const P5 = ['A', 'B', 'C', 'D', 'E'];
const P4 = ['A', 'B', 'C', 'D'];
let clock = 1_000_000;
function make(opts: Partial<DalmutiOptions> = {}, players = P5, seed = 1): DalmutiState {
const options = dalmuti.optionsSchema.parse(opts);
return dalmuti.setup({ players, options, rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
}
/** Seats `order`, gives hands (rest of the deck → discard) and starts a trick (optionally with a top set). */
function rig(
s: DalmutiState,
r: { order?: string[]; hands: Record<string, string[]>; current?: string; top?: { by: string; ids: string[] } },
): DalmutiState {
if (r.order) s.order = [...r.order];
for (const p of s.players) s.hands[p] = (r.hands[p] ?? []).map(card);
const used = new Set([...Object.values(r.hands).flat(), ...(r.top?.ids ?? [])]);
s.discard = deckFor(s.options.removeHighCards)
.filter((c) => !used.has(c.id))
.map((c) => c.id);
s.phase = { kind: 'playing' };
s.finishOrder = [];
s.taxLog = [];
const lead = r.current ?? s.order[0]!;
s.trick = { leader: r.top?.by ?? lead, top: null, passesSinceTop: [], lockedOut: [], pile: [] };
if (r.top) {
const cards = r.top.ids.map(card);
const nums = cards.filter((c) => c.n !== 13);
const top = { cardIds: r.top.ids, count: cards.length, rank: nums.length ? nums[0]!.n : 13, by: r.top.by };
s.trick.top = top;
s.trick.pile = [top];
}
s.current = lead;
return s;
}
const act = (s: DalmutiState, p: string, a: DalmutiAction): DalmutiState => {
const v = dalmuti.validate(s, p, a);
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
return dalmuti.apply(s, p, a, { rng: SeededRng.fromSeed([3, 3, 3, 3]), now: (clock += 1000) }).state;
};
const play = (s: DalmutiState, p: string, ids: string[]) => act(s, p, { type: 'play', cardIds: ids });
const pass = (s: DalmutiState, p: string) => act(s, p, { type: 'pass' });
const reject = (s: DalmutiState, p: string, a: DalmutiAction): string | null => {
const v = dalmuti.validate(s, p, a);
return v.ok ? null : v.reason;
};
const ids = (s: DalmutiState, p: string) => s.hands[p]!.map((c) => c.id);
const nums = (s: DalmutiState, p: string) => s.hands[p]!.map((c) => c.n);
const confirmAll = (s: DalmutiState, except: Record<string, DalmutiAction> = {}) => {
for (const p of s.players) s = act(s, p, except[p] ?? { type: 'confirmHand' });
return s;
};
/** A revolutionCheck state with given hands (5 players, order A..E unless given). */
function atRevolutionCheck(hands: Record<string, string[]>, opts: Partial<DalmutiOptions> = {}, order = P5): DalmutiState {
const s = rig(make(opts), { order, hands });
s.phase = { kind: 'revolutionCheck', confirmed: Object.fromEntries(s.players.map((p) => [p, false])) };
return s;
}
/** Splits the full deck so that the given cards land where wanted and the rest fill hands round-robin. */
function handsWith(order: string[], fixed: Record<string, string[]>): Record<string, string[]> {
const taken = new Set(Object.values(fixed).flat());
const rest = FULL_DECK.map((c) => c.id).filter((id) => !taken.has(id));
const hands: Record<string, string[]> = Object.fromEntries(order.map((p) => [p, [...(fixed[p] ?? [])]]));
const per = Math.floor(80 / order.length);
for (const p of order) while (hands[p]!.length < per) hands[p]!.push(rest.shift()!);
for (let i = 0; rest.length; i++) hands[order[i % order.length]!]!.push(rest.shift()!);
return hands;
}
// ---------------------------------------------------------------- deck / setup
describe('덱과 셋업 (§3, §4)', () => {
test('80 cards: n copies of n, 2 jesters; removeHighCards → 38', () => {
expect(FULL_DECK).toHaveLength(80);
for (let n = 1; n <= 12; n++) expect(FULL_DECK.filter((c) => c.n === n)).toHaveLength(n);
expect(FULL_DECK.filter((c) => c.n === 13)).toHaveLength(2);
expect(new Set(FULL_DECK.map((c) => c.id)).size).toBe(80);
expect(deckFor(true)).toHaveLength(38);
expect(deckFor(true).some((c) => c.n >= 9 && c.n <= 12)).toBe(false);
});
test('6 players: 14, 14, 13, 13, 13, 13 in rank order; all deals add up', () => {
const s = make({}, ['A', 'B', 'C', 'D', 'E', 'F'], 3);
expect(s.order.map((p) => s.hands[p]!.length)).toEqual([14, 14, 13, 13, 13, 13]);
const sizes: Record<number, number[]> = { 4: [20, 20, 20, 20], 5: [16, 16, 16, 16, 16], 7: [12, 12, 12, 11, 11, 11, 11], 8: [10, 10, 10, 10, 10, 10, 10, 10] };
for (const [n, want] of Object.entries(sizes)) {
const t = make({}, Array.from({ length: Number(n) }, (_, i) => `P${i}`), 4);
expect(t.order.map((p) => t.hands[p]!.length)).toEqual(want);
expect(allCardIds(t).sort()).toEqual(FULL_DECK.map((c) => c.id).sort());
}
const r = make({ removeHighCards: true }, Array.from({ length: 8 }, (_, i) => `P${i}`), 4);
expect(r.order.map((p) => r.hands[p]!.length)).toEqual([5, 5, 5, 5, 5, 5, 4, 4]);
});
test('player range 4..8', () => {
expect(dalmuti.minPlayers).toBe(4);
expect(dalmuti.maxPlayers).toBe(8);
expect(() => make({}, ['A', 'B', 'C'])).toThrow();
expect(() => make({}, 'ABCDEFGHI'.split(''))).toThrow();
});
test('first rank draw: same seed → same result; ties re-draw until the order is fixed (lower first)', () => {
expect(JSON.stringify(make({}, P5, 9))).toBe(JSON.stringify(make({}, P5, 9)));
let sawTie = 0;
for (let seed = 1; seed <= 400; seed++) {
const players = Array.from({ length: 8 }, (_, i) => `P${i}`);
const { order, draws } = drawFirstRanks(players, FULL_DECK as DCard[], SeededRng.fromSeed(seedN(seed)));
expect([...order].sort()).toEqual([...players].sort());
if (Object.values(draws).some((d) => d.length > 1)) sawTie++;
// Lexicographic on the draw sequence: tied players share a prefix and re-drew together.
for (let i = 0; i + 1 < order.length; i++) {
const a = draws[order[i]!]!;
const b = draws[order[i + 1]!]!;
const k = a.findIndex((x, j) => x !== b[j]);
expect(k).toBeGreaterThanOrEqual(0);
expect(a[k]!).toBeLessThan(b[k]!);
}
}
expect(sawTie).toBeGreaterThan(10);
const s = make({}, P5, 9);
expect(s.firstDraw).not.toBeNull();
expect(make({ firstRanking: 'random' }, P5, 9).firstDraw).toBeNull();
});
test('revolution on → everyone confirms first; off → tax right away', () => {
expect(make().phase.kind).toBe('revolutionCheck');
const s = make({ revolution: false });
expect(s.phase.kind).toBe('taxReturn');
const o = s.order as string[];
expect(s.taxLog.map((t) => [t.from, t.to, t.cardIds.length])).toEqual([
[o[4]!, o[0]!, 2],
[o[3]!, o[1]!, 1],
]);
});
});
// ---------------------------------------------------------------- tax
describe('세금 (§4-5)', () => {
const bottomHand = [J1, J2, C(3, 1), C(3, 2), C(7, 1), C(9, 1), C(12, 1)];
const hands = () => handsWith(P5, { E: bottomHand, D: [C(2, 1), C(5, 1), C(11, 1)] });
test('jesterTaxable off: 대농노 [광대, 광대, 3, 3, 7…] gives 3, 3; 소농노 gives its lowest number', () => {
let s = atRevolutionCheck(hands(), { jesterTaxable: false });
const dBefore = s.hands.D!.map((c) => c.n).filter((n) => n !== 13);
s = confirmAll(s);
expect(s.phase.kind).toBe('taxReturn');
expect(s.taxLog[0]).toEqual({ kind: 'tax', from: 'E', to: 'A', cardIds: [C(3, 1), C(3, 2)] });
expect(s.taxLog[1]!.from).toBe('D');
expect(s.taxLog[1]!.to).toBe('B');
expect(card(s.taxLog[1]!.cardIds[0]!).n).toBe(Math.min(...dBefore));
expect(ids(s, 'E')).toContain(J1);
expect(ids(s, 'A')).toEqual(expect.arrayContaining([C(3, 1), C(3, 2)]));
});
test('jesterTaxable on: the two jesters go', () => {
const s = confirmAll(atRevolutionCheck(hands(), { jesterTaxable: true }));
expect(s.taxLog[0]!.cardIds).toEqual([J1, J2]);
});
test('returning: 대달무티 may give back what it just got; wrong count refused; both done → A leads', () => {
let s = confirmAll(atRevolutionCheck(hands()));
const got = s.taxLog[0]!.cardIds;
expect(reject(s, 'A', { type: 'returnTax', cardIds: [got[0]!] })).toBe('돌려줄 카드 2장을 골라 주세요.');
expect(reject(s, 'B', { type: 'returnTax', cardIds: [ids(s, 'B')[0]!, ids(s, 'B')[1]!] })).toBe('돌려줄 카드 1장을 골라 주세요.');
expect(reject(s, 'C', { type: 'returnTax', cardIds: [ids(s, 'C')[0]!] })).toBe('돌려줄 카드가 없어요.');
expect(reject(s, 'A', { type: 'returnTax', cardIds: [got[0]!, ids(s, 'E')[0]!] })).toBe('손에 없는 카드예요.');
s = act(s, 'A', { type: 'returnTax', cardIds: [...got] });
expect(ids(s, 'E')).toEqual(expect.arrayContaining([C(3, 1), C(3, 2)]));
expect(s.phase.kind).toBe('taxReturn');
expect(reject(s, 'A', { type: 'returnTax', cardIds: [...got] })).toBe('이미 카드를 돌려줬어요.');
s = act(s, 'B', { type: 'returnTax', cardIds: [ids(s, 'B')[0]!] });
expect(s.phase.kind).toBe('playing');
expect(s.current).toBe('A');
expect(s.hands.A!.length).toBe(16);
expect(allCardIds(s).sort()).toEqual(FULL_DECK.map((c) => c.id).sort());
});
test('4 players: 소달무티 ↔ 소농노 and 대달무티 ↔ 대농노 only', () => {
const s = confirmAll(atRevolutionCheck(handsWith(P4, {}), {}, P4));
expect(s.taxLog.map((t) => [t.from, t.to, t.cardIds.length])).toEqual([
['D', 'A', 2],
['C', 'B', 1],
]);
});
});
// ---------------------------------------------------------------- revolution
describe('혁명 (§4-4)', () => {
test('a commoner with both jesters declares → no tax, same ranks, 대달무티 leads', () => {
const s0 = atRevolutionCheck(handsWith(P5, { C: [J1, J2] }));
expect(reject(s0, 'A', { type: 'confirmHand', declareRevolution: true })).toBe('광대 2장이 있어야 혁명할 수 있어요.');
const s = confirmAll(s0, { C: { type: 'confirmHand', declareRevolution: true } });
expect(s.revolution).toBe('revolution');
expect(s.revolutionBy).toBe('C');
expect(s.taxLog).toEqual([]);
expect(s.order).toEqual(P5);
expect(s.phase.kind).toBe('playing');
expect(s.current).toBe('A');
});
test('대농노 declares → great revolution: order reversed, the new 대달무티 leads, no tax', () => {
const s = confirmAll(atRevolutionCheck(handsWith(P5, { E: [J1, J2] })), { E: { type: 'confirmHand', declareRevolution: true } });
expect(s.revolution).toBe('great');
expect(s.order).toEqual(['E', 'D', 'C', 'B', 'A']);
expect(s.current).toBe('E');
expect(s.taxLog).toEqual([]);
const v = dalmuti.view(s, 'A');
expect(v.seats[0]!).toMatchObject({ id: 'E', title: '대달무티' });
expect(v.seats[4]!).toMatchObject({ id: 'A', title: '대농노' });
});
test('not declaring is allowed: holder confirms → normal tax', () => {
const s = confirmAll(atRevolutionCheck(handsWith(P5, { B: [J1, J2] })));
expect(s.revolution).toBe('none');
expect(s.phase.kind).toBe('taxReturn');
});
test('no info leak: the check phase looks the same with or without a holder; canDeclareRevolution only in the holder view', () => {
const withHolder = atRevolutionCheck(handsWith(P5, { C: [J1, J2] }));
const without = atRevolutionCheck(handsWith(P5, { C: [J1], D: [J2] }));
for (const s of [withHolder, without]) {
expect(s.phase.kind).toBe('revolutionCheck');
for (const p of ['A', 'B', 'D', 'E']) {
const v = JSON.stringify(dalmuti.view(s, p));
expect(v).not.toContain('canDeclareRevolution');
}
expect(JSON.stringify(dalmuti.view(s, null))).not.toContain('canDeclareRevolution');
expect(dalmuti.deadline!(s)).toBe(s.turnStartedAt + 20_000);
}
expect(dalmuti.view(withHolder, 'C').my!.canDeclareRevolution).toBe(true);
expect(JSON.stringify(dalmuti.view(without, 'C'))).not.toContain('canDeclareRevolution');
// Other views of both states differ only in the hidden hand contents (same shape, same keys).
const keys = (v: DalmutiView) => JSON.stringify({ ...v, my: v.my ? Object.keys(v.my) : null });
expect(keys(dalmuti.view(withHolder, 'A')).replace(/"hand":\[.*?\]/, '')).toBe(keys(dalmuti.view(without, 'A')).replace(/"hand":\[.*?\]/, ''));
});
});
// ---------------------------------------------------------------- playing
describe('트릭 진행 (§5.1)', () => {
test('following 9×3: 8×2 refused (count), 9×3 refused (same number), 4+4+광대 ok, 광대×2+1 ok (1×3)', () => {
const s = rig(make(), {
order: P5,
hands: { A: [C(8, 1), C(8, 2), C(9, 4), C(9, 5), C(9, 6), C(4, 1), C(4, 2), J1, C(1, 1), J2], B: [C(5, 1)], C: [C(6, 1)], D: [C(7, 1)], E: [C(10, 1)] },
top: { by: 'E', ids: [C(9, 1), C(9, 2), C(9, 3)] },
current: 'A',
});
expect(reject(s, 'A', { type: 'play', cardIds: [C(8, 1), C(8, 2)] })).toBe('앞사람과 같은 장수(3장)로 내야 해요.');
expect(reject(s, 'A', { type: 'play', cardIds: [C(9, 4), C(9, 5), C(9, 6)] })).toBe('더 낮은 숫자만 낼 수 있어요.');
expect(reject(s, 'A', { type: 'play', cardIds: [C(4, 1), C(8, 1), J1] })).toBe('같은 숫자끼리만 낼 수 있어요.');
expect(reject(s, 'A', { type: 'play', cardIds: [C(4, 1), C(4, 2), J1] })).toBeNull();
expect(reject(s, 'A', { type: 'play', cardIds: [J1, J2, C(1, 1)] })).toBeNull();
const after = play(s, 'A', [J1, J2, C(1, 1)]);
expect(after.trick.top).toMatchObject({ count: 3, rank: 1, by: 'A' });
// The view offers the same choices.
const ch = dalmuti.view(s, 'A').my!.choices;
expect(ch.find((c) => c.rank === 4)).toEqual({ rank: 4, have: 2, counts: [3], needsJester: true });
expect(ch.find((c) => c.rank === 1)).toEqual({ rank: 1, have: 1, counts: [3], needsJester: true });
expect(ch.find((c) => c.rank === 8)).toEqual({ rank: 8, have: 2, counts: [3], needsJester: true });
expect(ch.some((c) => c.rank === 9 || c.rank === 13)).toBe(false);
});
test('jester alone: on 12×1 refused (13 is worse); as a lead allowed (13×1), then any single number beats it', () => {
let s = rig(make(), { order: P5, hands: { A: [J1, C(12, 2)], B: [C(12, 3), C(5, 1)], C: [C(6, 1)], D: [C(7, 1)], E: [C(10, 1)] }, top: { by: 'E', ids: [C(12, 1)] }, current: 'A' });
expect(reject(s, 'A', { type: 'play', cardIds: [J1] })).toBe('더 낮은 숫자만 낼 수 있어요.');
s = rig(make(), { order: P5, hands: { A: [J1, C(12, 2)], B: [C(12, 3), C(5, 1)], C: [C(6, 1)], D: [C(7, 1)], E: [C(10, 1)] }, current: 'A' });
s = play(s, 'A', [J1]);
expect(s.trick.top).toMatchObject({ count: 1, rank: 13 });
expect(reject(s, 'B', { type: 'play', cardIds: [C(12, 3)] })).toBeNull();
});
test('a lead cannot pass; leads may be any size of one number', () => {
const s = rig(make(), { order: P5, hands: { A: [C(7, 1), C(7, 2), C(7, 3), J1], B: [C(5, 1)], C: [C(6, 1)], D: [C(8, 1)], E: [C(10, 1)] }, current: 'A' });
expect(reject(s, 'A', { type: 'pass' })).toBe('새로 시작할 때는 패스할 수 없어요.');
expect(reject(s, 'A', { type: 'play', cardIds: [C(7, 1), C(7, 2), C(7, 3), J1] })).toBeNull();
expect(dalmuti.view(s, 'A').my!.choices.find((c) => c.rank === 7)!.counts).toEqual([1, 2, 3, 4]);
});
test('§5.3 example: everyone but D passes → D leads the next trick', () => {
let s = rig(make(), {
order: P5,
hands: { A: [C(7, 1), C(7, 2), C(3, 1)], B: [C(5, 1), C(5, 2), C(9, 1)], C: [C(10, 1), C(11, 1)], D: [C(2, 1), J1, C(8, 1)], E: [C(12, 1), C(6, 1)] },
});
s = play(s, 'A', [C(7, 1), C(7, 2)]);
s = play(s, 'B', [C(5, 1), C(5, 2)]);
s = pass(s, 'C');
s = play(s, 'D', [C(2, 1), J1]);
for (const p of ['E', 'A', 'B']) s = pass(s, p);
expect(s.current).toBe('C');
expect(s.trick.top!.by).toBe('D');
s = pass(s, 'C');
expect(s.trick.top).toBeNull();
expect(s.trick.leader).toBe('D');
expect(s.current).toBe('D');
expect(s.discard).toEqual(expect.arrayContaining([C(7, 1), C(5, 1), C(2, 1), J1]));
});
test('going out with the top set → the next player with cards leads', () => {
let s = rig(make(), { order: P5, hands: { A: [C(3, 1)], B: [C(5, 1), C(5, 2)], C: [C(10, 1)], D: [C(8, 1)], E: [C(12, 1), C(12, 2)] }, current: 'E' });
s = play(s, 'E', [C(12, 1)]);
s = play(s, 'A', [C(3, 1)]); // A is out on the top set
expect(s.finishOrder).toEqual(['A']);
for (const p of ['B', 'C', 'D']) s = pass(s, p);
expect(s.current).toBe('E');
s = pass(s, 'E');
expect(s.trick.top).toBeNull();
expect(s.current).toBe('B');
});
test('passLocksOut off: a passer may play when the turn comes back; on: skipped for the rest of the trick', () => {
const hands = { A: [C(10, 1), C(1, 1)], B: [C(9, 1), C(2, 1)], C: [C(8, 1), C(12, 1)], D: [C(12, 2), C(12, 3)], E: [C(12, 4), C(12, 5)] };
const run = (passLocksOut: boolean) => {
let s = rig(make({ passLocksOut }), { order: P5, hands });
s = play(s, 'A', [C(10, 1)]);
s = pass(s, 'B');
s = play(s, 'C', [C(8, 1)]);
for (const p of ['D', 'E', 'A']) s = pass(s, p);
return s;
};
const off = run(false);
expect(off.current).toBe('B');
expect(reject(off, 'B', { type: 'play', cardIds: [C(2, 1)] })).toBeNull();
const on = run(true);
expect(on.trick.top).toBeNull();
expect(on.current).toBe('C');
// Mid-trick, a locked-out player is skipped in the turn order.
let m = rig(make({ passLocksOut: true }), { order: P5, hands });
m = play(m, 'A', [C(10, 1)]);
m = pass(m, 'B');
m = play(m, 'C', [C(8, 1)]);
m = pass(m, 'D');
m = pass(m, 'E');
m = play(m, 'A', [C(1, 1)]);
expect(m.current).toBe('C');
expect(dalmuti.view(m, null).seats.find((x) => x.id === 'B')!.lockedOut).toBe(true);
});
});
// ---------------------------------------------------------------- rounds / scoring
describe('라운드 종료와 점수 (§5.2, §6)', () => {
test('one player left with cards → round over; that player is the next 대농노; next order = finish order', () => {
let s = rig(make({ rounds: 3 }), { order: P5, hands: { A: [C(3, 1)], B: [C(4, 1)], C: [C(5, 1)], D: [C(6, 1)], E: [C(12, 1), C(12, 2)] }, current: 'D' });
s = play(s, 'D', [C(6, 1)]);
s = pass(s, 'E');
s = play(s, 'A', [C(3, 1)]); // A out (1st)
s = pass(s, 'B'); // B: 4 > 3
s = pass(s, 'C');
// D is out already; E passes → trick over, A is out → next with cards after A = B leads.
s = pass(s, 'E');
expect(s.current).toBe('B');
s = play(s, 'B', [C(4, 1)]); // B out (3rd? no: D 1st, A 2nd, B 3rd)
expect(s.finishOrder).toEqual(['D', 'A', 'B']);
s = pass(s, 'C');
s = pass(s, 'E');
expect(s.current).toBe('C');
s = play(s, 'C', [C(5, 1)]); // C out → only E left → round over
expect(s.round).toBe(2);
expect(s.roundResults[0]!.order).toEqual(['D', 'A', 'B', 'C', 'E']);
expect(s.roundResults[0]!.points).toEqual({ D: 4, A: 3, B: 2, C: 1, E: 0 });
expect(s.order).toEqual(['D', 'A', 'B', 'C', 'E']);
expect(s.phase.kind).toBe('revolutionCheck');
expect(s.order.map((p) => s.hands[p]!.length)).toEqual([16, 16, 16, 16, 16]);
expect(dalmuti.view(s, 'E').seats.find((x) => x.id === 'E')!.title).toBe('대농노');
expect(allCardIds(s).sort()).toEqual(FULL_DECK.map((c) => c.id).sort());
});
test('5 players, 3 rounds: rank points add up; ties go to the better last-round rank; last-round mode', () => {
const rr = (round: number, order: string[]) => ({ round, order, revolution: 'none' as const, points: Object.fromEntries(order.map((p, i) => [p, 4 - i])) });
const roundResults = [rr(1, ['A', 'B', 'C', 'D', 'E']), rr(2, ['C', 'A', 'B', 'E', 'D']), rr(3, ['B', 'C', 'E', 'A', 'D'])];
const totals: Record<string, number> = {};
for (const r of roundResults) for (const [p, pt] of Object.entries(r.points)) totals[p] = (totals[p] ?? 0) + pt;
expect(totals).toEqual({ A: 8, B: 9, C: 9, D: 1, E: 3 });
const base = { roundResults, totals, players: P5, options: dalmuti.optionsSchema.parse({}) };
const f = finalOf(base);
// B and C tie on 9 → B was 1st in the last round, C 2nd.
expect(f.ranking).toEqual([['B'], ['C'], ['A'], ['E'], ['D']]);
expect(f.players.find((p) => p.player === 'A')!.roundRanks).toEqual([1, 2, 4]);
expect(f.summary).toContain('같은 점수는 마지막 라운드 순위');
expect(f.summary).toContain('3라운드');
const last = finalOf({ ...base, options: dalmuti.optionsSchema.parse({ scoring: 'last-round' }) });
expect(last.ranking).toEqual([['B'], ['C'], ['E'], ['A'], ['D']]);
});
test('the game ends after `rounds` rounds with a result', () => {
let s = rig(make({ rounds: 1 }), { order: P4.concat('E'), hands: { A: [C(3, 1)], B: [C(4, 1)], C: [C(5, 1)], D: [C(6, 1)], E: [C(7, 1)] }, current: 'E' });
s = play(s, 'E', [C(7, 1)]);
s = play(s, 'A', [C(3, 1)]);
for (const p of ['B', 'C', 'D']) s = pass(s, p);
s = play(s, 'B', [C(4, 1)]);
s = pass(s, 'C');
s = pass(s, 'D');
s = play(s, 'C', [C(5, 1)]);
expect(s.phase.kind).toBe('finished');
const res = dalmuti.result(s)!;
expect(res.ranking).toEqual([['E'], ['A'], ['B'], ['C'], ['D']]);
expect(res.scores).toEqual({ E: 4, A: 3, B: 2, C: 1, D: 0 });
expect(reject(s, 'D', { type: 'pass' })).toBe('게임이 이미 끝났어요.');
});
});
// ---------------------------------------------------------------- timeouts / leaving
describe('시간 초과와 나가기 (§8.5)', () => {
test('lead timeout plays every card of the highest number; follow timeout passes; jesters only → all jesters', () => {
let s = rig(make(), { order: P5, hands: { A: [C(2, 1), C(11, 1), C(11, 2), J1], B: [C(5, 1)], C: [C(6, 1)], D: [C(7, 1)], E: [C(10, 1)] } });
expect(dalmuti.onTimeout(s, 'A')).toEqual({ type: 'timeout' });
s = act(s, 'A', { type: 'timeout' });
expect(s.trick.top).toMatchObject({ by: 'A', count: 2, rank: 11 });
expect(ids(s, 'A')).toEqual([C(2, 1), J1]);
s = act(s, 'B', { type: 'timeout' });
expect(s.trick.passesSinceTop).toEqual(['B']);
const j = act(rig(make(), { order: P5, hands: { A: [J1, J2], B: [C(5, 1)], C: [C(6, 1)], D: [C(7, 1)], E: [C(10, 1)] } }), 'A', { type: 'timeout' });
expect(j.trick.top).toMatchObject({ count: 2, rank: 13 });
});
test('tax return timeout gives back the highest number cards; revolutionCheck timeout never declares', () => {
let s = atRevolutionCheck(handsWith(P5, { A: [C(12, 1), C(12, 2), J1, J2] }));
for (const p of P5) s = act(s, p, { type: 'timeout' });
expect(s.revolution).toBe('none');
expect(s.phase.kind).toBe('taxReturn');
const hiA = Math.max(...nums(s, 'A').filter((n) => n !== 13));
s = act(s, 'A', { type: 'timeout' });
const back = s.taxLog.find((t) => t.kind === 'return' && t.from === 'A')!;
expect(back.cardIds.map((id) => card(id).n)).toEqual([hiA, hiA]);
expect(back.cardIds).not.toContain(J1);
});
test('3 timeouts in a row → away, deadline 5 s; acting again clears it', () => {
let s = rig(make(), { order: P5, hands: { A: [C(1, 1), C(9, 1), C(9, 2), C(9, 3)], B: [C(12, 1), C(12, 2)], C: [C(12, 3)], D: [C(12, 4)], E: [C(12, 5)] } });
s.timeoutsInRow.B = 2;
s = play(s, 'A', [C(9, 1)]);
expect(dalmuti.deadline!(s)).toBe(s.turnStartedAt + 20_000);
s = act(s, 'B', { type: 'timeout' });
expect(s.away.B).toBe(true);
for (const p of ['C', 'D', 'E']) s = pass(s, p);
s = play(s, 'A', [C(9, 2)]);
expect(s.current).toBe('B');
expect(dalmuti.deadline!(s)).toBe(s.turnStartedAt + 5000);
expect(dalmuti.timeoutNotBefore!(s)).toBe(s.turnStartedAt + 1200);
s = pass(s, 'B');
expect(s.away.B).toBe(false);
});
test('leaving does not eliminate: the seat stays, marked away, and keeps being auto-played', () => {
let s = rig(make(), { order: P5, hands: { A: [C(9, 1)], B: [C(12, 1), C(5, 1)], C: [C(12, 3)], D: [C(12, 4)], E: [C(12, 5)] } });
expect(dalmuti.onLeave!(s, 'B')).toEqual({ type: 'leave' });
s = act(s, 'B', { type: 'leave' });
expect(s.left.B).toBe(true);
expect(s.away.B).toBe(true);
expect(s.order).toContain('B');
expect(dalmuti.onLeave!(s, 'B')).toBeNull();
expect(dalmuti.view(s, null).seats.find((x) => x.id === 'B')!.left).toBe(true);
});
});
// ---------------------------------------------------------------- validation / leaks / options
describe('검증과 정보 유출 (§8.3, §10)', () => {
test('not my turn / card not in hand / resent packet are refused and change nothing', () => {
let s = rig(make(), { order: P5, hands: { A: [C(9, 1), C(9, 2)], B: [C(5, 1)], C: [C(6, 1)], D: [C(7, 1)], E: [C(10, 1)] } });
const snap = JSON.stringify(s);
expect(reject(s, 'B', { type: 'play', cardIds: [C(5, 1)] })).toBe('지금은 내 차례가 아니에요.');
expect(reject(s, 'A', { type: 'play', cardIds: [C(5, 1)] })).toBe('손에 없는 카드예요.');
expect(reject(s, 'A', { type: 'play', cardIds: [C(9, 1), C(9, 1)] })).toBe('같은 카드를 두 번 고를 수 없어요.');
expect(reject(s, 'Z', { type: 'pass' })).toBe('이 게임의 플레이어가 아니에요.');
expect(reject(s, 'B', { type: 'timeout' })).toBe('시간 초과 대상이 아니에요.');
expect(JSON.stringify(s)).toBe(snap);
s = play(s, 'A', [C(9, 1)]);
const snap2 = JSON.stringify(s);
expect(reject(s, 'A', { type: 'play', cardIds: [C(9, 1)] })).toBe('지금은 내 차례가 아니에요.');
expect(JSON.stringify(s)).toBe(snap2);
});
test('spectators and other players see counts only; tax card contents only for the two involved', () => {
const s = confirmAll(atRevolutionCheck(handsWith(P5, { E: [J1, J2, C(3, 1), C(3, 2)] })));
const taxIds = s.taxLog.flatMap((t) => t.cardIds);
for (const viewer of [null, 'C']) {
const v = dalmuti.view(s, viewer);
const json = JSON.stringify(v);
for (const p of P5) if (p !== viewer) for (const id of ids(s, p)) expect(json).not.toContain(`"${id}"`);
for (const id of taxIds) expect(json).not.toContain(`"${id}"`);
expect(v.tax.every((t) => t.cards === null)).toBe(true);
expect(v.tax.map((t) => t.count)).toEqual([2, 1]);
}
const ve = dalmuti.view(s, 'E');
expect(ve.tax[0]!.cards).toEqual([3, 3]);
expect(ve.tax[1]!.cards).toBeNull();
const va = dalmuti.view(s, 'A');
expect(va.tax[0]!.cards).toEqual([3, 3]);
expect(va.my!.receivedIds).toEqual([C(3, 1), C(3, 2)]);
expect(va.my!.owe).toEqual({ to: 'E', count: 2 });
expect(va.my!.suggestedReturn.map((id) => card(id).n)).toEqual(worst2(s, 'A'));
// After A gives the 3s back, A's view must not keep their ids.
const t = act(s, 'A', { type: 'returnTax', cardIds: [C(3, 1), C(3, 2)] });
expect(JSON.stringify(dalmuti.view(t, 'A'))).not.toContain(`"${C(3, 1)}"`);
expect(dalmuti.view(t, 'E').tax[2]!.cards).toEqual([3, 3]);
});
test('options: defaults, Korean metadata on every option', () => {
const o = dalmuti.defaultOptions;
expect(o).toEqual({ rounds: 3, scoring: 'rank-points', firstRanking: 'draw', revolution: true, jesterTaxable: false, passLocksOut: false, removeHighCards: false, turnSeconds: 20 });
const shape = (dalmuti.optionsSchema as unknown as { shape: Record<string, { meta(): { title?: string } | undefined }> }).shape;
for (const [k, f] of Object.entries(shape)) {
expect(f.meta()?.title, k).toMatch(/[가-힣]/);
}
});
test('client actions only (system actions are not in the schema)', () => {
expect(dalmuti.actionSchema.safeParse({ type: 'timeout' }).success).toBe(false);
expect(dalmuti.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
expect(dalmuti.actionSchema.safeParse({ type: 'pass' }).success).toBe(true);
expect(dalmuti.actionSchema.safeParse({ type: 'play', cardIds: [] }).success).toBe(false);
});
});
function worst2(s: DalmutiState, p: string): number[] {
const n = nums(s, p).filter((x) => x !== 13).sort((a, b) => b - a);
return n.slice(0, 2);
}
// ---------------------------------------------------------------- random playouts
function invariants(s: DalmutiState): void {
const all = allCardIds(s);
const deck = deckFor(s.options.removeHighCards);
if (all.length !== deck.length || new Set(all).size !== deck.length) throw new Error(`card count ${all.length} (unique ${new Set(all).size}) ≠ ${deck.length}`);
if (s.phase.kind === 'playing' && s.hands[s.current]!.length === 0) throw new Error('current player has no cards');
if (s.phase.kind !== 'finished' && s.order.length !== s.players.length) throw new Error('order lost a player');
}
function checkLeaks(s: DalmutiState, players: PlayerId[], viewers: (PlayerId | null)[] = [null, ...players]): void {
for (const viewer of viewers) {
const v = dalmuti.view(s, viewer);
const json = JSON.stringify(v);
for (const p of players) {
if (p === viewer) continue;
for (const c of s.hands[p]!) if (json.includes(`"${c.id}"`)) throw new Error(`view for ${viewer} leaks ${c.id} of ${p}`);
}
for (const t of v.tax) if (t.cards && viewer !== t.from && viewer !== t.to) throw new Error(`tax contents leak to ${viewer}`);
const holder = viewer !== null && s.phase.kind === 'revolutionCheck' && s.hands[viewer]!.filter((c) => c.n === 13).length === 2;
if (!holder && json.includes('canDeclareRevolution')) throw new Error(`canDeclareRevolution in the view for ${viewer}`);
}
}
interface FastReport {
steps: number;
finished: boolean;
trace: string;
final: DalmutiState;
}
/** Same chooser and selection as `randomPlayout`, with lighter per-step checks so 1,000 games stay fast. */
function fastPlayout(players: PlayerId[], options: DalmutiOptions, seed: RngState, maxSteps: number): FastReport {
const r = SeededRng.fromSeed(seed);
const chooser = SeededRng.fromSeed([seed[3], seed[2], seed[1], seed[0] ^ 0x9e3779b9]);
let now = 1_700_000_000_000;
let s = dalmuti.setup({ players, options, rng: r, now });
const trace: string[] = [];
for (let step = 0; step < maxSteps; step++) {
invariants(s);
if (step % 15 === 0) checkLeaks(s, players, [null, players[(step / 15) % players.length]!]);
if (step % 60 === 0 && JSON.stringify(JSON.parse(JSON.stringify(s))) !== JSON.stringify(s)) throw new Error('not JSON round-trippable');
for (const p of dalmuti.timeoutPlayers!(s)) {
const v = dalmuti.validate(s, p, dalmuti.onTimeout(s, p));
if (!v.ok) throw new Error(`onTimeout rejected for ${p}: ${v.reason}`);
}
if (dalmuti.result(s)) {
checkLeaks(s, players);
return { steps: step, finished: true, trace: trace.join(';'), final: s };
}
const actives = dalmuti.activePlayers(s);
if (!actives.length) throw new Error('no active players');
const actor = actives[chooser.int(actives.length)]!;
// Some turns go through the timer path, like real away players.
const legal = chooser.int(12) === 0 ? [] : dalmuti.legalActions!(s, actor);
const action = legal.length > 0 ? legal[chooser.int(legal.length)]! : dalmuti.onTimeout(s, actor);
const v = dalmuti.validate(s, actor, action);
if (!v.ok) throw new Error(`generated action rejected: ${v.reason} ${JSON.stringify(action)}`);
now += 1000;
const before = step % 25 === 0 ? JSON.stringify(s) : null;
const out = dalmuti.apply(s, actor, action, { rng: r, now });
if (before !== null && JSON.stringify(s) !== before) throw new Error('apply mutated the previous state');
if (JSON.stringify(out.events).match(/"c\d+-\d+"|"j[12]"/)) throw new Error('event carries a card id');
s = out.state;
trace.push(`${actor}:${JSON.stringify(action)}`);
}
return { steps: maxSteps, finished: false, trace: trace.join(';'), final: s };
}
const PRESETS: Partial<DalmutiOptions>[] = [
{ rounds: 1 },
{ rounds: 3 },
{ rounds: 1, passLocksOut: true, jesterTaxable: true },
{ rounds: 3, revolution: false, firstRanking: 'random', scoring: 'last-round' },
{ rounds: 1, removeHighCards: true },
{ rounds: 5, removeHighCards: true, passLocksOut: true },
];
describe('random playouts (1,000 seeds)', () => {
test('1,000 seeded games finish, cards conserved, no leaks, onTimeout always legal, deterministic', () => {
let finished = 0;
let revolutions = 0;
let great = 0;
for (let i = 1; i <= 1000; i++) {
const n = 4 + (i % 5);
const players = Array.from({ length: n }, (_, k) => `P${k}`);
const options = dalmuti.optionsSchema.parse(PRESETS[i % PRESETS.length]!);
const a = fastPlayout(players, options, seedN(i), 20_000);
if (!a.finished) throw new Error(`seed ${i} (${n} players) did not finish in 20,000 steps`);
finished++;
const res = dalmuti.result(a.final)!;
expect(res.ranking.flat().sort()).toEqual([...players].sort());
expect(a.final.roundResults).toHaveLength(options.rounds);
revolutions += a.final.roundResults.filter((x) => x.revolution === 'revolution').length;
great += a.final.roundResults.filter((x) => x.revolution === 'great').length;
if (i % 50 === 0) {
const b = fastPlayout(players, options, seedN(i), 20_000);
expect(b.trace).toBe(a.trace);
expect(JSON.stringify(b.final)).toBe(JSON.stringify(a.final));
}
}
expect(finished).toBe(1000);
expect(revolutions).toBeGreaterThan(0);
expect(great).toBeGreaterThan(0);
}, 60_000);
test.each([
[4, {}],
[5, { rounds: 1, passLocksOut: true }],
[8, { rounds: 1, revolution: false, removeHighCards: true }],
] as const)('randomPlayout with the engine’s per-step leak / round-trip checks: %i players', (n, opts) => {
const players = Array.from({ length: n }, (_, k) => `P${k}`);
const options = dalmuti.optionsSchema.parse(opts);
const conserve = (st: unknown) => invariants(st as DalmutiState);
for (let i = 1; i <= 2; i++) {
const a = randomPlayout(dalmuti, { players, options, seed: seedN(2000 + i), maxSteps: 20_000, invariant: conserve, maxApplyMs: 30 });
expect(a.finished).toBe(true);
if (i === 1) {
const b = randomPlayout(dalmuti, { players, options, seed: seedN(2000 + i), maxSteps: 20_000, maxApplyMs: 30 });
expect(JSON.stringify(b.trace)).toBe(JSON.stringify(a.trace));
}
}
}, 60_000);
});