병합: 루미큐브 앱 규칙 기본 + 끌어다 놓는 판(움직이는 동안 모두에게 보임)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-14 04:43:03 +09:00
13 changed files with 1587 additions and 534 deletions

View File

@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN, type PlayerId } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { ALL_TILE_IDS, normalizeSet, rummikub, type RummikubAction, type RummikubOptions, type RummikubState } from './index';
import { ALL_TILE_IDS, cellsOf, layoutSets, normalizeSet, rummikub, stripsOf, type RummikubAction, type RummikubOptions, type RummikubState } from './index';
const ME = 'bot:1:x';
const OTHER = 'human0';
@@ -14,18 +14,19 @@ function rig(o: { rack: string[]; table?: string[][]; melded?: boolean; opts?: P
const otherRack = ALL_TILE_IDS.filter((id) => !o.rack.includes(id) && !table.flat().includes(id)).slice(-14);
const used = new Set([...o.rack, ...table.flat(), ...otherRack]);
s.racks = { [ME]: [...o.rack], [OTHER]: otherRack };
const strips = layoutSets(table)!;
s.table = table.map((ids, i) => {
const n = normalizeSet({ tileIds: ids })!;
return { id: `s${i + 1}`, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs };
return { id: `s${i + 1}`, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs, r: strips[i]!.r, c: strips[i]!.c };
});
s.pool = ALL_TILE_IDS.filter((id) => !used.has(id));
s.current = ME;
s.hasMelded = { [ME]: !!o.melded, [OTHER]: true };
s.draft = { sets: s.table.map((t) => ({ tileIds: [...t.tileIds], as: t.kind })), history: [], edits: 0 };
s.draft = { cells: cellsOf(s.table), edits: 0 };
return s;
}
/** Lets the bot finish its turn (draft, then commit); returns the actions it took. */
/** Lets the bot finish its turn; returns the actions it took. */
function botTurn(s: RummikubState): { state: RummikubState; acts: RummikubAction[] } {
const acts: RummikubAction[] = [];
let now = 1000;
@@ -41,7 +42,7 @@ describe('rummikub bot', () => {
test('makes the 30-point first meld from its rack and commits it in the same turn', () => {
const s = rig({ rack: ['R10a', 'R11a', 'R12a', 'K3a', 'B3a', 'O3a', 'B7a', 'K9b'] });
const { state, acts } = botTurn(s);
expect(acts.map((a) => a.type)).toEqual(['setDraft', 'commit']);
expect(acts.map((a) => a.type)).toEqual(['commit']);
expect(state.hasMelded[ME]).toBe(true);
expect(state.racks[ME]!.sort()).toEqual(['B7a', 'K9b']);
});
@@ -57,14 +58,17 @@ describe('rummikub bot', () => {
test('after melding it lays tiles off on table sets (extending runs repeatedly)', () => {
const s = rig({ rack: ['B8a', 'B9a', 'O5a', 'K1a'], table: [['B5a', 'B6a', 'B7a'], ['R5a', 'K5a', 'B5b']], melded: true });
const { state, acts } = botTurn(s);
expect(acts.map((a) => a.type)).toEqual(['setDraft', 'commit']);
expect(acts.map((a) => a.type)).toEqual(['commit']);
expect(state.racks[ME]).toEqual(['K1a']);
expect(state.table.map((t) => t.tileIds.length).sort()).toEqual([4, 5]);
// The run stays where it was and grows to the right; the group it grew into moves to a free place.
expect(state.table.find((t) => t.tileIds.includes('B5a'))).toMatchObject({ r: 0, c: 0 });
expect(stripsOf(cellsOf(state.table))).toHaveLength(2);
});
test('a half-built draft (left from a timeout race) is dropped by drawing, never committed', () => {
test('a half-built working table (left from a timeout race) is dropped by drawing, never committed', () => {
let s = rig({ rack: ['R1a', 'B9a', 'K4a'], melded: true });
s = rummikub.apply(s, ME, { type: 'setDraft', sets: [{ tileIds: ['R1a'] }] }, { rng: SeededRng.fromSeed(seedN(2)), now: 500 }).state;
s = rummikub.apply(s, ME, { type: 'arrange', cells: [{ id: 'R1a', r: 3, c: 3 }] }, { rng: SeededRng.fromSeed(seedN(2)), now: 500 }).state;
const { state, acts } = botTurn(s);
expect(acts.map((a) => a.type)).toEqual(['draw']);
expect(state.racks[ME]).toHaveLength(4);

View File

@@ -1,12 +1,11 @@
/**
* 루미큐브 computer player. A turn is two decisions: first one `setDraft` with the whole plan (rack-only sets, then
* single tiles laid off on table / new sets), then `commit` once the view says the draft is valid. If the draft is
* not valid (should not happen) it draws, which also throws the draft away — it never leaves a half-built draft.
* Table sets are never rearranged beyond adding tiles to their ends.
* 루미큐브 computer player. A turn is one decision: the whole plan (rack-only sets, then single tiles laid off on
* table / new sets) laid out on the grid and sent as `commit` with its cells, or a draw. Table sets are never
* rearranged beyond adding tiles to their ends; they keep their places when there is room.
*/
import type { BotStrategy } from '../bots/types';
import { answerRequests } from '../bots/policy';
import { extendSet, isJoker, pickDisjoint, type JokerAs } from './rules';
import { cellsOf, extendSet, isJoker, layoutSets, pickDisjoint, type JokerAs } from './rules';
import type { RummikubAction, RummikubView } from './index';
type Plan = { tileIds: string[]; kind: 'run' | 'group'; jokerAs: Record<string, JokerAs> };
@@ -35,9 +34,8 @@ export const rummikubBot: BotStrategy<RummikubView, RummikubAction> = ({ view, l
if (req) return req;
if (legal.some((a) => a.type === 'ready')) return { type: 'ready' };
const my = view.my!;
// Drawing also throws away anything left on the working table (e.g. after a timeout race).
const endTurn: RummikubAction = legal.find((a) => a.type === 'pass') ?? { type: 'draw' };
// Second step of a turn: the plan is on the table — commit it, or give up cleanly (draw resets the draft).
if (my.changed) return my.check?.ok ? { type: 'commit', turn: view.turnNo } : endTurn;
const rack = my.rack;
const table: Plan[] = view.table.map((t) => ({ tileIds: [...t.tileIds], kind: t.kind, jokerAs: t.jokerAs }));
@@ -58,5 +56,10 @@ export const rummikubBot: BotStrategy<RummikubView, RummikubAction> = ({ view, l
}
const before = new Set(view.table.flatMap((t) => t.tileIds));
if (!sets.some((s) => s.tileIds.some((id) => !before.has(id)))) return endTurn;
return { type: 'setDraft', sets: sets.map((s) => ({ tileIds: s.tileIds, as: s.kind })), turn: view.turnNo };
const strips = layoutSets(
sets.map((s) => s.tileIds),
view.table,
);
if (!strips) return endTurn;
return { type: 'commit', cells: cellsOf(strips), turn: view.turnNo };
};

View File

@@ -3,18 +3,28 @@ import { z } from 'zod';
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine';
import {
ALL_TILE_IDS,
BOARD_COLS,
BOARD_ROWS,
arrangementKey,
cellKey,
cellsKey,
cellsOf,
extendSet,
findMeld,
isJoker,
freeSpot,
inBoard,
layoutSets,
pickDisjoint,
normalizeSet,
rackValue,
setProblem,
stripsOf,
tileOf,
type Cell,
type DraftSet,
type JokerAs,
type NormalSet,
type Strip,
type TileColor,
} from './rules';
@@ -23,47 +33,61 @@ export * from './rules';
const lit = <T extends number | null>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
/** Defaults follow the Rummikub app (§2, docs/13-decisions.md); the printed rulebook's choices stay selectable. */
export const rummikubOptionsSchema = z.object({
initialMeldPoints: lit(0, 20, 30, 50)
.default(30)
.meta({ title: '첫 등록 최소 점수', labels: { 0: '없음', 20: '20점', 30: '30점(공식)', 50: '50점' } }),
turnSeconds: lit(60, 90, 120, 180, null)
turnSeconds: lit(30, 60, 90, 120, 180, null)
.default(60)
.meta({ title: '한 차례 제한 시간', labels: { 60: '1분(공식)', 90: '1분 30초', 120: '2분', 180: '3분', null: '무제한' } }),
.meta({ title: '한 차례 제한 시간', labels: { 30: '30초', 60: '1분(공식)', 90: '1분 30초', 120: '2분', 180: '3분', null: '무제한' } }),
timeoutValidDraft: z
.enum(['commit', 'revert'])
.default('commit')
.meta({ title: '시간이 다 됐을 때 올바르게 놓아 둔 타일', labels: { commit: '자동으로 확정', revert: '되돌리고 한 장 가져오기(공식)' } }),
.default('revert')
.meta({ title: '시간이 다 됐을 때 올바르게 놓아 둔 타일', labels: { commit: '자동으로 완료', revert: '되돌리고 한 장 가져오기(앱·공식)' } }),
invalidTimeoutPenalty: lit(1, 3)
.default(3)
.meta({ title: '시간이 다 됐는데 덜 맞췄을 때 가져올 장수', labels: { 1: '1장', 3: '3장(공식)' } }),
.default(1)
.meta({ title: '시간이 다 됐는데 덜 맞췄을 때 가져올 장수', labels: { 1: '1장(앱)', 3: '3장(종이 규칙서)' } }),
invalidCommitPenalty: z
.enum(['reject', 'penalty3'])
.default('reject')
.meta({ title: '틀린 채로 확정을 누르면', labels: { reject: '알려 주고 계속 고치기', penalty3: '되돌리고 3장 가져오기' } }),
.meta({ title: '틀린 채로 완료를 누르면', labels: { reject: '알려 주고 계속 고치기(앱)', penalty3: '되돌리고 3장 가져오기' } }),
jokerPenalty: lit(30, 50)
.default(30)
.meta({ title: '받침대에 남은 조커 감점', labels: { 30: '30점(공식)', 50: '50점(대회)' } }),
initialMeldAllowExtend: z.boolean().default(false).meta({ title: '첫 등록하는 차례에 바닥 묶음에도 붙이기 허용' }),
showDraftToOthers: z.boolean().default(false).meta({ title: '고민 중인 배치를 다른 사람에게 보이기(되돌려도 이미 본 타일은 남아요)' }),
showDraftToOthers: z.boolean().default(true).meta({ title: '옮기는 타일을 모두에게 바로 보이기(앱처럼, 되돌려도 이미 본 타일은 남아요)' }),
gamesPerMatch: z
.enum(['1', 'players', '2', '3', '4'])
.default('1')
.meta({ title: '판 수', labels: { 1: '1판', players: '인원수만큼(공식)', 2: '2판', 3: '3판', 4: '4판' } }),
.meta({ title: '판 수', labels: { 1: '1판(앱)', players: '인원수만큼(종이 규칙서)', 2: '2판', 3: '3판', 4: '4판' } }),
hints: z.boolean().default(true).meta({ title: '"도와줘" 힌트 버튼' }),
});
export type RummikubOptions = z.infer<typeof rummikubOptionsSchema>;
const draftSetSchema = z.object({
tileIds: z.array(z.string().max(4)).min(1).max(106),
as: z.enum(['run', 'group']).optional(),
const cellSchema = z.object({
id: z.string().max(4),
r: z.number().int().min(0).max(BOARD_ROWS - 1),
c: z.number().int().min(0).max(BOARD_COLS - 1),
});
export const rummikubActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('setDraft'), sets: z.array(draftSetSchema).max(106), turn: z.number().int().optional() }),
z.object({ type: z.literal('undoDraft') }),
/** The whole working table after one drop (§5.6): checked loosely, shown to everybody. */
z.object({ type: z.literal('arrange'), cells: z.array(cellSchema).max(106), turn: z.number().int().optional() }),
/**
* Live drag preview (stream action, a few per second): the tiles in hand are at grid position (x, y), in cells.
* `ids` empty = the drag ended without a drop.
*/
z.object({
type: z.literal('drag'),
ids: z.array(z.string().max(4)).max(BOARD_COLS),
x: z.number().min(-4).max(BOARD_COLS + 4),
y: z.number().min(-4).max(BOARD_ROWS + 6),
turn: z.number().int().optional(),
}),
z.object({ type: z.literal('resetDraft') }),
z.object({ type: z.literal('commit'), turn: z.number().int().optional() }),
/** Ends the turn. `cells` (optional) is the final table, put down and checked in one step (computers, last drop). */
z.object({ type: z.literal('commit'), cells: z.array(cellSchema).max(106).optional(), turn: z.number().int().optional() }),
z.object({ type: z.literal('draw') }),
z.object({ type: z.literal('pass') }),
z.object({ type: z.literal('ready') }),
@@ -79,6 +103,9 @@ export interface TableSet {
tileIds: string[];
kind: 'run' | 'group';
jokerAs: Record<string, JokerAs>;
/** Grid position of the first tile; the set fills row `r` to the right. */
r: number;
c: number;
}
export type MoveKind = 'commit' | 'draw' | 'pass' | 'timeoutCommit' | 'timeoutDraw' | 'penalty' | 'left';
@@ -126,7 +153,8 @@ export interface RummikubState {
current: PlayerId;
turnNo: number;
turnStartedAt: number;
draft: { sets: DraftSet[]; history: DraftSet[][]; edits: number };
/** The current player's working table (grid cells) and how many drops they made this turn. */
draft: { cells: Cell[]; edits: number };
timeoutsInRow: Record<PlayerId, number>;
consecutivePasses: number;
/** Tiles each player drew at the end of their last turn (shown only to them). */
@@ -145,17 +173,17 @@ export interface RummikubState {
// ---------------------------------------------------------------- view
export interface DraftSetView {
/** One set on the working table with its live check (green / red outline on screen). */
export interface GroupView {
tileIds: string[];
as?: 'run' | 'group';
r: number;
c: number;
ok: boolean;
/** Short reason when not valid. */
problem: string | null;
kind: 'run' | 'group' | null;
jokerAs: Record<string, JokerAs>;
points: number;
/** Both readings possible ([빨강5, 조커, 조커]) — the screen offers a toggle. */
ambiguous: boolean;
}
export interface SeatView {
@@ -172,12 +200,23 @@ export interface SeatView {
export interface TurnCheck {
ok: boolean;
reason: string | null;
/** Indexes into `draft.groups` of the sets that are not valid. */
invalidIdx: number[];
/** Points of new rack-only sets (first meld progress). */
meldPoints: number;
fromRack: number;
}
/** Drag preview event (stream): tiles that are not on the table yet are hidden (null). */
export interface DragEvent {
type: 'drag';
player: PlayerId;
turn: number;
tiles: (string | null)[];
x: number;
y: number;
}
export interface RummikubView {
phase: RummikubState['phase'];
options: RummikubOptions;
@@ -188,19 +227,20 @@ export interface RummikubView {
/** 0 = 무제한. */
turnMs: number;
poolCount: number;
/** The committed table (positions included). */
table: TableSet[];
lastChanged: string[];
log: LogEntry[];
/** Number of edits the current player made this turn (shown as "생각 중"). */
/** Number of drops the current player made this turn (shown as "생각 중"). */
draftEdits: number;
/** Full draft: the current player always, others only with showDraftToOthers. */
draft: DraftSetView[] | null;
/** Working table: the current player always, everybody else with showDraftToOthers (live, §5.6). */
draft: { cells: Cell[]; groups: GroupView[] } | null;
me: PlayerId | null;
my: {
rack: string[];
lastDrawn: string[];
melded: boolean;
canUndo: boolean;
/** Anything moved this turn (되돌리기 is useful). */
changed: boolean;
check: TurnCheck | null;
needReady: boolean;
@@ -223,66 +263,87 @@ function turnLimitMs(s: RummikubState): number | null {
return s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000;
}
const ROUND_END_MS = 30_000;
const HISTORY_MAX = 100;
const activeSeats = (s: RummikubState): PlayerId[] => s.roundPlayers.filter((p) => !s.left.includes(p));
const startSets = (s: RummikubState): DraftSet[] => s.table.map((t) => ({ tileIds: [...t.tileIds], as: t.kind }));
const startCells = (s: RummikubState): Cell[] => cellsOf(s.table);
const tableTiles = (s: RummikubState): Set<string> => new Set(s.table.flatMap((t) => t.tileIds));
const draftChanged = (s: RummikubState): boolean => arrangementKey(s.draft.sets) !== arrangementKey(s.table);
const cleanSet = (d: DraftSet): DraftSet => (d.as ? { tileIds: [...d.tileIds], as: d.as } : { tileIds: [...d.tileIds] });
const setsOfCells = (cells: readonly Cell[]): DraftSet[] => stripsOf(cells).map((x) => ({ tileIds: x.tileIds }));
/** The sets differ from the turn start (moving whole sets around does not count). */
const draftChanged = (s: RummikubState): boolean => arrangementKey(setsOfCells(s.draft.cells)) !== arrangementKey(s.table);
/** Anything moved at all. */
const draftMoved = (s: RummikubState): boolean => cellsKey(s.draft.cells) !== cellsKey(startCells(s));
const resetDraft = (s: RummikubState): void => {
s.draft = { cells: startCells(s), edits: 0 };
};
function totalGames(o: RummikubOptions, players: number): number {
return o.gamesPerMatch === 'players' ? players : Number(o.gamesPerMatch);
}
/** C1–C3 (§8.2): tiles come from the start table or my rack, no duplicates, table tiles stay, first-meld rule. */
function conserve(s: RummikubState, p: PlayerId, sets: readonly DraftSet[]): string | null {
/**
* Loose check of a working table (§8.2 C1–C3): every tile from the start table or my rack, once, on its own cell,
* table tiles never back to the rack, and before the first meld the table tiles stay where they are.
*/
function conserve(s: RummikubState, p: PlayerId, cells: readonly Cell[]): string | null {
const start = tableTiles(s);
const rack = new Set(s.racks[p] ?? []);
const seen = new Set<string>();
for (const d of sets) {
if (d.tileIds.length === 0) return '빈 묶음이 있어요.';
for (const id of d.tileIds) {
if (seen.has(id)) return '같은 타일이 두 번 들어 있어요.';
seen.add(id);
if (!start.has(id) && !rack.has(id)) return '내 받침대나 바닥에 없는 타일이에요.';
}
const spots = new Set<number>();
for (const x of cells) {
if (seen.has(x.id)) return '같은 타일이 두 번 들어 있어요.';
seen.add(x.id);
if (!start.has(x.id) && !rack.has(x.id)) return '내 받침대나 바닥에 없는 타일이에요.';
if (!inBoard(x.r, x.c)) return '바닥 밖에는 놓을 수 없어요.';
const k = cellKey(x.r, x.c);
if (spots.has(k)) return '한 칸에 타일 두 개를 놓을 수 없어요.';
spots.add(k);
}
for (const id of start) if (!seen.has(id)) return '바닥의 타일은 내 받침대로 가져올 수 없어요.';
if (!s.hasMelded[p] && !s.options.initialMeldAllowExtend) {
const keys = new Set(sets.map((d) => [...d.tileIds].sort().join(',')));
for (const t of s.table) if (!keys.has([...t.tileIds].sort().join(','))) return '첫 등록 전에는 바닥의 타일을 옮길 수 없어요.';
const at = new Map(cells.map((x) => [x.id, cellKey(x.r, x.c)]));
for (const x of startCells(s)) if (at.get(x.id) !== cellKey(x.r, x.c)) return '첫 등록 전에는 바닥의 타일을 옮길 수 없어요.';
}
return null;
}
type TurnOutcome = { ok: true; normalized: NormalSet[]; fromRack: string[]; meldPoints: number } | { ok: false; reason: string; invalidIdx: number[]; meldPoints: number; fromRack: string[] };
type TurnOutcome =
| { ok: true; strips: Strip[]; normalized: NormalSet[]; fromRack: string[]; meldPoints: number }
| { ok: false; reason: string; invalidIdx: number[]; meldPoints: number; fromRack: string[] };
/** Turn commit validation (§8.2 validateTurn), shared by commit, timeout and the live check in the view. */
function validateTurn(s: RummikubState, p: PlayerId, sets: readonly DraftSet[], pre?: (NormalSet | null)[]): TurnOutcome {
function validateTurn(s: RummikubState, p: PlayerId, cells: readonly Cell[], pre?: { strips: Strip[]; norms: (NormalSet | null)[] }): TurnOutcome {
const start = tableTiles(s);
const fromRack = sets.flatMap((d) => d.tileIds).filter((id) => !start.has(id));
const normalized = pre ?? sets.map(normalizeSet);
const newOnly = normalized.filter((n, i) => n && sets[i]!.tileIds.every((id) => !start.has(id))) as NormalSet[];
const strips = pre?.strips ?? stripsOf(cells);
const normalized = pre?.norms ?? strips.map((x) => normalizeSet({ tileIds: x.tileIds }));
const fromRack = cells.map((x) => x.id).filter((id) => !start.has(id));
const newOnly = normalized.filter((n, i) => n && strips[i]!.tileIds.every((id) => !start.has(id))) as NormalSet[];
const meldPoints = newOnly.reduce((a, n) => a + n.points, 0);
const bad = (reason: string, invalidIdx: number[] = []): TurnOutcome => ({ ok: false, reason, invalidIdx, meldPoints, fromRack });
const c = conserve(s, p, sets);
const c = conserve(s, p, cells);
if (c) return bad(c);
if (fromRack.length === 0) return bad('받침대에서 타일을 1개 이상 내야 해요.');
const invalidIdx = normalized.flatMap((n, i) => (n ? [] : [i]));
if (invalidIdx.length) return bad('빨간 표시된 묶음을 고쳐 주세요.', invalidIdx);
if (!s.hasMelded[p]) {
if (!s.options.initialMeldAllowExtend) {
// The table sets must be exactly as they were: nothing added next to them.
const key = (ids: readonly string[]) => [...ids].sort().join(',');
const tableKeys = new Set(s.table.map((t) => key(t.tileIds)));
const idx = strips.flatMap((x, i) => (x.tileIds.some((id) => start.has(id)) && !tableKeys.has(key(x.tileIds)) ? [i] : []));
if (idx.length) return bad('첫 등록 전에는 바닥 묶음에 붙일 수 없어요. 한 칸 띄워 따로 놓아 주세요.', idx);
}
const min = s.options.initialMeldPoints;
if (meldPoints < min) return bad(`첫 등록은 ${min}점 이상이어야 해요 (지금 ${meldPoints}점).`);
}
return { ok: true, normalized: normalized as NormalSet[], fromRack, meldPoints };
return { ok: true, strips, normalized: normalized as NormalSet[], fromRack, meldPoints };
}
/** New table from normalized sets; ids are inherited from the old set with the biggest overlap. */
function buildTable(s: RummikubState, normalized: NormalSet[]): { table: TableSet[]; changed: string[] } {
/** New table from normalized sets at their strips; ids are inherited from the old set with the biggest overlap. */
function buildTable(s: RummikubState, out: Extract<TurnOutcome, { ok: true }>): { table: TableSet[]; changed: string[] } {
const taken = new Set<string>();
const changed: string[] = [];
const table = normalized.map((n) => {
const table = out.normalized.map((n, i) => {
const strip = out.strips[i]!;
let best: TableSet | null = null;
let bestOverlap = 0;
for (const t of s.table) {
@@ -302,7 +363,8 @@ function buildTable(s: RummikubState, normalized: NormalSet[]): { table: TableSe
id = `s${s.nextSetId++}`;
changed.push(id);
}
return { id, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs };
// The set keeps its strip; runs are written in ascending order (the server's reading of the jokers).
return { id, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs, r: strip.r, c: strip.c };
});
return { table, changed };
}
@@ -322,7 +384,7 @@ function startTurn(s: RummikubState, p: PlayerId, now: number): void {
s.current = p;
s.turnNo += 1;
s.turnStartedAt = now;
s.draft = { sets: startSets(s), history: [], edits: 0 };
resetDraft(s);
}
function nextPlayer(s: RummikubState, from: PlayerId): PlayerId {
@@ -335,9 +397,9 @@ function nextPlayer(s: RummikubState, from: PlayerId): PlayerId {
return from;
}
/** Turn ended without placing tiles: draw `count` (if the pool has any) or count it as a pass (§5.8). */
/** Turn ended without placing tiles: the table goes back, draw `count` (if the pool has any) or it counts as a pass (§5.8). */
function endWithoutPlay(s: RummikubState, p: PlayerId, count: number, kind: MoveKind, now: number, events: GameEvent[]): void {
s.draft = { sets: startSets(s), history: [], edits: 0 };
resetDraft(s);
const got = drawTiles(s, p, count);
s.lastDrawn[p] = got;
s.lastChanged = [];
@@ -357,7 +419,7 @@ function endWithoutPlay(s: RummikubState, p: PlayerId, count: number, kind: Move
}
function commitTurn(s: RummikubState, p: PlayerId, out: Extract<TurnOutcome, { ok: true }>, kind: MoveKind, now: number, events: GameEvent[]): void {
const { table, changed } = buildTable(s, out.normalized);
const { table, changed } = buildTable(s, out);
s.table = table;
const placed = new Set(out.fromRack);
s.racks[p] = s.racks[p]!.filter((id) => !placed.has(id));
@@ -425,7 +487,7 @@ function endRound(s: RummikubState, reason: 'rackEmpty' | 'stalemate', by: Playe
const revealed: Record<PlayerId, string[]> = {};
for (const p of players) revealed[p] = [...s.racks[p]!];
s.round = { gameNo: s.match.gameNo, endReason: reason, winners, scores, rackValues, revealed, ranking: rankByScore(players, winners, scores) };
s.draft = { sets: startSets(s), history: [], edits: 0 };
resetDraft(s);
events.push({ type: 'roundEnded', reason, winners, scores });
if (s.match.gameNo >= s.match.total || eligible.length < 2) finishMatch(s, eligible.length < 2 ? 'abandoned' : 'normal');
else {
@@ -513,21 +575,47 @@ function setupRound(s: RummikubState, rng: Rng, now: number): void {
startTurn(s, first, now);
}
function describeSet(d: DraftSet, n: NormalSet | null): DraftSetView {
// Only one number tile + jokers can be read both as a run and as a group.
const ambiguous = !!n && d.tileIds.length <= 4 && d.tileIds.filter((id) => !isJoker(id)).length === 1;
function describeGroup(x: Strip, n: NormalSet | null): GroupView {
return {
tileIds: d.tileIds,
...(d.as ? { as: d.as } : {}),
tileIds: x.tileIds,
r: x.r,
c: x.c,
ok: !!n,
problem: n ? null : setProblem(d),
problem: n ? null : setProblem({ tileIds: x.tileIds }),
kind: n?.kind ?? null,
jokerAs: n?.jokerAs ?? {},
points: n?.points ?? 0,
ambiguous,
};
}
/** The table cells a player would have after adding `sets` (whole sets, laid out like a computer would). */
function cellsFor(s: RummikubState, sets: readonly (readonly string[])[]): Cell[] | null {
const strips = layoutSets(sets, s.table);
return strips ? cellsOf(strips) : null;
}
/**
* Saves from before the grid (stateVersion 1): table sets get grid places, the working table its sets laid out the
* same way (the step-by-step undo history is dropped). Also tolerates a half-migrated state.
*/
function migrateV1(old: unknown): RummikubState {
const s = old as RummikubState & { table: (Omit<TableSet, 'r' | 'c'> & { r?: number; c?: number })[]; draft: { cells?: Cell[]; sets?: DraftSet[]; edits?: number } };
s.options = rummikubOptionsSchema.parse({ ...s.options });
if (s.table.some((t) => t.r === undefined || t.c === undefined)) {
const strips = layoutSets(s.table.map((t) => t.tileIds)) ?? [];
s.table = s.table.map((t, i) => ({ ...t, r: strips[i]?.r ?? 0, c: strips[i]?.c ?? 0 }));
}
const d = s.draft ?? {};
let cells: Cell[] | null = Array.isArray(d.cells) ? d.cells : null;
if (!cells && Array.isArray(d.sets)) {
const strips = layoutSets(d.sets.map((x) => x.tileIds), s.table as TableSet[]);
cells = strips ? cellsOf(strips) : null;
}
const st = s as RummikubState;
st.draft = { cells: cells ?? startCells(st), edits: d.edits ?? 0 };
return st;
}
// ---------------------------------------------------------------- definition
export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubView, RummikubOptions> = {
@@ -535,7 +623,7 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
nameKo: '루미큐브',
minPlayers: 2,
maxPlayers: 4,
stateVersion: 1,
stateVersion: 2,
defaultOptions: rummikubOptionsSchema.parse({}),
optionsSchema: rummikubOptionsSchema,
actionSchema: rummikubActionSchema as z.ZodType<RummikubAction>,
@@ -554,7 +642,7 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
current: players[0]!,
turnNo: 0,
turnStartedAt: now,
draft: { sets: [], history: [], edits: 0 },
draft: { cells: [], edits: 0 },
timeoutsInRow: Object.fromEntries(players.map((p) => [p, 0])),
consecutivePasses: 0,
lastDrawn: {},
@@ -582,26 +670,32 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
if (s.phase === 'finished') return fail('게임이 이미 끝났어요.');
if (a.type === 'leave') return s.left.includes(actor) ? fail('이미 나간 플레이어예요.') : ok;
if (s.left.includes(actor)) return fail('방을 나간 플레이어예요.');
// A late drag preview (the turn just ended) is dropped silently in apply, not answered with an error.
if (a.type === 'drag') return ok;
if (s.phase === 'roundEnd') {
if (a.type !== 'ready' && a.type !== 'timeout') return fail('다음 판을 기다리는 중이에요.');
return s.ready.includes(actor) ? fail('이미 준비했어요.') : ok;
}
if (a.type === 'ready') return fail('지금은 할 수 없어요.');
if (actor !== s.current) return fail('지금은 내 차례가 아니에요.');
if ((a.type === 'setDraft' || a.type === 'commit') && a.turn !== undefined && a.turn !== s.turnNo) return fail('지난 차례의 요청이라 무시했어요.');
if ((a.type === 'arrange' || a.type === 'commit') && a.turn !== undefined && a.turn !== s.turnNo) return fail('지난 차례의 요청이라 무시했어요.');
switch (a.type) {
case 'setDraft': {
const err = conserve(s, actor, a.sets);
case 'arrange': {
const err = conserve(s, actor, a.cells);
return err ? fail(err) : ok;
}
case 'undoDraft':
return s.draft.history.length ? ok : fail('되돌릴 것이 없어요.');
case 'resetDraft':
return ok;
case 'commit': {
const r = validateTurn(s, actor, s.draft.sets);
if (a.cells) {
const err = conserve(s, actor, a.cells);
if (err) return fail(err);
}
const cells = a.cells ?? s.draft.cells;
const r = validateTurn(s, actor, cells);
if (r.ok) return ok;
if (s.options.invalidCommitPenalty === 'reject' || !draftChanged(s) || r.fromRack.length === 0) return fail(r.reason);
const changed = arrangementKey(setsOfCells(cells)) !== arrangementKey(s.table);
if (s.options.invalidCommitPenalty === 'reject' || !changed || r.fromRack.length === 0) return fail(r.reason);
return ok;
}
case 'draw':
@@ -614,6 +708,16 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
},
apply(prev, actor, a, { rng, now }) {
if (a.type === 'drag') {
// Stream action: the state does not change; the event goes to everybody (tiles not on the table yet hidden).
const s = prev;
if (s.phase !== 'playing' || actor !== s.current || !s.options.showDraftToOthers || (a.turn !== undefined && a.turn !== s.turnNo)) return { state: prev, events: [] };
const onBoard = new Set(s.draft.cells.map((x) => x.id));
const rack = new Set(s.racks[actor] ?? []);
const tiles = a.ids.filter((id) => onBoard.has(id) || rack.has(id)).map((id) => (onBoard.has(id) ? id : null));
const ev: DragEvent = { type: 'drag', player: actor, turn: s.turnNo, tiles, x: a.x, y: a.y };
return { state: prev, events: [ev as unknown as GameEvent] };
}
// The state is plain JSON by contract; this is much faster than structuredClone.
const s = JSON.parse(JSON.stringify(prev)) as RummikubState;
const events: GameEvent[] = [];
@@ -627,7 +731,7 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
else if (s.seats.every((p) => s.ready.includes(p))) setupRound(s, rng, now);
} else if (activeSeats(s).length < 2) {
// Nobody left to play against: the match ends without scoring this round.
s.draft = { sets: startSets(s), history: [], edits: 0 };
resetDraft(s);
finishMatch(s, 'abandoned');
} else if (s.current === actor) {
pushLog(s, actor, 'left', 0);
@@ -641,26 +745,17 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
return { state: s, events };
}
switch (a.type) {
case 'setDraft':
s.draft.history.push(s.draft.sets);
if (s.draft.history.length > HISTORY_MAX) s.draft.history.shift();
s.draft.sets = a.sets.map(cleanSet);
s.draft.edits += 1;
break;
case 'undoDraft':
s.draft.sets = s.draft.history.pop()!;
case 'arrange':
s.draft.cells = a.cells.map((x) => ({ id: x.id, r: x.r, c: x.c }));
s.draft.edits += 1;
break;
case 'resetDraft':
if (draftChanged(s)) {
s.draft.history.push(s.draft.sets);
if (s.draft.history.length > HISTORY_MAX) s.draft.history.shift();
}
s.draft.sets = startSets(s);
s.draft.edits += 1;
if (draftMoved(s)) s.draft.edits += 1;
s.draft.cells = startCells(s);
break;
case 'commit': {
const r = validateTurn(s, actor, s.draft.sets);
if (a.cells) s.draft.cells = a.cells.map((x) => ({ id: x.id, r: x.r, c: x.c }));
const r = validateTurn(s, actor, s.draft.cells);
if (r.ok) commitTurn(s, actor, r, 'commit', now, events);
else endWithoutPlay(s, actor, 3, 'penalty', now, events);
break;
@@ -676,14 +771,18 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
endWithoutPlay(s, actor, 1, 'timeoutDraw', now, events);
break;
}
const r = validateTurn(s, actor, s.draft.sets);
const r = validateTurn(s, actor, s.draft.cells);
if (r.ok) {
// App rule (default): the turn is not finished until 완료, so even a valid table goes back (§5.7).
if (s.options.timeoutValidDraft === 'commit') commitTurn(s, actor, r, 'timeoutCommit', now, events);
else endWithoutPlay(s, actor, 1, 'timeoutDraw', now, events);
} else if (r.fromRack.length === 0 && r.invalidIdx.length === 0) {
// Only rearranged (or nothing from the rack): put it back, no penalty.
endWithoutPlay(s, actor, 1, 'timeoutDraw', now, events);
} else endWithoutPlay(s, actor, s.options.invalidTimeoutPenalty, 'penalty', now, events);
} else {
const n = s.options.invalidTimeoutPenalty;
endWithoutPlay(s, actor, n, n > 1 ? 'penalty' : 'timeoutDraw', now, events);
}
break;
}
}
@@ -695,10 +794,11 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
const playing = s.phase === 'playing';
const isCur = playing && me === s.current;
const draftVisible = playing && (isCur || s.options.showDraftToOthers);
const norms = draftVisible ? s.draft.sets.map(normalizeSet) : [];
const strips = draftVisible ? stripsOf(s.draft.cells) : [];
const norms = strips.map((x) => normalizeSet({ tileIds: x.tileIds }));
let check: TurnCheck | null = null;
if (isCur) {
const r = validateTurn(s, me, s.draft.sets, norms);
const r = validateTurn(s, me, s.draft.cells, { strips, norms });
check = r.ok
? { ok: true, reason: null, invalidIdx: [], meldPoints: r.meldPoints, fromRack: r.fromRack.length }
: { ok: false, reason: r.reason, invalidIdx: r.invalidIdx, meldPoints: r.meldPoints, fromRack: r.fromRack.length };
@@ -725,15 +825,14 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
lastChanged: s.lastChanged,
log: s.log,
draftEdits: playing ? s.draft.edits : 0,
draft: draftVisible ? s.draft.sets.map((d, i) => describeSet(d, norms[i] ?? null)) : null,
draft: draftVisible ? { cells: s.draft.cells, groups: strips.map((x, i) => describeGroup(x, norms[i] ?? null)) } : null,
me,
my: me
? {
rack: s.racks[me] ?? [],
lastDrawn: s.lastDrawn[me] ?? [],
melded: !!s.hasMelded[me],
canUndo: isCur && s.draft.history.length > 0,
changed: isCur && draftChanged(s),
changed: isCur && draftMoved(s),
check,
needReady: s.phase === 'roundEnd' && !s.ready.includes(me) && !s.left.includes(me),
}
@@ -748,6 +847,10 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
};
},
isStreamAction(a) {
return a.type === 'drag';
},
activePlayers(s) {
if (s.phase === 'playing') return [s.current];
if (s.phase === 'roundEnd') return s.seats.filter((p) => !s.ready.includes(p) && !s.left.includes(p));
@@ -783,15 +886,20 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
};
},
/** Test helper: draw / play rack-only sets / extend a table set / an invalid try, then commit or undo. */
/** v1 (sets without grid places) → v2 (grid). */
migrate(old, fromVersion) {
return fromVersion < 2 ? migrateV1(old) : (old as RummikubState);
},
/** Test helper: draw / lay out rack-only sets / extend a table set / an invalid try, then commit or reset. */
legalActions(s, p) {
if (!s.seats.includes(p) || s.left.includes(p) || s.phase === 'finished') return [];
if (s.phase === 'roundEnd') return s.ready.includes(p) ? [] : [{ type: 'ready' }];
if (p !== s.current) return [];
const acts: RummikubAction[] = [];
if (draftChanged(s)) {
const r = validateTurn(s, p, s.draft.sets);
if (r.ok) acts.push(s.draft.edits % 4 === 3 ? { type: 'undoDraft' } : { type: 'commit' });
const r = validateTurn(s, p, s.draft.cells);
if (r.ok) acts.push(s.draft.edits % 4 === 3 ? { type: 'resetDraft' } : { type: 'commit' });
else {
acts.push({ type: 'resetDraft' }, { type: 'draw' });
if (s.options.invalidCommitPenalty === 'penalty3' && r.fromRack.length > 0) acts.push({ type: 'commit' });
@@ -800,42 +908,50 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
}
const drawAct: RummikubAction = s.pool.length ? { type: 'draw' } : { type: 'pass' };
const rack = s.racks[p]!;
const base = startSets(s);
const base = s.table.map((t) => t.tileIds);
const push = (sets: string[][], direct = false) => {
const cells = cellsFor(s, sets);
if (cells) acts.push(direct ? { type: 'commit', cells } : { type: 'arrange', cells });
};
if (!s.hasMelded[p]) {
const meld = findMeld(rack, s.options.initialMeldPoints);
if (meld) acts.push({ type: 'setDraft', sets: [...base, ...meld.map((m) => ({ tileIds: m.tileIds }))] });
if (meld) push([...base, ...meld.map((m) => m.tileIds)], s.turnNo % 2 === 0);
} else {
// Everything playable at once: disjoint rack sets, then single tiles added to any set that accepts them.
const all: { tileIds: string[]; kind: 'run' | 'group'; jokerAs: Record<string, JokerAs> }[] = [...s.table, ...pickDisjoint(rack).sets];
const used = new Set(all.flatMap((d) => d.tileIds));
let firstExt: DraftSet[] | null = null;
let firstExt: string[][] | null = null;
for (const id of rack) {
if (used.has(id)) continue;
for (let i = 0; i < all.length; i++) {
const ext = extendSet(all[i]!, id);
if (!ext) continue;
if (!firstExt && i < base.length) firstExt = base.map((d, k) => (k === i ? { tileIds: ext.tileIds } : d));
if (!firstExt && i < base.length) firstExt = base.map((d, k) => (k === i ? ext.tileIds : d));
all[i] = ext;
used.add(id);
break;
}
}
if (all.length !== base.length || firstExt) acts.push({ type: 'setDraft', sets: all.map((d) => ({ tileIds: d.tileIds })) });
if (all.length !== base.length || firstExt) push(all.map((d) => d.tileIds), s.turnNo % 2 === 0);
// Rearrangement only: one rack tile added to an existing table set.
if (firstExt) acts.push({ type: 'setDraft', sets: firstExt });
if (firstExt) push(firstExt);
}
if (!acts.length || s.turnNo % 3 === 0) acts.push(drawAct);
// An unfinished try (single tile) now and then, to exercise invalid commit / timeout paths.
if (rack.length && s.turnNo % 7 === 0) acts.push({ type: 'setDraft', sets: [...base, { tileIds: [rack[0]!] }] });
if (rack.length && s.turnNo % 7 === 0) {
const cells = startCells(s);
const spot = freeSpot(cells, 1);
if (spot) acts.push({ type: 'arrange', cells: [...cells, { id: rack[0]!, ...spot }] });
}
return acts;
},
/** Hidden tiles of `player` (rack minus tiles already shown in a visible draft) plus the pool. */
/** Hidden tiles of `player` (rack minus tiles already shown on a visible working table) plus the pool. */
secretsOf(s, player) {
if (s.phase !== 'playing') return [...s.pool];
let rack = s.racks[player] ?? [];
if (s.options.showDraftToOthers && player === s.current) {
const shown = new Set(s.draft.sets.flatMap((d) => d.tileIds));
const shown = new Set(s.draft.cells.map((x) => x.id));
rack = rack.filter((id) => !shown.has(id));
}
return [...rack, ...s.pool];

View File

@@ -277,3 +277,134 @@ export function extendSet(set: Pick<NormalSet, 'tileIds' | 'kind' | 'jokerAs'>,
}
return cand ? normalizeSet({ tileIds: cand, as: set.kind }) : null;
}
// ---------------------------------------------------------------- table grid (§8.1)
/**
* The table is a grid like the app's: tiles side by side in a row (left to right) form one set, an empty cell ends
* it. 20 × 12 cells hold every possible table (106 tiles with the gaps; a 13-tile run fits in one row).
*/
export const BOARD_COLS = 20;
export const BOARD_ROWS = 12;
/** One tile on the grid. */
export interface Cell {
id: string;
r: number;
c: number;
}
/** A set on the grid: `tileIds` fill row `r` from column `c` to the right. */
export interface Strip {
tileIds: string[];
r: number;
c: number;
}
export const cellKey = (r: number, c: number): number => r * BOARD_COLS + c;
export const inBoard = (r: number, c: number): boolean => Number.isInteger(r) && Number.isInteger(c) && r >= 0 && r < BOARD_ROWS && c >= 0 && c < BOARD_COLS;
/** The sets on the grid, top row first, left to right; tile order = left to right. */
export function stripsOf(cells: readonly Cell[]): Strip[] {
const sorted = [...cells].sort((a, b) => a.r - b.r || a.c - b.c);
const out: Strip[] = [];
let cur: Strip | null = null;
for (const x of sorted) {
if (cur && cur.r === x.r && cur.c + cur.tileIds.length === x.c) cur.tileIds.push(x.id);
else {
cur = { tileIds: [x.id], r: x.r, c: x.c };
out.push(cur);
}
}
return out;
}
/** Cells of positioned sets. */
export function cellsOf(sets: readonly { tileIds: readonly string[]; r: number; c: number }[]): Cell[] {
return sets.flatMap((s) => s.tileIds.map((id, i) => ({ id, r: s.r, c: s.c + i })));
}
/** Order-insensitive key of exact positions (did anything move at all?). */
export function cellsKey(cells: readonly Cell[]): string {
return cells
.map((x) => `${x.id}@${x.r}.${x.c}`)
.sort()
.join(',');
}
/** Room for `n` tiles at (r, c): inside the grid, free, and an empty cell (or the edge) on both sides. */
function fits(taken: Set<number>, r: number, c: number, n: number): boolean {
if (r < 0 || r >= BOARD_ROWS || c < 0 || c + n > BOARD_COLS) return false;
for (let k = c - 1; k <= c + n; k++) if (k >= 0 && k < BOARD_COLS && taken.has(cellKey(r, k))) return false;
return true;
}
/** First free place for a set of `n` tiles (top row first), or null when the grid is full. */
export function freeSpot(cells: readonly Cell[], n: number): { r: number; c: number } | null {
const taken = new Set(cells.map((x) => cellKey(x.r, x.c)));
for (let r = 0; r < BOARD_ROWS; r++) for (let c = 0; c + n <= BOARD_COLS; c++) if (fits(taken, r, c, n)) return { r, c };
return null;
}
/**
* Positions for whole sets (computer players, legacy saves, test helpers). A set that keeps tiles of a positioned
* set in `prev` stays where those tiles were when there is room (so extending a run only adds tiles at its end);
* the rest go to the first free place. null when they do not fit.
*/
export function layoutSets(sets: readonly (readonly string[])[], prev: readonly Strip[] = []): Strip[] | null {
const where = new Map<string, { s: number; i: number }>();
prev.forEach((p, s) => p.tileIds.forEach((id, i) => where.set(id, { s, i })));
const taken = new Set<number>();
const out: (Strip | null)[] = sets.map(() => null);
const anchor = (ids: readonly string[]): { r: number; c: number; overlap: number } | null => {
const counts = new Map<number, number>();
for (const id of ids) {
const w = where.get(id);
if (w) counts.set(w.s, (counts.get(w.s) ?? 0) + 1);
}
let best = -1;
let overlap = 0;
for (const [s, n] of counts) if (n > overlap) [best, overlap] = [s, n];
if (best < 0) return null;
const k = ids.findIndex((id) => where.get(id)?.s === best);
const p = prev[best]!;
return { r: p.r, c: p.c + where.get(ids[k]!)!.i - k, overlap };
};
const anchored = sets.map((ids, i) => ({ i, a: anchor(ids) })).filter((x) => x.a).sort((x, y) => y.a!.overlap - x.a!.overlap);
for (const { i, a } of anchored) {
const n = sets[i]!.length;
if (!fits(taken, a!.r, a!.c, n)) continue;
out[i] = { tileIds: [...sets[i]!], r: a!.r, c: a!.c };
for (let k = 0; k < n; k++) taken.add(cellKey(a!.r, a!.c + k));
}
for (let i = 0; i < sets.length; i++) {
if (out[i]) continue;
const n = sets[i]!.length;
let spot: { r: number; c: number } | null = null;
for (let r = 0; r < BOARD_ROWS && !spot; r++) for (let c = 0; c + n <= BOARD_COLS && !spot; c++) if (fits(taken, r, c, n)) spot = { r, c };
if (!spot) return null;
out[i] = { tileIds: [...sets[i]!], ...spot };
for (let k = 0; k < n; k++) taken.add(cellKey(spot.r, spot.c + k));
}
return out as Strip[];
}
/**
* Drops `ids` (in this order, left to right) so the first one lands on (r, c) — the drag-and-drop / tap placement.
* Other tiles in the way are pushed right together with everything right of them in that row (inserting into a
* set). Tiles that are not in `cells` yet come from the rack. null when the row has no room.
*/
export function placeTiles(cells: readonly Cell[], ids: readonly string[], r: number, c: number): Cell[] | null {
const n = ids.length;
if (n === 0 || n > BOARD_COLS || r < 0 || r >= BOARD_ROWS) return null;
const moving = new Set(ids);
let rest = cells.filter((x) => !moving.has(x.id));
const c0 = Math.max(0, Math.min(c, BOARD_COLS - n));
const blocked = rest.some((x) => x.r === r && x.c >= c0 && x.c < c0 + n);
if (blocked) {
const right = rest.filter((x) => x.r === r && x.c >= c0);
if (right.some((x) => x.c + n >= BOARD_COLS)) return null;
rest = rest.map((x) => (x.r === r && x.c >= c0 ? { ...x, c: x.c + n } : x));
}
return [...rest, ...ids.map((id, i) => ({ id, r, c: c0 + i }))];
}

View File

@@ -2,14 +2,20 @@ import { describe, expect, test } from 'bun:test';
import { SeededRng, playoutSeeds, randomPlayout, seedN, type GameEvent, type PlayerId } from '@bg/engine';
import {
ALL_TILE_IDS,
BOARD_COLS,
BOARD_ROWS,
cellsOf,
findMeld,
layoutSets,
normalizeSet,
placeTiles,
rummikub,
scoreRound,
setProblem,
sortTiles,
stripsOf,
tileCount,
type DraftSet,
type Cell,
type RummikubAction,
type RummikubOptions,
type RummikubState,
@@ -26,8 +32,8 @@ function mk(opts: Partial<RummikubOptions> = {}, players = ['A', 'B'], seed = 1)
}
/**
* 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.
* Puts the game into a hand-made position: given racks and table sets (laid out on the grid), everything else goes
* to the pool (in id order), `current` has the turn with a fresh working table.
*/
function rig(
s: RummikubState,
@@ -36,10 +42,11 @@ function rig(
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] ?? [])]]));
const strips = layoutSets(table)!;
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 };
return { id: `s${i + 1}`, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs, r: strips[i]!.r, c: strips[i]!.c };
});
s.nextSetId = table.length + 1;
const rest = ALL_TILE_IDS.filter((id) => !used.has(id));
@@ -51,7 +58,7 @@ function rig(
}
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.draft = { cells: cellsOf(s.table), edits: 0 };
s.consecutivePasses = 0;
expect(tileCount(s)).toBe(106);
return s;
@@ -61,6 +68,8 @@ 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 parsed = rummikub.actionSchema.safeParse(a);
if (!parsed.success && a.type !== 'timeout' && a.type !== 'leave') throw new Error(`schema rejects ${JSON.stringify(a)}`);
const v = rummikub.validate(s, who, a);
if (!v.ok) throw new Error(`${who} ${JSON.stringify(a)} rejected: ${v.reason}`);
clock += 1000;
@@ -73,10 +82,13 @@ function reason(s: RummikubState, who: PlayerId, a: RummikubAction): string {
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] }));
/** Grid cells for whole sets: table sets keep their places, new ones go to the first free place. */
const lay = (s: RummikubState, sets: string[][]): Cell[] => cellsOf(layoutSets(sets, s.table)!);
const tableSets = (s: RummikubState): string[][] => s.table.map((t) => [...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' });
const arrange = (s: RummikubState, who: PlayerId, sets: string[][]) => act(s, who, { type: 'arrange', cells: lay(s, sets) });
/** Lays the sets out and commits in one go. */
const play = (s: RummikubState, who: PlayerId, sets: string[][]) => act(arrange(s, who, sets), who, { type: 'commit' });
// ---------------------------------------------------------------- setup
@@ -101,6 +113,7 @@ describe('셋업 (§4)', () => {
expect(tileCount(s)).toBe(106);
expect(new Set([...s.pool, ...Object.values(s.racks).flat()]).size).toBe(106);
expect(s.table).toEqual([]);
expect(s.draft).toEqual({ cells: [], edits: 0 });
});
test('same seed → same deal and first player; the opening draw picks the highest number', () => {
@@ -178,12 +191,66 @@ describe('세트 판정 (§5.1)', () => {
});
});
// ---------------------------------------------------------------- grid
describe('바닥 칸 (§8.1)', () => {
test('tiles side by side in a row are one set; an empty cell or a new row starts another', () => {
const cells: Cell[] = [
{ id: 'R5a', r: 0, c: 3 },
{ id: 'R3a', r: 0, c: 1 },
{ id: 'R4a', r: 0, c: 2 },
{ id: 'K7a', r: 0, c: 5 },
{ id: 'B7a', r: 1, c: 0 },
];
expect(stripsOf(cells)).toEqual([
{ tileIds: ['R3a', 'R4a', 'R5a'], r: 0, c: 1 },
{ tileIds: ['K7a'], r: 0, c: 5 },
{ tileIds: ['B7a'], r: 1, c: 0 },
]);
});
test('placeTiles: drop on an empty cell, next to a set (joins it), or onto a tile (pushes the rest of the row right)', () => {
const run: Cell[] = cellsOf([{ tileIds: ['R4a', 'R5a', 'R6a'], r: 0, c: 0 }, { tileIds: ['K9a', 'B9a', 'O9a'], r: 0, c: 5 }]);
// Next to the run: it becomes R4-R7.
expect(stripsOf(placeTiles(run, ['R7a'], 0, 3)!)[0]).toEqual({ tileIds: ['R4a', 'R5a', 'R6a', 'R7a'], r: 0, c: 0 });
// Onto R6: R6 and everything right of it moves one cell right (inserting).
const ins = placeTiles(run, ['JK1'], 0, 2)!;
expect(stripsOf(ins).map((x) => x.tileIds)).toEqual([['R4a', 'R5a', 'JK1', 'R6a'], ['K9a', 'B9a', 'O9a']]);
expect(ins.find((x) => x.id === 'K9a')).toEqual({ id: 'K9a', r: 0, c: 6 });
// Several tiles keep their order; near the right edge they are pulled back inside.
expect(placeTiles([], ['B1a', 'B2a', 'B3a'], 2, BOARD_COLS - 1)).toEqual([
{ id: 'B1a', r: 2, c: BOARD_COLS - 3 },
{ id: 'B2a', r: 2, c: BOARD_COLS - 2 },
{ id: 'B3a', r: 2, c: BOARD_COLS - 1 },
]);
// Moving a tile within the board: it leaves its old cell.
const moved = placeTiles(run, ['R6a'], 3, 0)!;
expect(moved.filter((x) => x.id === 'R6a')).toEqual([{ id: 'R6a', r: 3, c: 0 }]);
// No room to push: null.
const full = cellsOf([{ tileIds: Array.from({ length: 13 }, (_, i) => `O${i + 1}a`), r: 0, c: BOARD_COLS - 13 }]);
expect(placeTiles(full, ['K1a'], 0, BOARD_COLS - 13)).toBeNull();
expect(placeTiles(full, ['K1a'], BOARD_ROWS, 0)).toBeNull();
});
test('layoutSets keeps sets in place, extends at the ends, puts new sets in free places with a gap', () => {
const prev = [{ tileIds: ['R5a', 'R6a', 'R7a'], r: 0, c: 4 }];
const out = layoutSets([['R4a', 'R5a', 'R6a', 'R7a'], ['K1a', 'K2a', 'K3a']], prev)!;
expect(out[0]).toEqual({ tileIds: ['R4a', 'R5a', 'R6a', 'R7a'], r: 0, c: 3 });
expect(out[1]).toEqual({ tileIds: ['K1a', 'K2a', 'K3a'], r: 0, c: 8 });
// Every possible table fits: 35 sets of three and ten runs of ten.
const threes = Array.from({ length: 35 }, (_, i) => [`a${i}`, `b${i}`, `c${i}`]);
expect(layoutSets(threes)).not.toBeNull();
const tens = Array.from({ length: 10 }, (_, i) => Array.from({ length: 10 }, (_, k) => `t${i}-${k}`));
expect(layoutSets(tens)).not.toBeNull();
});
});
// ---------------------------------------------------------------- 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'] }] });
s = arrange(s, 'B', [['B1a', 'B2a', 'B3a'], ['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' });
@@ -193,30 +260,36 @@ describe('첫 등록 (§5.3)', () => {
expect(s.racks.A).toEqual(['K5a']);
});
test('joker position decides the first meld: [조커, 검정9, 검정10] = 27 refused, [검정9, 검정10, 조커] = 30 accepted', () => {
test('joker position on the grid 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'] }] });
s = arrange(s, 'A', [['JK1', 'K9a', 'K10a']]);
expect(reason(s, 'A', { type: 'commit' })).toBe('첫 등록은 30점 이상이어야 해요 (지금 27점).');
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K9a', 'K10a', 'JK1'] }] });
s = arrange(s, 'A', [['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('첫 등록 전에는 바닥의 타일을 옮길 수 없어요.');
test('before the first meld: table tiles cannot move (arrange), and nothing may be added next to a table set (commit)', () => {
const s = rig(mk(), { racks: { A: ['R8a', 'K10a', 'B10a', 'O10a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a']], melded: ['B'] });
// Splitting the table run (moving R6, R7 away).
const split = placeTiles(s.draft.cells, ['R6a', 'R7a'], 2, 0)!;
expect(reason(s, 'A', { type: 'arrange', cells: split })).toBe('첫 등록 전에는 바닥의 타일을 옮길 수 없어요.');
// R8 right after the table run is fine while working, but cannot be committed, even with 30 points elsewhere.
let t = act(s, 'A', { type: 'arrange', cells: placeTiles(s.draft.cells, ['R8a'], 0, 4)! });
t = act(t, 'A', { type: 'arrange', cells: placeTiles(t.draft.cells, ['K10a', 'B10a', 'O10a'], 3, 0)! });
expect(reason(t, 'A', { type: 'commit' })).toBe('첫 등록 전에는 바닥 묶음에 붙일 수 없어요. 한 칸 띄워 따로 놓아 주세요.');
const v = rummikub.view(t, 'A');
expect(v.my!.check!.invalidIdx.map((i) => v.draft!.groups[i]!.tileIds)).toEqual([['R4a', 'R5a', 'R6a', 'R7a', 'R8a']]);
// 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);
const u = play(s, 'A', [['R4a', 'R5a', 'R6a', 'R7a'], ['K10a', 'B10a', 'O10a']]);
expect(u.hasMelded.A).toBe(true);
expect(u.table.find((x) => x.tileIds.includes('R4a'))).toMatchObject({ r: s.table[0]!.r, c: s.table[0]!.c });
});
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'] }] });
s = arrange(s, 'A', [['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([]);
@@ -241,6 +314,24 @@ describe('재배치와 조커 회수 (§5.4, §5.5)', () => {
expect(s.lastChanged.sort()).toEqual(['s1', 's2']);
});
test('the same split by dragging: R6 dropped onto R7 pushes R7-R8 right, then a gap is opened', () => {
let s = rig(mk(), { racks: { A: ['R6b', 'K1a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a', 'R8a']], melded: ['A'] });
const { r, c } = s.table[0]!;
// Drop R6b onto R7 → R4 R5 R6 R6b R7 R8; then move R6b R7 R8 one more to the right → R4 R5 R6 _ R6b R7 R8.
s = act(s, 'A', { type: 'arrange', cells: placeTiles(s.draft.cells, ['R6b'], r, c + 3)! });
expect(rummikub.view(s, 'A').draft!.groups.map((g) => g.ok)).toEqual([false]);
s = act(s, 'A', { type: 'arrange', cells: placeTiles(s.draft.cells, ['R6b', 'R7a', 'R8a'], r, c + 4)! });
expect(rummikub.view(s, 'A').draft!.groups.map((g) => g.tileIds)).toEqual([
['R4a', 'R5a', 'R6a'],
['R6b', 'R7a', 'R8a'],
]);
s = act(s, 'A', { type: 'commit' });
expect(s.table.map((t) => [t.c - c, t.tileIds.length])).toEqual([
[0, 3],
[4, 3],
]);
});
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'] },
@@ -252,77 +343,96 @@ describe('재배치와 조커 회수 (§5.4, §5.5)', () => {
expect(s.table).toHaveLength(4);
});
test('joker retrieval: [파랑5, 조커, 파랑7] + [파랑6, 검정3, 빨강3] → [파랑5,6,7] [검정3, 빨강3, 조커]', () => {
test('joker retrieval (§5.5): [파랑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('바닥의 타일은 내 받침대로 가져올 수 없어요.');
// Taking the joker back to the rack is refused (it must be used again on the table this turn).
const noJoker = lay(s, [['B5a', 'B6a', 'B7a']]);
expect(reason(s, 'A', { type: 'arrange', cells: noJoker })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
expect(reason(s, 'A', { type: 'commit', cells: noJoker })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
// The joker left on its own is not a valid set either.
const lonely = act(s, 'A', { type: 'arrange', cells: [...lay(s, [['B5a', 'B6a', 'B7a']]), { id: 'JK1', r: 5, c: 0 }] });
expect(reason(lonely, 'A', { type: 'commit' })).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('joker retrieval needs the first meld: before it, the joker cannot be moved at all', () => {
const s = rig(mk(), { racks: { A: ['B6a', 'R10a', 'R11a', 'R12a'], B: ['B1a'] }, table: [['B5a', 'JK1', 'B7a']], melded: ['B'] });
expect(reason(s, 'A', { type: 'arrange', cells: lay(s, [['B5a', 'B6a', 'B7a'], ['R10a', 'R11a', 'R12a', 'JK1']]) })).toBe('첫 등록 전에는 바닥의 타일을 옮길 수 없어요.');
});
test('cheating attempts: foreign tiles, duplicates, table tiles into the rack, empty sets', () => {
test('rearranging without a rack tile is refused; leftover single tiles are refused (and highlighted)', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a', 'R8a', 'R9a']], melded: ['A'] });
s = arrange(s, 'A', [['R4a', 'R5a', 'R6a'], ['R7a', 'R8a', 'R9a']]);
expect(reason(s, 'A', { type: 'commit' })).toBe('받침대에서 타일을 1개 이상 내야 해요.');
s = arrange(s, 'A', [['R4a', 'R5a', 'R6a'], ['R7a', 'R8a', 'R9a'], ['K1a', 'K2a']]);
expect(reason(s, 'A', { type: 'commit' })).toBe('빨간 표시된 묶음을 고쳐 주세요.');
const v = rummikub.view(s, 'A');
const bad = v.my!.check!.invalidIdx;
expect(bad).toHaveLength(1);
expect(v.draft!.groups[bad[0]!]).toMatchObject({ ok: false, problem: '3장 이상이어야 해요', tileIds: ['K1a', 'K2a'] });
});
test('cheating attempts: foreign tiles, duplicates, two tiles on one cell, off the grid, table tiles into the rack', () => {
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('지금은 내 차례가 아니에요.');
const with_ = (cells: Cell[]) => ({ type: 'arrange' as const, cells: [...s.draft.cells, ...cells] });
expect(reason(s, 'A', { type: 'arrange', cells: lay(s, [...base, ['B1a', 'B2a', 'B3a']]) })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', { type: 'arrange', cells: lay(s, [...base, ['O9a', 'O10a', 'O11a']]) })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', with_([{ id: 'XX1', r: 5, c: 0 }]))).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', with_([{ id: 'K1a', r: 5, c: 0 }, { id: 'K1a', r: 5, c: 1 }]))).toBe('같은 타일이 두 번 들어 있어요.');
expect(reason(s, 'A', with_([{ id: 'K1a', r: 5, c: 0 }, { id: 'K2a', r: 5, c: 0 }]))).toBe('한 칸에 타일 두 개를 놓을 수 없어요.');
expect(reason(s, 'A', with_([{ id: 'K1a', r: BOARD_ROWS, c: 0 }]))).toBe('바닥 밖에는 놓을 수 없어요.');
expect(rummikub.actionSchema.safeParse(with_([{ id: 'K1a', r: 0, c: BOARD_COLS }])).success).toBe(false);
expect(rummikub.actionSchema.safeParse(with_([{ id: 'K1a', r: 0.5, c: 1 }])).success).toBe(false);
expect(reason(s, 'A', { type: 'arrange', cells: s.draft.cells.slice(1) })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
// The same checks guard a commit that carries its own cells.
expect(reason(s, 'A', { type: 'commit', cells: lay(s, [...base, ['B1a', 'B2a', 'B3a']]) })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'B', { type: 'arrange', cells: s.draft.cells })).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']]);
const t = play(s, 'A', [...base, ['K1a', 'K2a', 'K3a']]);
expect(t.racks.A).toEqual([]);
});
});
// ---------------------------------------------------------------- draft / undo
// ---------------------------------------------------------------- working table / commit
describe('초안과 되돌리기 (§5.6)', () => {
test('5 setDraft → 2 undo → the 3rd draft; reset → turn start; survives a save/reload', () => {
describe('놓아 보기와 완료 (§5.6)', () => {
test('arrange replaces the working table; resetDraft puts it back; it 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 start = s.draft.cells;
for (let k = 1; k <= 5; k++) s = arrange(s, 'A', [...tableSets(s), ['K1a', 'K2a', 'K3a', 'K4a', 'K5a'].slice(0, k)]);
expect(s.draft.edits).toBe(5);
expect(rummikub.view(s, 'A').my!.changed).toBe(true);
// Reconnect = the persisted state is reloaded; the working table 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));
expect(rummikub.view(reloaded, 'A').draft!.cells).toEqual(s.draft.cells);
s = act(s, 'A', { type: 'resetDraft' });
expect(s.draft.sets.map((d) => d.tileIds)).toEqual(base.map((d) => d.tileIds));
expect(s.draft.cells).toEqual(start);
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('되돌릴 것이 없어요.');
// Moving a whole table set somewhere else is a change you can reset, but not a play.
s = act(s, 'A', { type: 'arrange', cells: placeTiles(s.draft.cells, ['R4a', 'R5a', 'R6a'], 6, 2)! });
expect(rummikub.view(s, 'A').my!.changed).toBe(true);
expect(reason(s, 'A', { type: 'commit' })).toBe('받침대에서 타일을 1개 이상 내야 해요.');
});
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('commit with cells: put down and checked in one step; the table keeps the grid places', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'R1a'], B: ['B1a'] }, melded: ['A'] });
const cells = cellsOf([{ tileIds: ['K3a', 'K1a', 'K2a'], r: 4, c: 7 }]);
s = act(s, 'A', { type: 'commit', cells, turn: s.turnNo });
// Runs are written ascending in their strip.
expect(s.table).toEqual([{ id: 's1', tileIds: ['K1a', 'K2a', 'K3a'], kind: 'run', jokerAs: {}, r: 4, c: 7 }]);
expect(s.current).toBe('B');
// The next player's working table starts from the committed grid.
expect(s.draft.cells).toEqual(cellsOf(s.table));
});
test('draw with a changed draft throws the draft away and draws one', () => {
test('draw with a changed working table throws it 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 = arrange(s, 'A', [['K1a', 'K2a', 'K3a']]);
s = act(s, 'A', { type: 'draw' });
expect(s.table).toEqual([]);
expect(s.racks.A).toHaveLength(4);
@@ -332,7 +442,7 @@ describe('초안과 되돌리기 (§5.6)', () => {
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 = arrange(s, 'A', [['K1a', 'K2a']]);
s = act(s, 'A', { type: 'commit' });
expect(s.table).toEqual([]);
expect(s.racks.A).toHaveLength(5);
@@ -364,49 +474,59 @@ describe('시간 초과 (§5.7, §8.5)', () => {
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', () => {
test('app rule (default): even a valid table goes back, the rack is restored and 1 tile is drawn', () => {
let s = pos();
const rackBefore = [...s.racks.A!];
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a'] }, { tileIds: ['R6a', 'K1a'] }] });
const tableBefore = s.table;
s = arrange(s, 'A', [...tableSets(s), ['K1a', 'K2a', 'K3a']]);
expect(rummikub.view(s, 'A').my!.check!.ok).toBe(true);
s = act(s, 'A', { type: 'timeout' });
expect(s.table).toEqual(tableBefore);
expect(s.racks.A!.slice(0, 4)).toEqual(rackBefore);
expect(s.racks.A).toHaveLength(5);
expect(s.log.at(-1)).toMatchObject({ by: 'A', kind: 'timeoutDraw', count: 1 });
expect(s.current).toBe('B');
});
test('app rule (default): an unfinished table goes back and 1 tile is drawn', () => {
let s = pos();
s = arrange(s, 'A', [['R4a', 'R5a'], ['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');
expect(s.racks.A).toHaveLength(5);
expect(s.lastDrawn.A).toHaveLength(1);
});
let t = pos({}, ['O13a', 'O13b']);
t = act(t, 'A', { type: 'setDraft', sets: [...tableSets(t), { tileIds: ['K1a'] }] });
test('rulebook options: valid table auto-committed; unfinished table → 3 tiles (only 2 in the pool → 2)', () => {
let c = pos({ timeoutValidDraft: 'commit' });
c = arrange(c, 'A', [...tableSets(c), ['K1a', 'K2a', 'K3a']]);
c = act(c, 'A', { type: 'timeout' });
expect(setsOf(c)).toEqual([['R4a', 'R5a', 'R6a'], ['K1a', 'K2a', 'K3a']]);
expect(c.racks.A).toEqual(['O9a']);
expect(c.log.at(-1)).toMatchObject({ kind: 'timeoutCommit', count: 3 });
let s = pos({ invalidTimeoutPenalty: 3 });
s = arrange(s, 'A', [['R4a', 'R5a'], ['R6a', 'K1a']]);
s = act(s, 'A', { type: 'timeout' });
expect(setsOf(s)).toEqual([['R4a', 'R5a', 'R6a']]);
expect(s.racks.A).toHaveLength(7);
expect(s.log.at(-1)).toMatchObject({ kind: 'penalty', count: 3 });
let t = pos({ invalidTimeoutPenalty: 3 }, ['O13a', 'O13b']);
t = arrange(t, 'A', [...tableSets(t), ['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();
test('nothing changed (or only moved around): draw 1, no penalty', () => {
let u = pos({ invalidTimeoutPenalty: 3 });
u = act(u, 'A', { type: 'arrange', cells: placeTiles(u.draft.cells, ['R4a', 'R5a', 'R6a'], 5, 5)! });
u = act(u, 'A', { type: 'timeout' });
expect(u.racks.A).toHaveLength(5);
expect(u.log.at(-1)).toMatchObject({ kind: 'timeoutDraw', count: 1 });
// The moved set went back to its place.
expect(u.table[0]).toMatchObject({ r: 0, c: 0 });
});
test('3 timeouts in a row → away: the deadline becomes short; acting again resets it', () => {
@@ -437,6 +557,11 @@ describe('시간 초과 (§5.7, §8.5)', () => {
s = act(s, s.current, { type: 'draw' });
expect(rummikub.deadline!(s)).toBeNull();
});
test('30-second turns', () => {
const s = mk({ turnSeconds: 30 });
expect(rummikub.deadline!(s)).toBe(s.turnStartedAt + 30_000);
});
});
// ---------------------------------------------------------------- scoring / end
@@ -562,29 +687,58 @@ describe('나가기', () => {
// ---------------------------------------------------------------- information
describe('정보 공개 (§8.3)', () => {
test('opponents and spectators see counts only; the draft is hidden unless showDraftToOthers', () => {
test('default (app): everybody sees the working table live — only the tiles put on it, never the rest of the rack', () => {
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'] }] });
s = act(s, 'A', { type: 'arrange', cells: [...s.draft.cells, { id: 'K1a', r: 2, c: 3 }] });
for (const viewer of ['B', null]) {
const v = rummikub.view(s, viewer);
expect(v.draft!.cells).toContainEqual({ id: 'K1a', r: 2, c: 3 });
expect(v.draft!.groups.find((g) => g.tileIds.includes('K1a'))).toMatchObject({ ok: false, r: 2, c: 3 });
expect(v.draftEdits).toBe(1);
expect(v.my?.check ?? null).toBeNull();
const json = JSON.stringify(v);
for (const id of ['K2a', 'K3a', 'O7a', ...s.pool, ...(viewer ? [] : s.racks.B!)]) expect(json.includes(`"${id}"`)).toBe(false);
expect(v.seats.find((x) => x.id === 'A')!.tiles).toBe(4);
}
// Put back on the rack → gone from everybody's view again.
s = act(s, 'A', { type: 'arrange', cells: cellsOf(s.table) });
expect(JSON.stringify(rummikub.view(s, 'B')).includes('"K1a"')).toBe(false);
expect(rummikub.secretsOf!(s, 'A')).toContain('K1a');
});
test('showDraftToOthers=false: opponents and spectators see counts and "thinking" only', () => {
let s = rig(mk({ showDraftToOthers: false }), { racks: { A: ['K1a', 'K2a', 'K3a', 'O7a'], B: ['B1a', 'B9b'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A'] });
s = arrange(s, 'A', [...tableSets(s), ['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.draft!.groups.map((d) => d.ok)).toEqual([true, true]);
expect(own.my!.check).toMatchObject({ ok: true, fromRack: 3 });
expect(rummikub.secretsOf!(s, 'A')).toContain('K1a');
});
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('drag preview (stream): public event, tiles still on the rack are hidden; nothing changes in the state', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'O7a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A'] });
s = act(s, 'A', { type: 'arrange', cells: [...s.draft.cells, { id: 'K1a', r: 2, c: 0 }] });
expect(rummikub.isStreamAction!({ type: 'drag', ids: ['K1a'], x: 1, y: 1 })).toBe(true);
expect(rummikub.isStreamAction!({ type: 'arrange', cells: [] })).toBe(false);
const a: RummikubAction = { type: 'drag', ids: ['R4a', 'K1a', 'O7a', 'B1a'], x: 3.5, y: 2.25, turn: s.turnNo };
const out = actE(s, 'A', a);
expect(out.state).toBe(s);
expect(out.events).toEqual([{ type: 'drag', player: 'A', turn: s.turnNo, tiles: ['R4a', 'K1a', null], x: 3.5, y: 2.25 }]);
// Somebody else's / a late drag is dropped silently (no error toast), and nothing is sent with the option off.
expect(actE(s, 'B', a).events).toEqual([]);
expect(actE(s, 'A', { ...a, turn: s.turnNo - 1 }).events).toEqual([]);
const off = rig(mk({ showDraftToOthers: false }), { racks: { A: ['K1a'], B: ['B1a'] }, melded: ['A'] });
expect(actE(off, 'A', { type: 'drag', ids: ['K1a'], x: 0, y: 0 }).events).toEqual([]);
expect(rummikub.actionSchema.safeParse({ type: 'drag', ids: ['K1a'], x: 999, y: 0 }).success).toBe(false);
});
test('draw events carry no tile; only the drawer sees the new tile', () => {
@@ -612,38 +766,63 @@ describe('정보 공개 (§8.3)', () => {
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'] }] });
s = arrange(s, 'A', [['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)', () => {
test('an arrange 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;
const cells = [{ id: 'K1a', r: 0, c: 0 }];
s = act(s, 'A', { type: 'draw' });
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a'] }], turn })).toBe('지금은 내 차례가 아니에요.');
expect(reason(s, 'A', { type: 'arrange', cells, 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);
expect(reason(s, 'A', { type: 'arrange', cells, turn })).toBe('지난 차례의 요청이라 무시했어요.');
expect(rummikub.validate(s, 'A', { type: 'arrange', cells, turn: s.turnNo }).ok).toBe(true);
});
});
// ---------------------------------------------------------------- saves from before the grid
describe('예전 저장 (stateVersion 1)', () => {
test('a v1 game in progress gets grid places for the table and the working table, and plays on', () => {
const s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'R1a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a'], ['B9a', 'K9a', 'O9a']], melded: ['A'] });
const old = JSON.parse(JSON.stringify(s)) as Record<string, any>;
old.table = old.table.map(({ r: _r, c: _c, ...t }: Record<string, unknown>) => t);
old.draft = { sets: [{ tileIds: ['R4a', 'R5a', 'R6a'], as: 'run' }, { tileIds: ['B9a', 'K9a', 'O9a'] }, { tileIds: ['K1a', 'K2a', 'K3a'] }], history: [[]], edits: 2 };
delete old.options.showDraftToOthers;
const m = rummikub.migrate!(old, 1);
expect(m.table.map((t) => [t.r, t.c])).toEqual([
[0, 0],
[0, 4],
]);
expect(stripsOf(m.draft.cells).map((x) => x.tileIds)).toEqual([['R4a', 'R5a', 'R6a'], ['B9a', 'K9a', 'O9a'], ['K1a', 'K2a', 'K3a']]);
expect(m.draft.edits).toBe(2);
expect(m.options.showDraftToOthers).toBe(true);
expect(rummikub.view(m, 'B').draft!.groups).toHaveLength(3);
const t = act(m, 'A', { type: 'commit' });
expect(t.racks.A).toEqual(['R1a']);
expect(rummikub.migrate!(t, 2)).toBe(t);
});
});
// ---------------------------------------------------------------- options / hints
describe('옵션과 힌트', () => {
test('every option has a Korean title; defaults follow the doc', () => {
test('every option has a Korean title; defaults follow the app', () => {
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,
timeoutValidDraft: 'revert',
invalidTimeoutPenalty: 1,
invalidCommitPenalty: 'reject',
jokerPenalty: 30,
initialMeldAllowExtend: false,
showDraftToOthers: false,
showDraftToOthers: true,
gamesPerMatch: '1',
hints: true,
});
@@ -661,9 +840,9 @@ describe('옵션과 힌트', () => {
const CONFIGS: Partial<RummikubOptions>[] = [
{},
{ initialMeldPoints: 0, showDraftToOthers: true },
{ initialMeldPoints: 0, showDraftToOthers: false },
{ initialMeldPoints: 50, invalidCommitPenalty: 'penalty3', jokerPenalty: 50 },
{ timeoutValidDraft: 'revert', invalidTimeoutPenalty: 1, initialMeldAllowExtend: true },
{ timeoutValidDraft: 'commit', invalidTimeoutPenalty: 3, initialMeldAllowExtend: true },
{ gamesPerMatch: '2', initialMeldPoints: 20 },
];
@@ -673,11 +852,13 @@ 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).
// The committed table is always made of valid sets that are apart on the grid (checked once per turn).
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}`);
const strips = stripsOf(cellsOf(s.table));
if (strips.length !== s.table.length) throw new Error('table sets touch on the grid');
}
describe('random playouts (docs/09 §7)', () => {