Files
joke-app/packages/games/src/rummikub/rummikub.test.ts

772 lines
40 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, expect, test } from 'bun:test';
import { SeededRng, playoutSeeds, randomPlayout, seedN, type GameEvent, type PlayerId } from '@bg/engine';
import {
ALL_TILE_IDS,
findMeld,
normalizeSet,
rummikub,
scoreRound,
setProblem,
sortTiles,
tileCount,
type DraftSet,
type RummikubAction,
type RummikubOptions,
type RummikubState,
} from './index';
// ---------------------------------------------------------------- helpers
let clock = 1_000_000;
const RNG = () => SeededRng.fromSeed([7, 7, 7, 7]);
function mk(opts: Partial<RummikubOptions> = {}, players = ['A', 'B'], seed = 1): RummikubState {
const options = rummikub.optionsSchema.parse(opts);
return rummikub.setup({ players, options, rng: SeededRng.fromSeed(seedN(seed)), now: clock });
}
/**
* Puts the game into a hand-made position: given racks and table sets, everything else goes to the pool
* (in id order), `current` has the turn with a fresh draft.
*/
function rig(
s: RummikubState,
o: { racks: Record<PlayerId, string[]>; table?: string[][]; current?: PlayerId; melded?: PlayerId[]; pool?: string[] },
): RummikubState {
const table = o.table ?? [];
const used = new Set([...Object.values(o.racks).flat(), ...table.flat()]);
s.racks = Object.fromEntries(s.roundPlayers.map((p) => [p, [...(o.racks[p] ?? [])]]));
s.table = table.map((ids, i) => {
const n = normalizeSet({ tileIds: ids });
if (!n) throw new Error(`rig: invalid table set ${ids}`);
return { id: `s${i + 1}`, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs };
});
s.nextSetId = table.length + 1;
const rest = ALL_TILE_IDS.filter((id) => !used.has(id));
s.pool = o.pool ? o.pool : rest;
if (o.pool) {
// The given pool must hold every tile that is in no rack and not on the table (106 in total).
const extra = rest.filter((id) => !o.pool!.includes(id));
if (extra.length) throw new Error('rig: pool must contain every unused tile');
}
s.current = o.current ?? s.roundPlayers[0]!;
s.hasMelded = Object.fromEntries(s.roundPlayers.map((p) => [p, (o.melded ?? []).includes(p)]));
s.draft = { sets: s.table.map((t) => ({ tileIds: [...t.tileIds], as: t.kind })), history: [], edits: 0 };
s.consecutivePasses = 0;
expect(tileCount(s)).toBe(106);
return s;
}
function act(s: RummikubState, who: PlayerId, a: RummikubAction): RummikubState {
return actE(s, who, a).state;
}
function actE(s: RummikubState, who: PlayerId, a: RummikubAction): { state: RummikubState; events: GameEvent[] } {
const v = rummikub.validate(s, who, a);
if (!v.ok) throw new Error(`${who} ${JSON.stringify(a)} rejected: ${v.reason}`);
clock += 1000;
const out = rummikub.apply(s, who, a, { rng: RNG(), now: clock });
expect(tileCount(out.state)).toBe(106);
return out;
}
function reason(s: RummikubState, who: PlayerId, a: RummikubAction): string {
const v = rummikub.validate(s, who, a);
if (v.ok) throw new Error(`expected rejection of ${JSON.stringify(a)}`);
return v.reason;
}
const tableSets = (s: RummikubState): DraftSet[] => s.table.map((t) => ({ tileIds: [...t.tileIds] }));
const setsOf = (s: RummikubState) => s.table.map((t) => t.tileIds);
/** Sets the draft and commits in one go. */
const play = (s: RummikubState, who: PlayerId, sets: string[][]) => act(act(s, who, { type: 'setDraft', sets: sets.map((tileIds) => ({ tileIds })) }), who, { type: 'commit' });
// ---------------------------------------------------------------- setup
describe('셋업 (§4)', () => {
test('106 tiles: 104 numbers + 2 jokers, ids R7a/R7b/JK1/JK2', () => {
expect(ALL_TILE_IDS).toHaveLength(106);
expect(new Set(ALL_TILE_IDS).size).toBe(106);
expect(ALL_TILE_IDS.filter((id) => id.startsWith('JK'))).toEqual(['JK1', 'JK2']);
expect(ALL_TILE_IDS).toContain('R7a');
expect(ALL_TILE_IDS).toContain('O13b');
});
test.each([
[2, 78],
[3, 64],
[4, 50],
])('%i players: 14 tiles each, pool %i', (n, pool) => {
const players = ['A', 'B', 'C', 'D'].slice(0, n);
const s = mk({}, players, 3);
for (const p of players) expect(s.racks[p]).toHaveLength(14);
expect(s.pool).toHaveLength(pool);
expect(tileCount(s)).toBe(106);
expect(new Set([...s.pool, ...Object.values(s.racks).flat()]).size).toBe(106);
expect(s.table).toEqual([]);
});
test('same seed → same deal and first player; the opening draw picks the highest number', () => {
const a = mk({}, ['A', 'B', 'C'], 42);
const b = mk({}, ['A', 'B', 'C'], 42);
expect(JSON.stringify(a)).toBe(JSON.stringify(b));
const lastRound = Math.max(...a.opening.map((o) => o.round));
const final = a.opening.filter((o) => o.round === lastRound && o.n !== null);
const max = Math.max(...final.map((o) => o.n!));
expect(final.filter((o) => o.n === max).map((o) => o.player)).toEqual([a.current]);
// Different seeds give different deals.
expect(JSON.stringify(mk({}, ['A', 'B', 'C'], 43).racks)).not.toBe(JSON.stringify(a.racks));
});
test('turn order is the seat order starting from the first player', () => {
const s = mk({}, ['A', 'B', 'C', 'D'], 5);
const order = [s.current];
let t = s;
for (let i = 0; i < 4; i++) {
t = act(t, t.current, { type: 'draw' });
order.push(t.current);
}
const i0 = ['A', 'B', 'C', 'D'].indexOf(order[0]!);
expect(order).toEqual([0, 1, 2, 3, 4].map((k) => ['A', 'B', 'C', 'D'][(i0 + k) % 4]!));
});
});
// ---------------------------------------------------------------- sets
describe('세트 판정 (§5.1)', () => {
const ok = (ids: string[], as?: 'run' | 'group') => normalizeSet(as ? { tileIds: ids, as } : { tileIds: ids });
test('invalid sets from the checklist', () => {
expect(ok(['R12a', 'R13a', 'R1a'])).toBeNull();
expect(setProblem({ tileIds: ['R12a', 'R13a', 'R1a'] })).toBe('13 다음에 1은 올 수 없어요');
expect(ok(['B5a', 'R5a', 'B5b'])).toBeNull();
expect(setProblem({ tileIds: ['B5a', 'R5a', 'B5b'] })).toBe('같은 색이 두 개예요');
expect(ok(['B5a', 'R5a', 'K5a', 'O5a', 'JK1'])).toBeNull();
expect(setProblem({ tileIds: ['B5a', 'R5a', 'K5a', 'O5a', 'JK1'] })).toBe('같은 숫자 묶음은 4장까지예요');
expect(ok(['R1a', 'R2a'])).toBeNull();
expect(setProblem({ tileIds: ['R1a', 'R2a'] })).toBe('3장 이상이어야 해요');
expect(ok(['R3a', 'R5a', 'R6a'])).toBeNull();
expect(setProblem({ tileIds: ['R3a', 'R5a', 'R6a'] })).toBe('숫자가 이어지지 않아요');
expect(ok(['R3a', 'B4a', 'R5a'])).toBeNull();
expect(ok(['R3a', 'R3b', 'R4a'])).toBeNull();
expect(ok(['JK1', 'JK2', 'R5a', 'R5a'])).toBeNull(); // duplicate id
});
test('valid groups and runs, points', () => {
expect(ok(['R7a', 'B7a', 'K7a'])).toMatchObject({ kind: 'group', points: 21 });
expect(ok(['R7a', 'B7a', 'K7a', 'O7b'])).toMatchObject({ kind: 'group', points: 28 });
expect(ok(['B3a', 'B4a', 'B5a', 'B6a'])).toMatchObject({ kind: 'run', points: 18, tileIds: ['B3a', 'B4a', 'B5a', 'B6a'] });
// Sent in any order: sorted ascending.
expect(ok(['B6a', 'B4a', 'B5a'])).toMatchObject({ kind: 'run', tileIds: ['B4a', 'B5a', 'B6a'] });
const all13 = Array.from({ length: 13 }, (_, i) => `O${i + 1}a`);
expect(ok(all13)).toMatchObject({ kind: 'run', points: 91 });
});
test('jokers: gap filling, two jokers in one set, interpretation (§5.5)', () => {
expect(ok(['K9a', 'K11a', 'JK1'])).toMatchObject({ kind: 'run', tileIds: ['K9a', 'JK1', 'K11a'], jokerAs: { JK1: { color: 'K', n: 10 } } });
expect(ok(['K5a', 'JK1', 'JK2'])).toMatchObject({ kind: 'run', points: 18 });
expect(ok(['K5a', 'JK1', 'JK2'], 'group')).toMatchObject({ kind: 'group', points: 15, jokerAs: { JK1: { color: null, n: 5 } } });
expect(ok(['R7a', 'B7a', 'JK2'])).toMatchObject({ kind: 'group', points: 21 });
// [조커, 검정9, 검정10] in this order = 8-9-10; [검정9, 검정10, 조커] = 9-10-11.
expect(ok(['JK1', 'K9a', 'K10a'])).toMatchObject({ points: 27, jokerAs: { JK1: { n: 8 } } });
expect(ok(['K9a', 'K10a', 'JK1'])).toMatchObject({ points: 30, jokerAs: { JK1: { n: 11 } } });
// [빨강12, 빨강13, 조커] cannot go up: 11-12-13.
expect(ok(['R12a', 'R13a', 'JK1'])).toMatchObject({ kind: 'run', tileIds: ['JK1', 'R12a', 'R13a'], points: 36, jokerAs: { JK1: { color: 'R', n: 11 } } });
// Jokers cannot stand in for 0 or 14.
expect(ok(['JK1', 'R1a', 'R2a'])).toMatchObject({ points: 6, tileIds: ['R1a', 'R2a', 'JK1'] });
});
test('rack sort by colour / number keeps jokers last', () => {
expect(sortTiles(['JK1', 'R3a', 'K5a', 'K2a', 'B3a'], 'color')).toEqual(['K2a', 'K5a', 'R3a', 'B3a', 'JK1']);
expect(sortTiles(['JK1', 'R3a', 'K5a', 'K2a', 'B3a'], 'number')).toEqual(['K2a', 'R3a', 'B3a', 'K5a', 'JK1']);
});
});
// ---------------------------------------------------------------- first meld
describe('첫 등록 (§5.3)', () => {
test('30 points from rack tiles only; 21 points is refused with the current total', () => {
let s = rig(mk(), { racks: { A: ['R10a', 'R11a', 'R12a', 'K5a'], B: ['B1a', 'B2a', 'B3a', 'K5b', 'R5a', 'O5a'] }, current: 'B' });
s = act(s, 'B', { type: 'setDraft', sets: [{ tileIds: ['B1a', 'B2a', 'B3a'] }, { tileIds: ['K5b', 'R5a', 'O5a'] }] });
expect(reason(s, 'B', { type: 'commit' })).toBe('첫 등록은 30점 이상이어야 해요 (지금 21점).');
expect(rummikub.view(s, 'B').my!.check).toMatchObject({ ok: false, meldPoints: 21 });
s = act(s, 'B', { type: 'draw' });
expect(s.table).toEqual([]);
s = play(s, 'A', [['R10a', 'R11a', 'R12a']]);
expect(s.hasMelded.A).toBe(true);
expect(s.racks.A).toEqual(['K5a']);
});
test('joker position decides the first meld: [조커, 검정9, 검정10] = 27 refused, [검정9, 검정10, 조커] = 30 accepted', () => {
let s = rig(mk(), { racks: { A: ['JK1', 'K9a', 'K10a', 'R1a'], B: ['B1a'] } });
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['JK1', 'K9a', 'K10a'] }] });
expect(reason(s, 'A', { type: 'commit' })).toBe('첫 등록은 30점 이상이어야 해요 (지금 27점).');
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K9a', 'K10a', 'JK1'] }] });
s = act(s, 'A', { type: 'commit' });
expect(s.table[0]!.jokerAs).toEqual({ JK1: { color: 'K', n: 11 } });
});
test('before the first meld: touching or extending table sets is refused at setDraft (C3)', () => {
const s = rig(mk(), { racks: { A: ['R3a', 'K10a', 'B10a', 'O10a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a']], melded: ['B'] });
// Extend the table run with a rack tile.
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R3a', 'R4a', 'R5a', 'R6a', 'R7a'] }] })).toBe('첫 등록 전에는 바닥의 타일을 옮길 수 없어요.');
// Split the table run.
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a'] }, { tileIds: ['R6a', 'R7a'] }] })).toBe('첫 등록 전에는 바닥의 타일을 옮길 수 없어요.');
// A new set next to the untouched table set is fine.
const t = play(s, 'A', [['R4a', 'R5a', 'R6a', 'R7a'], ['K10a', 'B10a', 'O10a']]);
expect(t.hasMelded.A).toBe(true);
});
test('initialMeldAllowExtend: 30 from new sets first, then extending in the same turn is allowed', () => {
const base = { racks: { A: ['R3a', 'K10a', 'B10a', 'O10a', 'R8a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a']], melded: ['B'] };
let s = rig(mk({ initialMeldAllowExtend: true }), base);
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R3a', 'R4a', 'R5a', 'R6a', 'R7a', 'R8a'] }] });
expect(reason(s, 'A', { type: 'commit' })).toBe('첫 등록은 30점 이상이어야 해요 (지금 0점).');
s = play(s, 'A', [['R3a', 'R4a', 'R5a', 'R6a', 'R7a', 'R8a'], ['K10a', 'B10a', 'O10a']]);
expect(s.racks.A).toEqual([]);
});
test('initialMeldPoints 0 = no first-meld rule at all', () => {
const s = mk({ initialMeldPoints: 0 });
expect(Object.values(s.hasMelded).every(Boolean)).toBe(true);
});
});
// ---------------------------------------------------------------- rearrangement
describe('재배치와 조커 회수 (§5.4, §5.5)', () => {
test('table [빨강4..8] + rack 빨강6 → [4,5,6] [6,7,8]', () => {
let s = rig(mk(), { racks: { A: ['R6b', 'K1a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a', 'R8a']], melded: ['A'] });
s = play(s, 'A', [['R4a', 'R5a', 'R6a'], ['R6b', 'R7a', 'R8a']]);
expect(setsOf(s)).toEqual([['R4a', 'R5a', 'R6a'], ['R6b', 'R7a', 'R8a']]);
expect(s.racks.A).toEqual(['K1a']);
// The first set keeps its id (biggest overlap), the second is new; both are highlighted as changed.
expect(s.table.map((t) => t.id)).toEqual(['s1', 's2']);
expect(s.lastChanged.sort()).toEqual(['s1', 's2']);
});
test('official examples: add 파랑3 to 파랑4-5-6, 4th colour to a group, take 파랑4 from a 4-group', () => {
let s = rig(mk(), {
racks: { A: ['B3a', 'O8a', 'B3b', 'B5b', 'B6b', 'K1a'], B: ['B1a'] },
table: [['B4a', 'B5a', 'B6a'], ['R8a', 'K8a', 'B8a'], ['R4a', 'K4a', 'B4b', 'O4a']],
melded: ['A'],
});
s = play(s, 'A', [['B3a', 'B4a', 'B5a', 'B6a'], ['R8a', 'K8a', 'B8a', 'O8a'], ['R4a', 'K4a', 'O4a'], ['B3b', 'B4b', 'B5b', 'B6b']]);
expect(s.racks.A).toEqual(['K1a']);
expect(s.table).toHaveLength(4);
});
test('joker retrieval: [파랑5, 조커, 파랑7] + [파랑6, 검정3, 빨강3] → [파랑5,6,7] [검정3, 빨강3, 조커]', () => {
let s = rig(mk(), { racks: { A: ['B6a', 'K3a', 'R3a', 'O1a'], B: ['B1a'] }, table: [['B5a', 'JK1', 'B7a']], melded: ['A'] });
// Taking the joker back to the rack is refused (C2).
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['B5a', 'B6a', 'B7a'] }] })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
s = play(s, 'A', [['B5a', 'B6a', 'B7a'], ['K3a', 'R3a', 'JK1']]);
expect(setsOf(s)).toEqual([['B5a', 'B6a', 'B7a'], ['K3a', 'R3a', 'JK1']]);
expect(s.table[1]!.jokerAs).toEqual({ JK1: { color: null, n: 3 } });
expect(s.racks.A).toEqual(['O1a']);
});
test('rearranging without a rack tile is refused; leftover single tiles are refused', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a', 'R8a', 'R9a']], melded: ['A'] });
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a', 'R6a'] }, { tileIds: ['R7a', 'R8a', 'R9a'] }] });
expect(reason(s, 'A', { type: 'commit' })).toBe('받침대에서 타일을 1개 이상 내야 해요.');
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a', 'R6a'] }, { tileIds: ['R7a', 'R8a', 'R9a'] }, { tileIds: ['K1a', 'K2a'] }] });
expect(reason(s, 'A', { type: 'commit' })).toBe('빨간 표시된 묶음을 고쳐 주세요.');
expect(rummikub.view(s, 'A').my!.check!.invalidIdx).toEqual([2]);
expect(rummikub.view(s, 'A').draft![2]).toMatchObject({ ok: false, problem: '3장 이상이어야 해요' });
});
test('cheating attempts: foreign tiles, duplicates, table tiles into the rack, empty sets', () => {
const s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a'], B: ['B1a', 'B2a', 'B3a'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A', 'B'] });
const base = tableSets(s);
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['B1a', 'B2a', 'B3a'] }] })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['O9a', 'O10a', 'O11a'] }] })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['XX1', 'K2a', 'K3a'] }] })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['K1a', 'K1a', 'K2a'] }] })).toBe('같은 타일이 두 번 들어 있어요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['K1a', 'K2a', 'K3a', 'R4a'] }] })).toBe('같은 타일이 두 번 들어 있어요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a'] }, { tileIds: ['K1a', 'K2a', 'K3a'] }] })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
expect(rummikub.actionSchema.safeParse({ type: 'setDraft', sets: [{ tileIds: [] }] }).success).toBe(false);
expect(reason(s, 'B', { type: 'setDraft', sets: base })).toBe('지금은 내 차례가 아니에요.');
expect(reason(s, 'Z', { type: 'draw' })).toBe('이 게임의 플레이어가 아니에요.');
// A valid commit puts exactly the played tiles on the table.
const t = play(s, 'A', [...base.map((d) => d.tileIds), ['K1a', 'K2a', 'K3a']]);
expect(t.racks.A).toEqual([]);
});
});
// ---------------------------------------------------------------- draft / undo
describe('초안과 되돌리기 (§5.6)', () => {
test('5 setDraft → 2 undo → the 3rd draft; reset → turn start; survives a save/reload', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'K4a', 'K5a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A'] });
const base = tableSets(s);
const drafts = [1, 2, 3, 4, 5].map((k) => [...base, { tileIds: ['K1a', 'K2a', 'K3a', 'K4a', 'K5a'].slice(0, k) }]);
for (const d of drafts) s = act(s, 'A', { type: 'setDraft', sets: d });
s = act(s, 'A', { type: 'undoDraft' });
s = act(s, 'A', { type: 'undoDraft' });
expect(s.draft.sets).toEqual(drafts[2]!);
// Reconnect = the persisted state is reloaded; the draft is still there.
const reloaded = JSON.parse(JSON.stringify(s)) as RummikubState;
expect(rummikub.view(reloaded, 'A').draft!.map((d) => d.tileIds)).toEqual(drafts[2]!.map((d) => d.tileIds));
s = act(s, 'A', { type: 'resetDraft' });
expect(s.draft.sets.map((d) => d.tileIds)).toEqual(base.map((d) => d.tileIds));
expect(rummikub.view(s, 'A').my!.changed).toBe(false);
// Reset can be undone too.
s = act(s, 'A', { type: 'undoDraft' });
expect(s.draft.sets).toEqual(drafts[2]!);
for (let i = 0; i < 3; i++) s = act(s, 'A', { type: 'undoDraft' });
expect(reason(s, 'A', { type: 'undoDraft' })).toBe('되돌릴 것이 없어요.');
});
test('history keeps at most 100 steps', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a'], B: ['B1a'] }, melded: ['A'] });
for (let i = 0; i < 130; i++) s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: [i % 2 ? 'K1a' : 'K2a'] }] });
expect(s.draft.history).toHaveLength(100);
});
test('draw with a changed draft throws the draft away and draws one', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a'], B: ['B1a'] }, melded: ['A'] });
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a', 'K2a', 'K3a'] }] });
s = act(s, 'A', { type: 'draw' });
expect(s.table).toEqual([]);
expect(s.racks.A).toHaveLength(4);
expect(s.current).toBe('B');
});
test('invalidCommitPenalty=penalty3: an invalid commit reverts, draws 3 and ends the turn', () => {
let s = rig(mk({ invalidCommitPenalty: 'penalty3' }), { racks: { A: ['K1a', 'K2a'], B: ['B1a'] }, melded: ['A'] });
expect(reason(s, 'A', { type: 'commit' })).toBe('받침대에서 타일을 1개 이상 내야 해요.');
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a', 'K2a'] }] });
s = act(s, 'A', { type: 'commit' });
expect(s.table).toEqual([]);
expect(s.racks.A).toHaveLength(5);
expect(s.current).toBe('B');
expect(s.log.at(-1)).toMatchObject({ by: 'A', kind: 'penalty', count: 3 });
});
});
// ---------------------------------------------------------------- timeouts
describe('시간 초과 (§5.7, §8.5)', () => {
const pos = (opts: Partial<RummikubOptions> = {}, pool?: string[]) => {
const s = mk(opts);
const racks = { A: ['K1a', 'K2a', 'K3a', 'O9a'], B: ['B1a'] };
const table = [['R4a', 'R5a', 'R6a']];
if (pool) {
// Park everything except `pool` in B's rack so the pool has exactly these tiles.
const used = new Set([...racks.A, ...table.flat(), ...pool]);
racks.B = ALL_TILE_IDS.filter((id) => !used.has(id));
}
return rig(s, { racks, table, melded: ['A'], ...(pool ? { pool } : {}) });
};
test('timeout is system-only and legal for the current player', () => {
const s = pos();
expect(rummikub.actionSchema.safeParse({ type: 'timeout' }).success).toBe(false);
expect(rummikub.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
expect(rummikub.validate(s, 'A', rummikub.onTimeout(s, 'A')).ok).toBe(true);
expect(rummikub.deadline!(s)).toBe(s.turnStartedAt + 60_000);
});
test('invalid draft: table and rack restored, 3 tiles drawn; with only 2 in the pool, 2', () => {
let s = pos();
const rackBefore = [...s.racks.A!];
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a'] }, { tileIds: ['R6a', 'K1a'] }] });
s = act(s, 'A', { type: 'timeout' });
expect(setsOf(s)).toEqual([['R4a', 'R5a', 'R6a']]);
expect(s.racks.A!.slice(0, 4)).toEqual(rackBefore);
expect(s.racks.A).toHaveLength(7);
expect(s.lastDrawn.A).toHaveLength(3);
expect(s.current).toBe('B');
let t = pos({}, ['O13a', 'O13b']);
t = act(t, 'A', { type: 'setDraft', sets: [...tableSets(t), { tileIds: ['K1a'] }] });
t = act(t, 'A', { type: 'timeout' });
expect(t.racks.A).toHaveLength(6);
expect(t.pool).toEqual([]);
});
test('invalidTimeoutPenalty=1 draws only one', () => {
let s = pos({ invalidTimeoutPenalty: 1 });
s = act(s, 'A', { type: 'setDraft', sets: [...tableSets(s), { tileIds: ['K1a'] }] });
s = act(s, 'A', { type: 'timeout' });
expect(s.racks.A).toHaveLength(5);
});
test('valid draft: auto-commit (default) or revert + draw 1; no change: draw 1', () => {
let s = pos();
s = act(s, 'A', { type: 'setDraft', sets: [...tableSets(s), { tileIds: ['K1a', 'K2a', 'K3a'] }] });
s = act(s, 'A', { type: 'timeout' });
expect(setsOf(s)).toEqual([['R4a', 'R5a', 'R6a'], ['K1a', 'K2a', 'K3a']]);
expect(s.racks.A).toEqual(['O9a']);
expect(s.log.at(-1)).toMatchObject({ kind: 'timeoutCommit', count: 3 });
let r = pos({ timeoutValidDraft: 'revert' });
r = act(r, 'A', { type: 'setDraft', sets: [...tableSets(r), { tileIds: ['K1a', 'K2a', 'K3a'] }] });
r = act(r, 'A', { type: 'timeout' });
expect(setsOf(r)).toEqual([['R4a', 'R5a', 'R6a']]);
expect(r.racks.A).toHaveLength(5);
let u = pos();
u = act(u, 'A', { type: 'timeout' });
expect(u.racks.A).toHaveLength(5);
expect(u.log.at(-1)).toMatchObject({ kind: 'timeoutDraw', count: 1 });
});
test('3 timeouts in a row → away: the deadline becomes short; acting again resets it', () => {
let s = mk({}, ['A', 'B'], 2);
const p = s.current;
for (let i = 0; i < 3; i++) {
s = act(s, p, { type: 'timeout' });
s = act(s, s.current, { type: 'draw' });
}
expect(rummikub.view(s, null).seats.find((x) => x.id === p)!.away).toBe(true);
expect(rummikub.deadline!(s)).toBe(s.turnStartedAt + 3000);
s = act(s, p, { type: 'draw' });
expect(s.timeoutsInRow[p]).toBe(0);
});
test('무제한: 차례 마감이 없고(타이머 0), 연결이 끊겨 3번 넘어간 사람만 짧은 마감', () => {
let s = mk({ turnSeconds: null }, ['A', 'B'], 2);
expect(rummikub.deadline!(s)).toBeNull();
expect(rummikub.view(s, null).turnMs).toBe(0);
const p = s.current;
for (let i = 0; i < 3; i++) {
s = act(s, p, { type: 'timeout' });
expect(rummikub.deadline!(s)).toBeNull();
s = act(s, s.current, { type: 'draw' });
}
expect(rummikub.deadline!(s)).toBe(s.turnStartedAt + 3000);
s = act(s, p, { type: 'draw' });
s = act(s, s.current, { type: 'draw' });
expect(rummikub.deadline!(s)).toBeNull();
});
});
// ---------------------------------------------------------------- scoring / end
describe('점수와 끝 (§6, §5.8)', () => {
test('rack emptied: 4-player example B -15, C 조커 -30, D -15, A +60', () => {
const r = scoreRound({ A: [], B: ['R3a', 'K12a'], C: ['JK1'], D: ['R1a', 'B1a', 'O13a'] }, ['A', 'B', 'C', 'D'], 'rackEmpty', 30);
expect(r.winners).toEqual(['A']);
expect(r.scores).toEqual({ A: 60, B: -15, C: -30, D: -15 });
expect(scoreRound({ A: [], B: ['JK1'] }, ['A', 'B'], 'rackEmpty', 50).scores).toEqual({ A: 50, B: -50 });
});
test('stalemate example: A=5, B=12, C=30 → A +32, B -7, C -25; ties: fewer tiles, then shared', () => {
const r = scoreRound({ A: ['R5a'], B: ['R12a'], C: ['R10a', 'B10a', 'K10a'] }, ['A', 'B', 'C'], 'stalemate', 30);
expect(r.winners).toEqual(['A']);
expect(r.scores).toEqual({ A: 32, B: -7, C: -25 });
const t = scoreRound({ A: ['R5a'], B: ['R2a', 'R3a'], C: ['R10a'] }, ['A', 'B', 'C'], 'stalemate', 30);
expect(t.winners).toEqual(['A']);
const sh = scoreRound({ A: ['R5a'], B: ['B5a'], C: ['R10a'] }, ['A', 'B', 'C'], 'stalemate', 30);
expect(sh.winners).toEqual(['A', 'B']);
expect(sh.scores).toEqual({ A: 2, B: 2, C: -5 });
});
test('emptying the rack ends the game with ranking, scores and a Korean summary', () => {
let s = rig(mk({}, ['A', 'B', 'C', 'D']), {
racks: { A: ['K1a', 'K2a', 'K3a'], B: ['R3a', 'K12a'], C: ['JK1'], D: ['R1a', 'B1a', 'O13a'] },
melded: ['A'],
});
s = play(s, 'A', [['K1a', 'K2a', 'K3a']]);
expect(s.phase).toBe('finished');
const res = rummikub.result(s)!;
expect(res.ranking).toEqual([['A'], ['B', 'D'], ['C']]);
expect(res.scores).toEqual({ A: 60, B: -15, C: -30, D: -15 });
expect(res.summary).toContain('+60점');
expect(res.reason).toBe('normal');
expect(rummikub.view(s, 'B').round!.revealed.C).toEqual(['JK1']);
expect(reason(s, 'B', { type: 'draw' })).toBe('게임이 이미 끝났어요.');
});
test('stalemate: empty pool, 3 players pass in a row → end; a commit in between resets the count', () => {
const s0 = mk({}, ['A', 'B', 'C']);
// Empty pool: everything else is parked in C's rack.
const racks: Record<string, string[]> = { A: ['K1a', 'K2a', 'K3a', 'R5a'], B: ['R12a'] };
const used = new Set(Object.values(racks).flat());
racks.C = ALL_TILE_IDS.filter((id) => !used.has(id));
let s = rig(s0, { racks, melded: ['A', 'B', 'C'], pool: [] });
s = act(s, 'A', { type: 'pass' });
s = act(s, 'B', { type: 'pass' });
expect(s.consecutivePasses).toBe(2);
s = play(s, 'C', [['O11a', 'O12a', 'O13a']]);
expect(s.consecutivePasses).toBe(0);
s = act(s, 'A', { type: 'draw' }); // empty pool: draw = pass
s = act(s, 'B', { type: 'pass' });
expect(s.phase).toBe('playing');
s = act(s, 'C', { type: 'timeout' }); // a timeout without playing counts too
expect(s.phase).toBe('finished');
expect(s.round!.endReason).toBe('stalemate');
// A = 1+2+3+5 = 11 < B = 12.
expect(s.round!.winners).toEqual(['A']);
expect(s.round!.scores.A! + s.round!.scores.B! + s.round!.scores.C!).toBe(0);
});
test('pass is refused while the pool has tiles', () => {
const s = mk();
expect(reason(s, s.current, { type: 'pass' })).toBe('가져올 타일이 남아 있으면 넘길 수 없어요. 한 장 가져와 주세요.');
});
test('gamesPerMatch=2: round end → ready → new deal; wins then totals decide', () => {
let s = rig(mk({ gamesPerMatch: '2' }), { racks: { A: ['K1a', 'K2a', 'K3a'], B: ['R10a', 'R11a'] }, melded: ['A'] });
s = play(s, 'A', [['K1a', 'K2a', 'K3a']]);
expect(s.phase).toBe('roundEnd');
expect(rummikub.result(s)).toBeNull();
expect(s.match).toMatchObject({ gameNo: 1, total: 2, wins: { A: 1, B: 0 }, totals: { A: 21, B: -21 } });
expect(rummikub.activePlayers(s).sort()).toEqual(['A', 'B']);
expect(rummikub.deadline!(s)).toBe(s.roundEndAt! + 30_000);
expect(reason(s, 'A', { type: 'draw' })).toBe('다음 판을 기다리는 중이에요.');
s = act(s, 'A', { type: 'ready' });
expect(reason(s, 'A', { type: 'ready' })).toBe('이미 준비했어요.');
s = act(s, 'B', { type: 'timeout' });
expect(s.phase).toBe('playing');
expect(s.match.gameNo).toBe(2);
expect(s.table).toEqual([]);
expect(Object.values(s.racks).map((r) => r.length)).toEqual([14, 14]);
expect(rummikub.view(s, 'A').round!.revealed).toEqual({});
s = rig(s, { racks: { A: ['O5a'], B: ['B1a', 'B2a', 'B3a'] }, current: 'B', melded: ['B'] });
s = play(s, 'B', [['B1a', 'B2a', 'B3a']]);
expect(s.phase).toBe('finished');
// 1 win each; totals A 21-5 = 16, B -21+5 = -16 → A first.
expect(rummikub.result(s)!.ranking).toEqual([['A'], ['B']]);
expect(rummikub.result(s)!.summary).toContain('2판 끝');
});
test('gamesPerMatch=players uses the number of players', () => {
expect(mk({ gamesPerMatch: 'players' }, ['A', 'B', 'C']).match.total).toBe(3);
});
});
// ---------------------------------------------------------------- leaving
describe('나가기', () => {
test('3 players: the current player leaves → the next one plays; left players are skipped', () => {
let s = mk({}, ['A', 'B', 'C'], 4);
const p = s.current;
expect(rummikub.onLeave!(s, p)).toEqual({ type: 'leave' });
s = act(s, p, { type: 'leave' });
expect(s.current).not.toBe(p);
for (let i = 0; i < 4; i++) {
expect(s.current).not.toBe(p);
s = act(s, s.current, { type: 'draw' });
}
expect(reason(s, p, { type: 'draw' })).toBe('방을 나간 플레이어예요.');
expect(rummikub.onLeave!(s, p)).toBeNull();
});
test('2 players: one leaves → finished, the other ranks first', () => {
let s = mk({}, ['A', 'B']);
s = act(s, 'B', { type: 'leave' });
expect(s.phase).toBe('finished');
expect(rummikub.result(s)).toMatchObject({ ranking: [['A'], ['B']], reason: 'abandoned' });
});
});
// ---------------------------------------------------------------- information
describe('정보 공개 (§8.3)', () => {
test('opponents and spectators see counts only; the draft is hidden unless showDraftToOthers', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'O7a'], B: ['B1a', 'B9b'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A'] });
s = act(s, 'A', { type: 'setDraft', sets: [...tableSets(s), { tileIds: ['K1a', 'K2a', 'K3a'] }] });
for (const viewer of ['B', null]) {
const v = rummikub.view(s, viewer);
const json = JSON.stringify(v);
for (const id of [...s.racks.A!, ...s.pool, ...(viewer ? [] : s.racks.B!)]) expect(json.includes(`"${id}"`)).toBe(false);
expect(v.draft).toBeNull();
expect(v.draftEdits).toBe(1);
expect(v.seats.find((x) => x.id === 'A')!.tiles).toBe(4);
expect(v.poolCount).toBe(s.pool.length);
}
expect(rummikub.view(s, 'B').my!.rack).toEqual(['B1a', 'B9b']);
const own = rummikub.view(s, 'A');
expect(own.draft!.map((d) => d.ok)).toEqual([true, true]);
expect(own.my!.check).toMatchObject({ ok: true, fromRack: 3 });
let t = rig(mk({ showDraftToOthers: true }), { racks: { A: ['K1a', 'K2a', 'K3a', 'O7a'], B: ['B1a'] }, melded: ['A'] });
t = act(t, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a', 'K2a', 'K3a'] }] });
const vb = rummikub.view(t, 'B');
expect(vb.draft!.map((d) => d.tileIds)).toEqual([['K1a', 'K2a', 'K3a']]);
expect(JSON.stringify(vb).includes('"O7a"')).toBe(false);
expect(rummikub.secretsOf!(t, 'A')).not.toContain('K1a');
});
test('draw events carry no tile; only the drawer sees the new tile', () => {
const s = mk();
const p = s.current;
const out = actE(s, p, { type: 'draw' });
const drawn = out.state.lastDrawn[p]!;
expect(drawn).toHaveLength(1);
expect(JSON.stringify(out.events).includes(drawn[0]!)).toBe(false);
expect(out.events).toEqual([{ type: 'drew', player: p, count: 1, penalty: false }]);
expect(rummikub.view(out.state, p).my!.lastDrawn).toEqual(drawn);
const other = s.seats.find((x) => x !== p)!;
expect(JSON.stringify(rummikub.view(out.state, other)).includes(`"${drawn[0]}"`)).toBe(false);
});
test('the opening draw is shown without tile ids (they are shuffled back)', () => {
const s = mk({}, ['A', 'B', 'C']);
expect(s.opening.length).toBeGreaterThanOrEqual(3);
expect(JSON.stringify(s.opening)).not.toMatch(/[KRBO]\d+[ab]/);
});
});
// ---------------------------------------------------------------- concurrency
describe('동시성', () => {
test('the same commit twice: the second is "not your turn"', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'R1a'], B: ['B1a'] }, melded: ['A'] });
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a', 'K2a', 'K3a'] }] });
const commit = { type: 'commit' } as const;
s = act(s, 'A', commit);
expect(reason(s, 'A', commit)).toBe('지금은 내 차례가 아니에요.');
});
test('a setDraft from an earlier turn is refused (turn number)', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'R1a'], B: ['B1a'] }, melded: ['A'] });
const turn = s.turnNo;
s = act(s, 'A', { type: 'draw' });
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a'] }], turn })).toBe('지금은 내 차례가 아니에요.');
s = act(s, 'B', { type: 'draw' });
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a'] }], turn })).toBe('지난 차례의 요청이라 무시했어요.');
expect(rummikub.validate(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a'] }], turn: s.turnNo }).ok).toBe(true);
});
});
// ---------------------------------------------------------------- options / hints
describe('옵션과 힌트', () => {
test('every option has a Korean title; defaults follow the doc', () => {
const shape = (rummikub.optionsSchema as unknown as { shape: Record<string, { meta(): { title?: string } | undefined }> }).shape;
for (const [k, v] of Object.entries(shape)) expect(v.meta()?.title, k).toBeTruthy();
expect(rummikub.defaultOptions).toEqual({
initialMeldPoints: 30,
turnSeconds: 60,
timeoutValidDraft: 'commit',
invalidTimeoutPenalty: 3,
invalidCommitPenalty: 'reject',
jokerPenalty: 30,
initialMeldAllowExtend: false,
showDraftToOthers: false,
gamesPerMatch: '1',
hints: true,
});
expect(rummikub.optionsSchema.safeParse({ initialMeldPoints: 25 }).success).toBe(false);
});
test('findMeld finds a 30+ point combination from the rack only', () => {
const m = findMeld(['R10a', 'R11a', 'R12a', 'K1a', 'B5a'], 30)!;
expect(m.map((x) => x.tileIds)).toEqual([['R10a', 'R11a', 'R12a']]);
expect(findMeld(['B1a', 'B2a', 'B3a', 'K5a', 'R5a', 'O5a'], 30)).toBeNull();
});
});
// ---------------------------------------------------------------- properties
const CONFIGS: Partial<RummikubOptions>[] = [
{},
{ initialMeldPoints: 0, showDraftToOthers: true },
{ initialMeldPoints: 50, invalidCommitPenalty: 'penalty3', jokerPenalty: 50 },
{ timeoutValidDraft: 'revert', invalidTimeoutPenalty: 1, initialMeldAllowExtend: true },
{ gamesPerMatch: '2', initialMeldPoints: 20 },
];
/** Every tile exactly once across pool, racks and table. */
let checkedTable: unknown = null;
function conserved(st: unknown): void {
const s = st as RummikubState;
const all = [...s.pool, ...s.table.flatMap((t) => t.tileIds), ...Object.values(s.racks).flat()];
if (all.length !== 106 || new Set(all).size !== 106) throw new Error(`tiles not conserved: ${all.length}/${new Set(all).size}`);
// The committed table is always made of valid sets (checked once per turn; it only changes between turns).
const key = `${s.match.gameNo}:${s.turnNo}`;
if (checkedTable === key) return;
checkedTable = key;
for (const t of s.table) if (!normalizeSet({ tileIds: t.tileIds, as: t.kind })) throw new Error(`invalid table set ${t.tileIds}`);
}
describe('random playouts (docs/09 §7)', () => {
test('engine randomPlayout (round trip, checkNoLeak via secretsOf, determinism) across options', () => {
// At least one game per config even in the quick run.
const games = Math.max(CONFIGS.length, playoutSeeds(25));
for (let i = 0; i < games; i++) {
const options = rummikub.optionsSchema.parse(CONFIGS[i % CONFIGS.length]);
const players = ['P0', 'P1', 'P2', 'P3'].slice(0, 2 + (i % 3));
const a = randomPlayout(rummikub, { players, options, seed: seedN(9000 + i), maxSteps: 4000, invariant: conserved, maxApplyMs: 30 });
expect(a.finished).toBe(true);
if (i < 5) {
const b = randomPlayout(rummikub, { players, options, seed: seedN(9000 + i), maxSteps: 4000, maxApplyMs: 30 });
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
}
}
}, 60_000);
/**
* 1,000 seeds (FULL_TESTS; 100 otherwise), same checks as randomPlayout with each view computed once per step (fast leak check),
* plus: onTimeout legal for every waiting player at every step, and 1 in 8 moves is a timeout.
*/
const TILE_RE = /"(?:[KRBO]\d{1,2}[ab]|JK[12])"/g;
function run(seed: number): { state: RummikubState; steps: number } {
const options = rummikub.optionsSchema.parse(CONFIGS[seed % CONFIGS.length]);
const players = ['P0', 'P1', 'P2', 'P3'].slice(0, 2 + (seed % 3));
const rng = SeededRng.fromSeed(seedN(seed));
const chooser = SeededRng.fromSeed(seedN(seed + 500_000));
let now = 1_700_000_000_000;
let s = rummikub.setup({ players, options, rng, now });
for (let step = 0; step < 4000; step++) {
// JSON round trip is checked every step in the engine playouts above (apply itself clones through JSON); here every 10th step.
if (step % 10 === 0) {
const json = JSON.stringify(s);
if (JSON.stringify(JSON.parse(json)) !== json) throw new Error('not JSON round-trippable');
}
conserved(s);
// Leak check: which hidden tile belongs to whom; every viewer (and a spectator) is checked once.
const pool = new Set(s.pool);
const owner = new Map<string, PlayerId>();
for (const p of players) for (const id of rummikub.secretsOf!(s, p)) owner.set(id, pool.has(id) ? '*pool' : p);
for (const viewer of [...players, null]) {
const ids = JSON.stringify(rummikub.view(s, viewer)).match(TILE_RE) ?? [];
for (const q of ids) {
const o = owner.get(q.slice(1, -1));
if (o && o !== viewer) throw new Error(`seed ${seed} step ${step}: ${viewer} sees ${q} of ${o}`);
}
}
if (rummikub.result(s)) return { state: s, steps: step };
const waiting = rummikub.activePlayers(s);
if (!waiting.length) throw new Error('no active players');
for (const p of waiting) {
const v = rummikub.validate(s, p, rummikub.onTimeout(s, p));
if (!v.ok) throw new Error(`seed ${seed}: onTimeout illegal: ${v.reason}`);
}
const actor = waiting[chooser.int(waiting.length)]!;
const legal = rummikub.legalActions!(s, actor);
const a = legal.length && chooser.int(8) !== 0 ? legal[chooser.int(legal.length)]! : rummikub.onTimeout(s, actor);
const v = rummikub.validate(s, actor, a);
if (!v.ok) throw new Error(`seed ${seed}: generated action rejected: ${v.reason} ${JSON.stringify(a)}`);
now += 1000;
const t0 = performance.now();
const out = rummikub.apply(s, actor, a, { rng, now });
const ms = performance.now() - t0;
if (ms > 30) throw new Error(`apply took ${ms.toFixed(1)}ms`);
for (const e of out.events) {
const ids = JSON.stringify(e).match(TILE_RE) ?? [];
for (const q of ids) if (!out.state.table.some((t) => t.tileIds.includes(q.slice(1, -1)))) throw new Error(`event leaks ${q}`);
}
s = out.state;
}
throw new Error(`seed ${seed}: not finished within 4000 steps`);
}
const totalSeeds = playoutSeeds(1000);
for (let chunk = 0; chunk * 100 < totalSeeds; chunk++) {
test(`seeded playouts: seeds ${chunk * 100 + 1}–${chunk * 100 + 100}`, () => {
const ends: Record<string, number> = {};
for (let seed = chunk * 100 + 1; seed <= chunk * 100 + 100; seed++) {
const { state } = run(seed);
expect(state.phase).toBe('finished');
const res = rummikub.result(state)!;
expect(res.ranking.flat().sort()).toEqual([...state.seats].sort());
const k = state.round?.endReason ?? 'none';
ends[k] = (ends[k] ?? 0) + 1;
if (seed % 100 === 0) expect(JSON.stringify(run(seed).state)).toBe(JSON.stringify(state));
}
expect(ends.stalemate ?? 0).toBeGreaterThan(0);
}, 60_000);
}
});