윷놀이 지역 룰 옵션: 말 없을 때 빽도(버림·다시 던지기·날윷), 낙이면 차례 끝, 던진 순서대로, 업기 고르기, 갈림길 고르기

- 엔진: 새 옵션 5개(기본값은 예전 동작 그대로), MOVE에 piece·alt·stack(선택), 따로 선 무더기는 Piece.group으로 구분
- 컴퓨터: 다른 길·따로 두기·날윷 빽도를 점수로 판단, 따로 선 말도 함께 잡힐 위험으로 계산
- 화면: 방 설정 "지역 룰(우리 동네 규칙)" 묶음(빽도/말 움직이기/던지기, 고른 값 설명, 기본으로 되돌리기), 로비 요약·규칙 보기·도움말에 적용 중인 룰, 게임 중 갈 길 고르기·업기/따로 두기 버튼
- 문서: docs/games/yut.md 2장 표, 7장(추가한 룰·뺀 룰과 이유), 테스트·E2E 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 03:33:12 +09:00
parent 71381087cc
commit 89312e28f2
11 changed files with 1013 additions and 137 deletions

View File

@@ -23,14 +23,21 @@ export const THROW_KO: Record<Throw, string> = { do: '도', gae: '개', geol: '
/** Display order of the result chips. */
export const THROW_ORDER: Throw[] = ['backdo', 'do', 'gae', 'geol', 'yut', 'mo'];
/** Nodes where a piece that stopped there has two roads ahead: 모, 뒷모, 방. */
export const FORKS: readonly NodeId[] = [5, 10, 22];
export const isFork = (n: NodeId | 'home'): boolean => n === 5 || n === 10 || n === 22;
/**
* One step forward (§5.2 table). `starting` = this step leaves the node the piece stood on,
* `prev` = the node passed just before `node` within the same move (only matters at 방).
* `alt` (지역 룰 `forkRule = choose`): when starting on a fork, take the other road — 모/뒷모 keep to the outer ring,
* 방 goes on toward 찌모 (23).
* Returns GOAL when the piece leaves 참먹이 after a lap.
*/
export function step(node: NodeId | 'home', starting: boolean, prev: NodeId | null): NodeId | typeof GOAL {
export function step(node: NodeId | 'home', starting: boolean, prev: NodeId | null, alt = false): NodeId | typeof GOAL {
if (node === 'home') return 1;
if (node === 0) return GOAL;
if (starting && alt && isFork(node)) return node === 22 ? 23 : node + 1;
if (starting) {
if (node === 5) return 20;
if (node === 10) return 25;
@@ -61,14 +68,15 @@ export interface Advance {
/**
* Moves `n` (≥ 1) steps forward from `from`. Reaching GOAL drops the remaining steps.
* `alt`: take the other road at the starting fork (see `step`).
* With `reach`, arriving at 참먹이 after a lap (always the case when entering 0 by moving forward) finishes at once.
*/
export function advance(from: NodeId | 'home', n: number, finishRule: 'pass' | 'reach'): Advance {
export function advance(from: NodeId | 'home', n: number, finishRule: 'pass' | 'reach', alt = false): Advance {
let cur: NodeId | 'home' = from;
let prev: NodeId | null = null;
const path: NodeId[] = [];
for (let i = 0; i < n; i++) {
const nxt = step(cur, i === 0, prev);
const nxt = step(cur, i === 0, prev, alt && i === 0);
if (nxt === GOAL) return { path, to: GOAL };
path.push(nxt);
prev = cur === 'home' ? null : cur;

View File

@@ -51,6 +51,37 @@ describe('yut bot', () => {
expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 0, from: 7 });
});
test('지역 룰 forkRule = choose: takes the other road from 모 when it catches an enemy there', () => {
const s = moving(['gae'], { forkRule: 'choose' });
put(s, 0, 0, 5, [1, 2, 3, 4, 5]);
put(s, 1, 0, 7, [6, 7]);
expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 0, from: 5, alt: true });
// Nothing to catch: the shortcut is better.
const t = moving(['gae'], { forkRule: 'choose' });
put(t, 0, 0, 5, [1, 2, 3, 4, 5]);
expect(decide(t)).toEqual({ type: 'MOVE', throwIndex: 0, from: 5 });
});
test('지역 룰 stacking = choose: stacks when it may, and moves stacks standing apart one by one', () => {
const s = moving(['geol'], { stacking: 'choose' });
put(s, 0, 0, 3, [1, 2, 3]);
put(s, 1, 0, 15, [15]);
expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 0, from: 'home' });
const a = moving(['gae'], { stacking: 'choose' });
put(a, 0, 0, 3, [1, 2, 3]);
put(a, 0, 1, 3, [2, 3]);
a.sides[0]!.pieces[1]!.group = 1;
put(a, 1, 0, 5, [1, 2, 3, 4, 5]);
const d = decide(a) as { type: string; from: unknown; piece?: number };
// Either stack on 3 catches the enemy on 5; the action names which one.
expect([d.type, d.from, typeof d.piece]).toEqual(['MOVE', 3, 'number']);
});
test('지역 룰 backdoNoPiece = enter: puts a new piece on 날윷 with 빽도 instead of crawling in with 개', () => {
const s = moving(['gae', 'backdo'], { backdoNoPiece: 'enter' });
expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 1, from: 'home' });
});
test('beats a random player clearly in 1-on-1', () => {
let wins = 0;
const games = 20;
@@ -75,6 +106,9 @@ describe('yut bot', () => {
[{ mode: 'team' as const, pieces: 2 as const }, 6],
[{ finishRule: 'reach' as const, backdoFromDo: 'finish' as const, nakPercent: 10 as const, stickModel: 'fair' as const }, 3],
[{ ranking: 'all' as const, backdo: false }, 4],
[{ stacking: 'choose' as const, forkRule: 'choose' as const, backdoNoPiece: 'enter' as const }, 2],
[{ useOrder: 'thrown' as const, backdoNoPiece: 'rethrow' as const, nakPercent: 10 as const, nakRule: 'lose' as const }, 3],
[{ mode: 'team' as const, stacking: 'choose' as const, forkRule: 'choose' as const, useOrder: 'thrown' as const }, 4],
] as const) {
test(`option mode ${JSON.stringify(opts)} with ${n} players finishes`, () => {
const options = yut.optionsSchema.parse(opts);

View File

@@ -25,6 +25,8 @@ export const yutBot: BotStrategy<YutView, YutAction> = ({ view, legal, random })
const live = new Set(view.sides.filter((x) => x.id !== me && !x.out && x.finishedRank === null).map((x) => x.id));
const enemyStacks = view.stacks.filter((st) => live.has(st.side));
const enemyHome = view.sides.some((x) => live.has(x.id) && x.home > 0);
// 지역 룰 backdoNoPiece = enter: an enemy with nothing on the board may put a piece on 날윷(19) with 빽도.
const enemyBackdoEnter = o.backdo && o.backdoNoPiece === 'enter' && view.sides.some((x) => live.has(x.id) && x.home > 0 && x.onBoard === 0);
/** Chance that some enemy can land on `node` with its next throw (bonus throws ignored). */
const risk = (node: NodeId): number => {
@@ -32,12 +34,14 @@ export const yutBot: BotStrategy<YutView, YutAction> = ({ view, legal, random })
for (const t of THROWS) {
const hits =
(t !== 'backdo' && enemyHome && advance('home', THROW_STEPS[t], o.finishRule).to === node) ||
(t === 'backdo' && enemyBackdoEnter && node === 19) ||
enemyStacks.some((st) => (t === 'backdo' ? defaultPrev(st.node) === node : advance(st.node, THROW_STEPS[t], o.finishRule).to === node));
if (hits) p += odds[t];
}
return Math.min(1, p);
};
const mineAt = (node: NodeId) => view.stacks.find((st) => st.side === me && st.node === node)?.count ?? 0;
/** Own pieces on `node` (several stacks may share it apart under `stacking = choose`). */
const mineAt = (node: NodeId) => view.stacks.filter((st) => st.side === me && st.node === node).reduce((a, st) => a + st.count, 0);
/** What losing `n` own pieces standing on `node` would cost. */
const exposure = (node: NodeId, n: number) => STEP * n * (home - dist(node)) + 10;
@@ -47,15 +51,18 @@ export const yutBot: BotStrategy<YutView, YutAction> = ({ view, legal, random })
if (m.finishes) return v + 15 * m.count;
const to = m.to as NodeId;
if (m.captures) v += 30 + m.captures * (STEP * (home - dist(to)) + 10);
const group = m.count + (m.stacks ? mineAt(to) : 0);
// Standing apart still shares the node, so a catch there takes everything; only stacking earns the small bonus.
const group = m.count + (m.stacks || m.stack === false ? mineAt(to) : 0);
if (m.stacks) v += 6;
// After a capture we throw again first, so the danger matters less.
v -= (m.captures ? 0.5 : 1) * risk(to) * exposure(to, group);
return v;
};
const byKey = new Map(view.legalMoves.map((m) => [`${m.throwIndex}:${m.from}`, m]));
const key = (x: { throwIndex: number; from: NodeId | 'home'; piece?: number; alt?: boolean; stack?: boolean }) =>
`${x.throwIndex}:${x.from}:${x.piece ?? ''}:${x.alt ? 1 : 0}:${x.stack === false ? 0 : 1}`;
const byKey = new Map(view.legalMoves.map((m) => [key(m), m]));
return best(moves, (a) => {
const m = byKey.get(`${a.throwIndex}:${a.from}`);
const m = byKey.get(key(a));
return m ? score(m) : -1e9;
}, random);
};

View File

@@ -7,6 +7,7 @@ import {
THROW_STEPS,
advance,
defaultPrev,
isFork,
remainingDistance,
rollSticks,
type NodeId,
@@ -49,6 +50,30 @@ export const yutOptionsSchema = z.object({
.enum(['first', 'all'])
.default('first')
.meta({ title: '3~4명 개인전에서 1등이 나오면', labels: { first: '바로 끝(나머지는 진행도로 순위)', all: '꼴찌가 정해질 때까지 계속' } }),
// ---- 지역 룰 (docs/games/yut.md §7). Defaults keep the original rules.
backdoNoPiece: z
.enum(['discard', 'rethrow', 'enter'])
.default('discard')
.meta({
title: '판에 내 말이 없을 때 빽도가 나오면',
labels: { discard: '쓸 곳이 없어 버림', rethrow: '다시 던짐', enter: '새 말이 참먹이 뒤(날윷)로 감' },
}),
nakRule: z
.enum(['keep', 'lose'])
.default('keep')
.meta({ title: '낙이 나오면', labels: { keep: '그 던지기만 무효(모아 둔 결과는 남음)', lose: '차례가 끝남(모아 둔 결과도 버림)' } }),
useOrder: z
.enum(['free', 'thrown'])
.default('free')
.meta({ title: '모아 둔 결과를 쓰는 순서', labels: { free: '원하는 순서로', thrown: '던진 순서대로' } }),
stacking: z
.enum(['always', 'choose'])
.default('always')
.meta({ title: '내 말이 있는 자리에 멈추면', labels: { always: '무조건 업음', choose: '업을지 따로 둘지 고름' } }),
forkRule: z
.enum(['shortcut', 'choose'])
.default('shortcut')
.meta({ title: '모서리·방에 멈췄다가 출발할 때', labels: { shortcut: '늘 지름길(방에서는 참먹이 쪽)', choose: '갈 길을 고름' } }),
turnSeconds: z
.union([z.literal(15), z.literal(30), z.literal(60), z.literal(null)])
.default(30)
@@ -62,6 +87,12 @@ export const yutActionSchema = z.discriminatedUnion('type', [
type: z.literal('MOVE'),
throwIndex: z.number().int().min(0).max(999),
from: z.union([z.literal('home'), z.number().int().min(0).max(28)]),
/** Which stack on `from` (any piece id in it) when one node holds several own stacks (`stacking = choose`). */
piece: z.number().int().min(0).max(4).optional(),
/** Take the other road at the starting fork (`forkRule = choose`). */
alt: z.boolean().optional(),
/** false = do not stack on own pieces there (`stacking = choose`). */
stack: z.boolean().optional(),
}),
z.object({ type: z.literal('CONCEDE') }),
]);
@@ -82,6 +113,11 @@ export interface Piece {
lapped: boolean;
/** Nodes visited since entering the board, current node last (for 빽도). Shared by a stack. */
trail: NodeId[];
/**
* Stack key when own pieces share a node without being stacked (`stacking = choose`): the lowest piece id of
* that stack. Absent = the node's ordinary stack. Pieces on one node with the same key move together.
*/
group?: number;
}
export interface SideState {
@@ -108,6 +144,10 @@ export interface YutMoveInfo {
count: number;
captured: { side: SideId; count: number }[];
stacked: boolean;
/** Took the other road at the fork (`forkRule = choose`). */
alt?: boolean;
/** Stopped on own pieces without stacking (`stacking = choose`). */
apart?: boolean;
}
export interface YutStats {
@@ -174,6 +214,10 @@ export interface YutLegalMove {
captures: number;
stacks: boolean;
finishes: boolean;
/** Action fields that pick this variant (see the MOVE schema); absent for the ordinary move. */
piece?: number;
alt?: boolean;
stack?: false;
}
export interface YutSideView {
@@ -193,6 +237,8 @@ export interface YutStackView {
node: NodeId;
side: SideId;
count: number;
/** Lowest piece id of the stack, only when one node holds several stacks of this side apart (`stacking = choose`). */
piece?: number;
}
export interface YutView {
@@ -215,7 +261,7 @@ export interface YutView {
/** Only for the player to move (null otherwise). */
legalMoves: YutLegalMove[] | null;
/** The move a timeout would play (§8.5), for the player to move. */
suggested: { throwIndex: number; from: NodeId | 'home' } | null;
suggested: Omit<YutMoveAction, 'type'> | null;
log: GameEvent[];
stats: YutStats;
result: YutResult | null;
@@ -272,6 +318,36 @@ function pushLog(s: YutState, events: GameEvent[], e: GameEvent): void {
if (s.log.length > LOG_MAX) s.log.splice(0, s.log.length - LOG_MAX);
}
/** Pieces of one stack share node and key; `group` is only set while own stacks share a node apart (`stacking = choose`). */
const groupKey = (p: Piece) => p.group ?? -1;
function clearPiece(p: Piece, status: 'home' | 'done'): void {
Object.assign(p, { status, node: null, lapped: false, trail: [] });
delete p.group;
}
/** Own stacks on the board, by node then lowest piece id; `ids` ascending. */
function stacksOf(x: SideState): { node: NodeId; ids: number[] }[] {
const byKey = new Map<string, { node: NodeId; ids: number[] }>();
for (const p of [...x.pieces].sort((a, b) => a.id - b.id)) {
if (p.status !== 'board') continue;
const k = `${p.node}:${groupKey(p)}`;
const g = byKey.get(k);
if (g) g.ids.push(p.id);
else byKey.set(k, { node: p.node!, ids: [p.id] });
}
return [...byKey.values()].sort((a, b) => a.node - b.node || a.ids[0]! - b.ids[0]!);
}
/** A 빽도 that could never be used this turn: no own piece on the board and no forward result to bring one on. */
function backdoUseless(s: YutState): boolean {
const side = s.sides[s.turnSide]!;
return !side.pieces.some((p) => p.status === 'board') && !s.pending.some((t) => t !== 'backdo');
}
/** Variant fields of a MOVE (see the action schema). */
type MoveSel = Pick<YutMoveAction, 'piece' | 'alt' | 'stack'>;
interface Plan {
throwIndex: number;
throw: Throw;
@@ -282,29 +358,46 @@ interface Plan {
trailAfter: NodeId[];
victims: { side: SideId; ids: number[] }[];
stackWith: number[];
/** Action selector for the stack on `from` (only when that node holds several own stacks). */
piece?: number;
alt: boolean;
/** Stops on own pieces but stays apart. */
apart: boolean;
}
/** Where `from` would go with `pending[throwIndex]`; null if that is not a legal move. */
function planMove(s: YutState, sideId: SideId, throwIndex: number, from: NodeId | 'home'): Plan | null {
function planMove(s: YutState, sideId: SideId, throwIndex: number, from: NodeId | 'home', sel: MoveSel = {}): Plan | null {
const t = s.pending[throwIndex];
const side = s.sides[sideId];
if (!t || !side) return null;
const o = s.options;
const alt = sel.alt === true;
if (alt && (o.forkRule !== 'choose' || from === 'home' || !isFork(from) || t === 'backdo')) return null;
let movers: Piece[];
let to: NodeId | typeof GOAL;
let path: NodeId[];
let trailAfter: NodeId[];
if (from === 'home') {
if (t === 'backdo') return null;
const p = side.pieces.find((x) => x.status === 'home');
if (!p) return null;
movers = [p];
const adv = advance('home', THROW_STEPS[t], o.finishRule);
({ to, path } = adv);
trailAfter = to === GOAL ? [] : [...path];
if (t === 'backdo') {
// 지역 룰: with no own piece on the board, a 빽도 puts a new piece one step behind 참먹이 (날윷).
if (o.backdoNoPiece !== 'enter' || side.pieces.some((x) => x.status === 'board')) return null;
to = 19;
path = [19];
trailAfter = [19];
} else {
const adv = advance('home', THROW_STEPS[t], o.finishRule);
({ to, path } = adv);
trailAfter = to === GOAL ? [] : [...path];
}
} else {
movers = side.pieces.filter((x) => x.status === 'board' && x.node === from);
if (movers.length === 0) return null;
const here = side.pieces.filter((x) => x.status === 'board' && x.node === from);
if (here.length === 0) return null;
const lead = sel.piece === undefined ? here.reduce((a, b) => (b.id < a.id ? b : a)) : here.find((x) => x.id === sel.piece);
if (!lead) return null;
movers = here.filter((x) => groupKey(x) === groupKey(lead));
const trail = movers[0]!.trail;
if (t === 'backdo') {
if (trail.length >= 2) {
@@ -319,7 +412,7 @@ function planMove(s: YutState, sideId: SideId, throwIndex: number, from: NodeId
}
path = to === GOAL ? [] : [to];
} else {
const adv = advance(from, THROW_STEPS[t], o.finishRule);
const adv = advance(from, THROW_STEPS[t], o.finishRule, alt);
({ to, path } = adv);
trailAfter = to === GOAL ? [] : [...trail, ...path];
}
@@ -334,28 +427,70 @@ function planMove(s: YutState, sideId: SideId, throwIndex: number, from: NodeId
else victims.push({ side: x.id, ids: here });
}
}
return { throwIndex, throw: t, from, to, path, movers: movers.map((p) => p.id), trailAfter, victims, stackWith };
const apart = sel.stack === false;
if (apart && (o.stacking !== 'choose' || stackWith.length === 0)) return null;
return {
throwIndex,
throw: t,
from,
to,
path,
movers: movers.map((p) => p.id),
trailAfter,
victims,
stackWith: apart ? [] : stackWith,
...(sel.piece !== undefined ? { piece: sel.piece } : {}),
alt,
apart,
};
}
/** Legal moves of the side to move. Equal results are listed once (first index). Order: index, node, 'home' last. */
/**
* Legal moves of the side to move. Equal results are listed once (first index; with `useOrder = thrown` only the
* first result). Order: index, stack (node, then lowest id), 'home' last; per source the ordinary move first, then
* "apart", the other road, other road + apart.
*/
function legalPlans(s: YutState): Plan[] {
if (s.phase !== 'move') return [];
const o = s.options;
const side = s.sides[s.turnSide]!;
const sources: (NodeId | 'home')[] = [...new Set(side.pieces.filter((p) => p.status === 'board').map((p) => p.node!))].sort((a, b) => a - b);
if (side.pieces.some((p) => p.status === 'home')) sources.push('home');
const stacks = stacksOf(side);
const sources: { from: NodeId | 'home'; piece?: number }[] = stacks.map((g) =>
stacks.filter((h) => h.node === g.node).length > 1 ? { from: g.node, piece: g.ids[0]! } : { from: g.node },
);
if (side.pieces.some((p) => p.status === 'home')) sources.push({ from: 'home' });
const out: Plan[] = [];
const seen = new Set<Throw>();
s.pending.forEach((t, i) => {
const indices = o.useOrder === 'thrown' ? s.pending.slice(0, 1) : s.pending;
indices.forEach((t, i) => {
if (seen.has(t)) return;
seen.add(t);
for (const from of sources) {
const p = planMove(s, s.turnSide, i, from);
if (p) out.push(p);
for (const src of sources) {
const roads = o.forkRule === 'choose' && src.from !== 'home' && isFork(src.from) && t !== 'backdo' ? [false, true] : [false];
for (const alt of roads) {
const sel: MoveSel = { ...(src.piece !== undefined ? { piece: src.piece } : {}), ...(alt ? { alt } : {}) };
const p = planMove(s, s.turnSide, i, src.from, sel);
if (!p) continue;
out.push(p);
if (o.stacking === 'choose' && p.stackWith.length) out.push(planMove(s, s.turnSide, i, src.from, { ...sel, stack: false })!);
}
}
});
return out;
}
/** The MOVE action that plays `p`. */
function planAction(p: Plan): YutMoveAction {
return {
type: 'MOVE',
throwIndex: p.throwIndex,
from: p.from,
...(p.piece !== undefined ? { piece: p.piece } : {}),
...(p.alt ? { alt: true } : {}),
...(p.apart ? { stack: false } : {}),
};
}
const toLegal = (p: Plan): YutLegalMove => ({
throwIndex: p.throwIndex,
throw: p.throw,
@@ -366,14 +501,23 @@ const toLegal = (p: Plan): YutLegalMove => ({
captures: p.victims.reduce((a, v) => a + v.ids.length, 0),
stacks: p.stackWith.length > 0,
finishes: p.to === GOAL,
...(p.piece !== undefined ? { piece: p.piece } : {}),
...(p.alt ? { alt: true } : {}),
...(p.apart ? { stack: false as const } : {}),
});
/** Deterministic auto move (§8.5): capture > finish > stack > most-behind piece with the biggest result > enter > rest. */
function chooseAuto(s: YutState, plans: Plan[]): Plan {
const rule = s.options.finishRule;
const side = s.sides[s.turnSide]!;
const flag = (x: boolean) => (x ? 1 : 0);
const byTie = (a: Plan, b: Plan) =>
a.throwIndex - b.throwIndex || (a.from === 'home' ? 1 : 0) - (b.from === 'home' ? 1 : 0) || (a.from === 'home' ? 0 : a.from) - (b.from === 'home' ? 0 : (b.from as number));
a.throwIndex - b.throwIndex ||
flag(a.from === 'home') - flag(b.from === 'home') ||
(a.from === 'home' ? 0 : a.from) - (b.from === 'home' ? 0 : (b.from as number)) ||
(a.piece ?? -1) - (b.piece ?? -1) ||
flag(a.alt) - flag(b.alt) ||
flag(a.apart) - flag(b.apart);
const pick = (list: Plan[], cmp: (a: Plan, b: Plan) => number) => [...list].sort((a, b) => cmp(a, b) || byTie(a, b))[0];
const caps = plans.filter((p) => p.victims.length > 0);
if (caps.length) return pick(caps, (a, b) => toLegal(b).captures - toLegal(a).captures)!;
@@ -394,8 +538,7 @@ export function autoAction(s: YutState): Exclude<YutAction, { type: 'TIMEOUT' }>
if (s.phase !== 'move') return { type: 'THROW' };
const plans = legalPlans(s);
if (plans.length === 0) return { type: 'THROW' }; // unreachable: stuck results are discarded right away
const p = chooseAuto(s, plans);
return { type: 'MOVE', throwIndex: p.throwIndex, from: p.from };
return planAction(chooseAuto(s, plans));
}
// ---------------------------------------------------------------- transitions
@@ -482,9 +625,15 @@ function finishGame(s: YutState, events: GameEvent[]): void {
pushLog(s, events, { type: 'gameOver', winners, summary });
}
/** In the move phase: if no pending result can be used, discard them all and end the turn (§5.3-2). */
/**
* In the move phase: if no pending result can be used, discard them all and end the turn (§5.3-2).
* With `useOrder = thrown` only the first result counts: an unusable first result is dropped and the next one is tried.
*/
function settleMovePhase(s: YutState, events: GameEvent[]): void {
if (s.phase !== 'move') return;
if (s.options.useOrder === 'thrown') {
while (s.pending.length && legalPlans(s).length === 0) pushLog(s, events, { type: 'discarded', side: s.turnSide, player: s.current, throws: s.pending.splice(0, 1) });
}
if (s.pending.length === 0) {
endTurn(s, events);
return;
@@ -501,8 +650,22 @@ function doThrow(s: YutState, rng: Rng, events: GameEvent[]): void {
s.stats.throws[r.result] += 1;
s.lastThrow = { no: s.throwNo, player: s.current, sticks: r.sticks, result: r.result };
s.throwsOwed -= 1;
if (r.result === 'nak' && s.options.nakRule === 'lose') {
// 지역 룰: a 낙 ends the turn and every unused result of this turn is lost.
pushLog(s, events, { type: 'nak', side: s.turnSide, player: s.current, endsTurn: true });
if (s.pending.length) pushLog(s, events, { type: 'discarded', side: s.turnSide, player: s.current, throws: [...s.pending] });
s.pending = [];
s.throwsOwed = 0;
endTurn(s, events);
return;
}
if (r.result === 'nak') {
pushLog(s, events, { type: 'nak', side: s.turnSide, player: s.current });
} else if (r.result === 'backdo' && s.options.backdoNoPiece === 'rethrow' && backdoUseless(s)) {
// 지역 룰: a 빽도 that could not be used is not kept; throw again.
pushLog(s, events, { type: 'thrown', side: s.turnSide, player: s.current, sticks: r.sticks, result: r.result });
pushLog(s, events, { type: 'backdoRethrow', side: s.turnSide, player: s.current });
s.throwsOwed += 1;
} else {
s.pending.push(r.result);
if (r.result === 'yut' || r.result === 'mo') s.throwsOwed += 1;
@@ -513,20 +676,30 @@ function doThrow(s: YutState, rng: Rng, events: GameEvent[]): void {
settleMovePhase(s, events);
}
function doMove(s: YutState, throwIndex: number, from: NodeId | 'home', events: GameEvent[]): void {
const plan = planMove(s, s.turnSide, throwIndex, from);
if (!plan) throw new Error(`yut: illegal move ${throwIndex} ${from}`);
function doMove(s: YutState, a: YutMoveAction, events: GameEvent[]): void {
const plan = planMove(s, s.turnSide, a.throwIndex, a.from, a);
if (!plan) throw new Error(`yut: illegal move ${a.throwIndex} ${a.from}`);
const side = s.sides[s.turnSide]!;
s.pending.splice(throwIndex, 1);
s.pending.splice(a.throwIndex, 1);
const movers = side.pieces.filter((p) => plan.movers.includes(p.id));
const lead = Math.min(...plan.movers);
for (const p of movers) {
if (plan.to === GOAL) Object.assign(p, { status: 'done', node: null, lapped: false, trail: [] });
else Object.assign(p, { status: 'board', node: plan.to, lapped: plan.to === 0, trail: [...plan.trailAfter] });
if (plan.to === GOAL) clearPiece(p, 'done');
else {
Object.assign(p, { status: 'board', node: plan.to, lapped: plan.to === 0, trail: [...plan.trailAfter] });
// Standing apart next to own pieces keeps a key of its own; otherwise it is the node's ordinary stack.
if (plan.apart) p.group = lead;
else delete p.group;
}
}
for (const p of side.pieces) {
if (!plan.stackWith.includes(p.id)) continue;
Object.assign(p, { lapped: plan.to === 0, trail: [...plan.trailAfter] });
delete p.group;
}
for (const p of side.pieces) if (plan.stackWith.includes(p.id)) Object.assign(p, { lapped: plan.to === 0, trail: [...plan.trailAfter] });
let caught = 0;
for (const v of plan.victims) {
for (const p of s.sides[v.side]!.pieces) if (v.ids.includes(p.id)) Object.assign(p, { status: 'home', node: null, lapped: false, trail: [] });
for (const p of s.sides[v.side]!.pieces) if (v.ids.includes(p.id)) clearPiece(p, 'home');
caught += v.ids.length;
}
s.moveNo += 1;
@@ -541,8 +714,21 @@ function doMove(s: YutState, throwIndex: number, from: NodeId | 'home', events:
count: movers.length,
captured: plan.victims.map((v) => ({ side: v.side, count: v.ids.length })),
stacked: plan.stackWith.length > 0,
...(plan.alt ? { alt: true } : {}),
...(plan.apart ? { apart: true } : {}),
};
pushLog(s, events, { type: 'moved', side: side.id, player: s.current, throw: plan.throw, from: plan.from, to: plan.to, path: plan.path, count: movers.length });
pushLog(s, events, {
type: 'moved',
side: side.id,
player: s.current,
throw: plan.throw,
from: plan.from,
to: plan.to,
path: plan.path,
count: movers.length,
...(plan.alt ? { alt: true } : {}),
...(plan.apart ? { apart: true } : {}),
});
if (plan.stackWith.length) pushLog(s, events, { type: 'stacked', side: side.id, node: plan.to, count: movers.length + plan.stackWith.length });
for (const v of plan.victims) pushLog(s, events, { type: 'captured', side: side.id, victimSide: v.side, count: v.ids.length, node: plan.to });
if (caught) s.stats.captures[String(side.id)] = (s.stats.captures[String(side.id)] ?? 0) + 1;
@@ -586,7 +772,7 @@ function doConcede(s: YutState, actor: PlayerId, events: GameEvent[]): void {
}
side.out = true;
side.outSeq = ++s.outCount;
for (const p of side.pieces) if (p.status === 'board') Object.assign(p, { status: 'home', node: null, lapped: false, trail: [] });
for (const p of side.pieces) if (p.status === 'board') clearPiece(p, 'home');
if (gameShouldEnd(s)) {
finishGame(s, events);
return;
@@ -694,13 +880,27 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
if (s.phase !== 'move') return fail('지금은 말을 움직일 차례가 아니에요. 먼저 윷을 던져 주세요.');
const t = s.pending[a.throwIndex];
if (!t) return fail('그 윷 결과는 없어요.');
const o = s.options;
if (o.useOrder === 'thrown' && a.throwIndex !== 0) return fail('이 방은 던진 순서대로 써요. 맨 앞의 결과부터 써 주세요.');
if (a.from === 'home') {
if (t === 'backdo') return fail('빽도로는 새 말을 올릴 수 없어요.');
if (!side.pieces.some((p) => p.status === 'home')) return fail('기다리는 말이 없어요.');
} else if (!side.pieces.some((p) => p.status === 'board' && p.node === a.from)) {
if (t === 'backdo') {
if (o.backdoNoPiece !== 'enter') return fail('빽도로는 새 말을 올릴 수 없어요.');
if (side.pieces.some((p) => p.status === 'board')) return fail('판에 내 말이 있으면 빽도는 판 위의 말에 써야 해요.');
}
} else if (!side.pieces.some((p) => p.status === 'board' && p.node === a.from && (a.piece === undefined || p.id === a.piece))) {
return fail('그 말은 움직일 수 없어요.');
}
return planMove(s, sideId, a.throwIndex, a.from) ? ok : fail('그 말은 움직일 수 없어요.');
if (a.alt) {
if (o.forkRule !== 'choose') return fail('이 방은 갈 길을 고르지 않아요. 모서리·방에 멈췄던 말은 늘 지름길로 가요.');
if (a.from === 'home' || !isFork(a.from) || t === 'backdo') return fail('모서리나 방에 멈춰 있던 말이 앞으로 갈 때만 길을 고를 수 있어요.');
}
if (a.stack === false) {
if (o.stacking !== 'choose') return fail('이 방은 내 말이 있는 자리에 멈추면 무조건 업어요.');
const plain = planMove(s, sideId, a.throwIndex, a.from, { ...a, stack: undefined });
if (plain && plain.stackWith.length === 0) return fail('그 자리에는 업을 내 말이 없어요.');
}
return planMove(s, sideId, a.throwIndex, a.from, a) ? ok : fail('그 말은 움직일 수 없어요.');
}
}
return fail('알 수 없는 행동이에요.');
@@ -721,7 +921,7 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
doThrow(s, rng, events);
break;
case 'MOVE':
doMove(s, act.throwIndex, act.from, events);
doMove(s, act, events);
break;
case 'CONCEDE':
doConcede(s, actor, events);
@@ -736,11 +936,13 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
const mySide = viewer !== null && s.sideOf[viewer] !== undefined ? s.sideOf[viewer]! : null;
const stacks: YutStackView[] = [];
for (const x of s.sides) {
const byNode = new Map<NodeId, number>();
for (const p of x.pieces) if (p.status === 'board') byNode.set(p.node!, (byNode.get(p.node!) ?? 0) + 1);
for (const [node, count] of byNode) stacks.push({ node, side: x.id, count });
const own = stacksOf(x);
for (const g of own) {
const apart = own.filter((h) => h.node === g.node).length > 1;
stacks.push({ node: g.node, side: x.id, count: g.ids.length, ...(apart ? { piece: g.ids[0]! } : {}) });
}
}
stacks.sort((a, b) => a.node - b.node);
stacks.sort((a, b) => a.node - b.node || (a.piece ?? -1) - (b.piece ?? -1));
const mine = s.phase === 'move' && viewer !== null && viewer === s.current;
const plans = mine ? legalPlans(s) : [];
const auto = mine && plans.length ? chooseAuto(s, plans) : null;
@@ -773,7 +975,7 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
deadlineAt: s.deadlineAt,
away: s.players.filter((p) => (s.timeouts[p] ?? 0) >= AWAY_AFTER),
legalMoves: mine ? plans.map(toLegal) : null,
suggested: auto ? { throwIndex: auto.throwIndex, from: auto.from } : null,
suggested: auto ? (({ type: _t, ...rest }) => rest)(planAction(auto)) : null,
log: s.log,
stats: s.stats,
result: s.final,
@@ -824,7 +1026,7 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
legalActions(s, p) {
if (s.phase === 'finished' || p !== s.current) return [];
if (s.phase === 'throw') return [{ type: 'THROW' }];
return legalPlans(s).map((x) => ({ type: 'MOVE' as const, throwIndex: x.throwIndex, from: x.from }));
return legalPlans(s).map(planAction);
},
};

View File

@@ -357,6 +357,194 @@ describe('던지기와 이동', () => {
});
});
// ---------------------------------------------------------------- 지역 룰 (§7)
describe('지역 룰', () => {
test('defaults keep the original rules', () => {
expect(yut.defaultOptions).toMatchObject({ backdoNoPiece: 'discard', nakRule: 'keep', useOrder: 'free', stacking: 'always', forkRule: 'shortcut' });
});
test('backdoNoPiece = rethrow: a 빽도 that could not be used is not kept and the player throws again', () => {
let s = make({ backdoNoPiece: 'rethrow' });
const rng = script(['backdo', 'gae']);
const r = actE(s, 'A', { type: 'THROW' }, rng);
s = r.state;
expect(r.events.map((e) => e.type)).toEqual(['thrown', 'backdoRethrow']);
expect([s.current, s.phase, s.throwsOwed, s.pending, s.lastThrow?.result]).toEqual(['A', 'throw', 1, [], 'backdo']);
expect(s.stats.throws.backdo).toBe(1);
s = throwN(s, rng);
expect([s.phase, s.pending]).toEqual(['move', ['gae']]);
// With a piece on the board (or a forward result to bring one on) the 빽도 is kept as usual.
const b = make({ backdoNoPiece: 'rethrow' });
put(b, 0, 0, 3, [1, 2, 3]);
expect(act(b, 'A', { type: 'THROW' }, script(['backdo'])).pending).toEqual(['backdo']);
const y = throwN(make({ backdoNoPiece: 'rethrow' }), script(['yut', 'backdo']), 2);
expect([y.phase, y.pending]).toEqual(['move', ['yut', 'backdo']]);
});
test('backdoNoPiece = enter: with nothing on the board a 빽도 puts a new piece on 날윷(19); 개 from there finishes', () => {
let s = moving(make({ backdoNoPiece: 'enter' }), ['backdo', 'gae']);
expect(yut.view(s, 'A').legalMoves!.map((m) => [m.throw, m.from, m.to])).toEqual([
['backdo', 'home', 19],
['gae', 'home', 2],
]);
s = act(s, 'A', mv(0, 'home'));
expect(piece(s, 0, 0)).toMatchObject({ status: 'board', node: 19, trail: [19], lapped: false });
s = act(s, 'A', mv(0, 19));
expect(piece(s, 0, 0).status).toBe('done');
// 도 stops on 참먹이 (pass) — the piece counts as lapped there.
let d = moving(make({ backdoNoPiece: 'enter' }), ['backdo', 'do']);
d = use(use(d, 'backdo', 'home'), 'do', 19);
expect(piece(d, 0, 0)).toMatchObject({ node: 0, lapped: true });
// Only while no own piece is on the board; an enemy on 19 is caught.
const busy = make({ backdoNoPiece: 'enter' });
put(busy, 0, 0, 3, [1, 2, 3]);
expect(reject(moving(busy, ['backdo']), 'A', mv(0, 'home'))).toBe('판에 내 말이 있으면 빽도는 판 위의 말에 써야 해요.');
expect(reject(moving(make(), ['backdo']), 'A', mv(0, 'home'))).toBe('빽도로는 새 말을 올릴 수 없어요.');
const cap = make({ backdoNoPiece: 'enter' });
put(cap, 1, 0, 19, [16, 17, 18, 19]);
const c = act(moving(cap, ['backdo']), 'A', mv(0, 'home'));
expect([piece(c, 1, 0).status, c.phase]).toEqual(['home', 'throw']);
});
test('nakRule = lose: a 낙 ends the turn and the collected results are lost; keep (default) keeps them', () => {
let s = make({ nakPercent: 10, nakRule: 'lose' });
const rng = script(['yut', 'nak'], true);
s = throwN(s, rng);
const r = actE(s, 'A', { type: 'THROW' }, rng);
s = r.state;
expect(r.events.find((e) => e.type === 'nak')).toMatchObject({ endsTurn: true });
expect(r.events.find((e) => e.type === 'discarded')).toMatchObject({ throws: ['yut'] });
expect([s.current, s.phase, s.pending]).toEqual(['B', 'throw', []]);
// Also on a capture-bonus throw: earlier unused results go too.
let b = make({ nakPercent: 10, nakRule: 'lose' });
put(b, 0, 0, 2, [1, 2]);
put(b, 1, 0, 4, [1, 2, 3, 4]);
b = use(moving(b, ['gae', 'geol']), 'gae', 2);
b = act(b, 'A', { type: 'THROW' }, script(['nak'], true));
expect([b.current, b.pending]).toEqual(['B', []]);
expect(piece(b, 0, 0).node).toBe(4);
});
test('useOrder = thrown: only the first result can be used; an unusable first result is dropped', () => {
let s = moving(make({ useOrder: 'thrown' }), ['yut', 'mo', 'geol']);
expect(new Set(yut.legalActions!(s, 'A').map((a) => (a as { throwIndex: number }).throwIndex))).toEqual(new Set([0]));
expect(reject(s, 'A', mv(1, 'home'))).toBe('이 방은 던진 순서대로 써요. 맨 앞의 결과부터 써 주세요.');
s = act(s, 'A', mv(0, 'home'));
expect([piece(s, 0, 0).node, s.pending]).toEqual([4, ['mo', 'geol']]);
// Free order (default) may start with 모.
expect(yut.validate(moving(make(), ['yut', 'mo', 'geol']), 'A', mv(1, 'home')).ok).toBe(true);
// [걸, 빽도, 개] with the only board piece finishing on 걸: the 빽도 has nowhere to go and is dropped, 개 stays.
let d = make({ useOrder: 'thrown' });
put(d, 0, 0, 18, [16, 17, 18]);
const r = actE(moving(d, ['geol', 'backdo', 'gae']), 'A', mv(0, 18));
d = r.state;
expect(piece(d, 0, 0).status).toBe('done');
expect(r.events.find((e) => e.type === 'discarded')).toMatchObject({ throws: ['backdo'] });
expect([d.phase, d.pending, d.current]).toEqual(['move', ['gae'], 'A']);
});
test('stacking = choose: stop next to own pieces apart, move each stack on its own, both get caught together', () => {
let s = make({ stacking: 'choose' });
put(s, 0, 0, 3, [1, 2, 3]);
s = moving(s, ['geol', 'gae', 'do']);
const lm = yut.view(s, 'A').legalMoves!.filter((m) => m.throw === 'geol' && m.from === 'home');
expect(lm.map((m) => [m.to, m.stacks, m.stack])).toEqual([
[3, true, undefined],
[3, false, false],
]);
s = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home', stack: false });
expect(piece(s, 0, 1)).toMatchObject({ node: 3, group: 1 });
expect(s.lastMove).toMatchObject({ stacked: false, apart: true });
expect(yut.view(s, 'A').stacks).toEqual([
{ node: 3, side: 0, count: 1, piece: 0 },
{ node: 3, side: 0, count: 1, piece: 1 },
]);
const from3 = yut.legalActions!(s, 'A').filter((a) => a.type === 'MOVE' && a.from === 3);
expect(from3).toContainEqual({ type: 'MOVE', throwIndex: 0, from: 3, piece: 0 });
expect(from3).toContainEqual({ type: 'MOVE', throwIndex: 0, from: 3, piece: 1 });
s = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 3, piece: 1 }); // 개: only piece 1 → 5
expect([piece(s, 0, 0).node, piece(s, 0, 1).node]).toEqual([3, 5]);
expect(piece(s, 0, 1).group).toBeUndefined();
// Stacking onto a node that holds two stacks apart merges all of them.
let m = make({ stacking: 'choose' });
put(m, 0, 0, 4, [1, 2, 3, 4]);
put(m, 0, 1, 4, [2, 3, 4]);
m.sides[0]!.pieces[1]!.group = 1;
put(m, 0, 2, 2, [1, 2]);
m = act(moving(m, ['gae']), 'A', mv(0, 2));
expect(yut.view(m, 'A').stacks).toEqual([{ node: 4, side: 0, count: 3 }]);
expect(m.sides[0]!.pieces.map((p) => p.group)).toEqual([undefined, undefined, undefined, undefined]);
// An enemy landing there catches every own piece on the node.
let c = make({ stacking: 'choose' });
put(c, 1, 0, 3, [1, 2, 3]);
put(c, 1, 1, 3, [1, 2, 3]);
c.sides[1]!.pieces[1]!.group = 1;
const cr = actE(moving(c, ['geol']), 'A', mv(0, 'home'));
expect(cr.events.find((e) => e.type === 'captured')).toMatchObject({ count: 2 });
expect([piece(cr.state, 1, 0).status, piece(cr.state, 1, 1).status, piece(cr.state, 1, 1).group]).toEqual(['home', 'home', undefined]);
});
test('stacking: validation (always = no choice; apart needs own pieces there; piece must stand on from)', () => {
const a = make();
put(a, 0, 0, 3, [1, 2, 3]);
expect(reject(moving(a, ['geol']), 'A', { type: 'MOVE', throwIndex: 0, from: 'home', stack: false })).toBe('이 방은 내 말이 있는 자리에 멈추면 무조건 업어요.');
expect(yut.view(moving(a, ['geol']), 'A').legalMoves!.every((m) => m.stack === undefined)).toBe(true);
const c = make({ stacking: 'choose' });
put(c, 0, 0, 3, [1, 2, 3]);
expect(reject(moving(c, ['gae']), 'A', { type: 'MOVE', throwIndex: 0, from: 'home', stack: false })).toBe('그 자리에는 업을 내 말이 없어요.');
expect(reject(moving(c, ['gae']), 'A', { type: 'MOVE', throwIndex: 0, from: 3, piece: 2 })).toBe('그 말은 움직일 수 없어요.');
});
test('forkRule = choose: a piece that stopped on 모 / 뒷모 / 방 may take the other road', () => {
const at = (node: NodeId, trail: NodeId[], t: Throw) => {
const s = make({ forkRule: 'choose' });
put(s, 0, 0, node, trail);
return moving(s, [t]);
};
const roads = (s: YutState) => yut.view(s, 'A').legalMoves!.filter((m) => m.from !== 'home').map((m) => [m.to, m.alt ?? false]);
expect(roads(at(5, [1, 2, 3, 4, 5], 'geol'))).toEqual([[22, false], [8, true]]);
expect(roads(at(10, [6, 7, 8, 9, 10], 'gae'))).toEqual([[26, false], [12, true]]);
expect(roads(at(22, [20, 21, 22], 'do'))).toEqual([[27, false], [23, true]]);
expect(roads(at(3, [1, 2, 3], 'do'))).toEqual([[4, false]]);
expect(roads(at(5, [4, 5], 'backdo'))).toEqual([[4, false]]);
let s = act(at(5, [1, 2, 3, 4, 5], 'geol'), 'A', { type: 'MOVE', throwIndex: 0, from: 5, alt: true });
expect(piece(s, 0, 0)).toMatchObject({ node: 8, trail: [1, 2, 3, 4, 5, 6, 7, 8] });
expect(s.lastMove).toMatchObject({ alt: true, path: [6, 7, 8] });
// 빽도 afterwards walks the recorded road back.
s.turnSide = 0;
s.current = 'A';
s = act(moving(s, ['backdo']), 'A', mv(0, 8));
expect(piece(s, 0, 0).node).toBe(7);
// Passing a fork is unchanged: 4 + 걸 → 7.
expect(roads(at(4, [1, 2, 3, 4], 'geol'))).toEqual([[7, false]]);
// The other road can catch.
const cap = at(5, [1, 2, 3, 4, 5], 'gae');
put(cap, 1, 0, 7, [6, 7]);
const c = act(cap, 'A', { type: 'MOVE', throwIndex: 0, from: 5, alt: true });
expect([piece(c, 1, 0).status, c.phase]).toEqual(['home', 'throw']);
});
test('forkRule: validation', () => {
const s = make();
put(s, 0, 0, 5, [1, 2, 3, 4, 5]);
expect(reject(moving(s, ['geol']), 'A', { type: 'MOVE', throwIndex: 0, from: 5, alt: true })).toBe('이 방은 갈 길을 고르지 않아요. 모서리·방에 멈췄던 말은 늘 지름길로 가요.');
const c = make({ forkRule: 'choose' });
put(c, 0, 0, 5, [4, 5]);
put(c, 0, 1, 3, [1, 2, 3]);
expect(reject(moving(c, ['geol']), 'A', { type: 'MOVE', throwIndex: 0, from: 3, alt: true })).toBe('모서리나 방에 멈춰 있던 말이 앞으로 갈 때만 길을 고를 수 있어요.');
expect(reject(moving(c, ['backdo']), 'A', { type: 'MOVE', throwIndex: 0, from: 5, alt: true })).toBe('모서리나 방에 멈춰 있던 말이 앞으로 갈 때만 길을 고를 수 있어요.');
expect(reject(moving(c, ['geol']), 'A', { type: 'MOVE', throwIndex: 0, from: 'home', alt: true })).toBe('모서리나 방에 멈춰 있던 말이 앞으로 갈 때만 길을 고를 수 있어요.');
});
test('timeouts pick the ordinary move first (shortcut, stacking)', () => {
const s = make({ forkRule: 'choose', stacking: 'choose' });
put(s, 0, 0, 5, [1, 2, 3, 4, 5]);
put(s, 0, 1, 20, [20]);
expect(autoAction(moving(s, ['do']))).toEqual({ type: 'MOVE', throwIndex: 0, from: 5 });
});
});
// ---------------------------------------------------------------- turns, teams, ranking
describe('차례·팀전·순위', () => {
@@ -618,6 +806,12 @@ const CONFIGS: Config[] = [
{ opts: { mode: 'team', pieces: 5, backdo: false, nakPercent: 3 }, n: 8 },
{ opts: { pieces: 5, ranking: 'all', finishRule: 'reach', stickModel: 'fair' }, n: 3 },
{ opts: { pieces: 2, nakPercent: 5, turnSeconds: null }, n: 2 },
// 지역 룰
{ opts: { stacking: 'choose', forkRule: 'choose' }, n: 2 },
{ opts: { backdoNoPiece: 'rethrow', useOrder: 'thrown', nakPercent: 10, nakRule: 'lose' }, n: 3 },
{ opts: { backdoNoPiece: 'enter', stacking: 'choose', stickModel: 'fair', finishRule: 'reach' }, n: 4 },
{ opts: { mode: 'team', forkRule: 'choose', useOrder: 'thrown', backdoNoPiece: 'enter', pieces: 5 }, n: 4 },
{ opts: { stacking: 'choose', forkRule: 'choose', backdoNoPiece: 'rethrow', nakPercent: 3, nakRule: 'lose', ranking: 'all', pieces: 5 }, n: 4 },
];
/** Per-step invariants: piece count, one side per node, trail ends on the node, phase consistency, onTimeout legal. */
@@ -636,12 +830,21 @@ function invariant(st: unknown): void {
occupied.set(p.node, x.id);
} else if (p.node !== null || p.trail.length) throw new Error('off-board piece keeps a position');
}
const stacked = new Map<number, string>();
const stacked = new Map<string, string>();
for (const p of x.pieces) {
if (p.status !== 'board') continue;
if (p.status !== 'board') {
if (p.group !== undefined) throw new Error('off-board piece keeps a stack key');
continue;
}
if (p.group !== undefined) {
if (s.options.stacking !== 'choose') throw new Error('stack key without stacking = choose');
const lead = x.pieces[p.group];
if (!lead || lead.status !== 'board' || lead.node !== p.node || lead.group !== p.group) throw new Error('stack key without its lead piece');
}
const k = `${p.node}:${p.group ?? -1}`;
const key = JSON.stringify(p.trail);
if (stacked.has(p.node!) && stacked.get(p.node!) !== key) throw new Error('stack with different trails');
stacked.set(p.node!, key);
if (stacked.has(k) && stacked.get(k) !== key) throw new Error('stack with different trails');
stacked.set(k, key);
}
if (x.finishedRank !== null && x.pieces.some((p) => p.status !== 'done')) throw new Error('finished side with pieces left');
}