- 규칙 모듈 packages/games/src/uno: 108장(원카드 색깔 카드 덱·점수 재사용, 원카드 코드는 그대로), 7장씩, 공식 시작 카드 처리(드로우4 다시 섞기, 드로우2·스킵·리버스, 와일드는 첫 사람이 색 고르기), 색·숫자·기호 맞추기, 낼 카드가 있어도 뽑기 + 뽑은 카드 바로 내기, 2명 리버스=스킵, 와일드 드로우4 도전(공식: 몰래 낼 수 있고 성공 4장/실패 6장, 손패는 도전한 사람만) 또는 쉬운 규칙, "우노!" 외치기(내면서 또는 직후, 다음 차례 행동 전까지 누구나 잡기 2장), 공식 점수(한 판/500점), 하우스 룰(드로우 카드 쌓기, 낼 수 있을 때까지 뽑기, 기본 끄기). 시간 초과는 낼 수 있는 카드 자동 (와일드는 많이 가진 색), 나가기·자리 비움 처리. - 컴퓨터 상대(bot.ts): 레벨별 우노 깜빡함·잡기 확률, 드로우 카드 아끼기, 드로우4 거짓말/도전 판단, 색 고르기. - 테스트: 규칙 시나리오, 무작위 대국(유출·보존·결정성), 컴퓨터, 방에서 사람 1 + 컴퓨터 3 끝까지. - 화면 apps/web/src/games/uno: 지금 색 링·칩, 방향·다음 사람, 남은 장수, 우노 버튼(준비/외치기), 잡기 버튼, 도전·시작 색·판 결과 창, 30초 요약, 지금 할 수 있는 것. - 등록(GAMES, 카탈로그, BOT_GAMES/BOT_STRATEGIES, 화면 레지스트리, 아이콘·카드 탭), docs/games/uno.md, E2E 계획(PC 1 + 휴대폰 2, 끝까지, 잡기·도전 화면). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
603 lines
30 KiB
TypeScript
603 lines
30 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
||
import { SeededRng, playoutSeeds, randomPlayout, seedN, type GameEvent, type PlayerId, type RngState } from '@bg/engine';
|
||
import { cardTotal, uno, unoDeck, type UnoAction, type UnoCard, type UnoOptions, type UnoState } from './index';
|
||
|
||
// ---------------------------------------------------------------- helpers
|
||
|
||
const ALL = unoDeck();
|
||
const card = (id: string): UnoCard => {
|
||
const c = ALL.find((x) => x.id === id);
|
||
if (!c) throw new Error(`no card ${id}`);
|
||
return c;
|
||
};
|
||
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
|
||
let clock = 1_000_000;
|
||
|
||
function make(opts: Partial<UnoOptions> = {}, players = ['A', 'B', 'C'], seed = 1): UnoState {
|
||
return uno.setup({ players, options: uno.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||
}
|
||
|
||
/** Replaces hands / discard / turn; the rest of the deck becomes the draw pile (unless given). */
|
||
function rig(s: UnoState, r: { hands: Record<string, string[]>; discard: string[]; current?: string; drawPile?: string[]; pending?: number; color?: UnoState['color'] }): UnoState {
|
||
for (const p of s.seats) s.hands[p] = (r.hands[p] ?? []).map(card);
|
||
s.discard = r.discard.map(card);
|
||
const t = s.discard[s.discard.length - 1]!;
|
||
s.color = r.color ?? ('color' in t ? t.color : 'R');
|
||
s.current = r.current ?? s.seats[0]!;
|
||
s.phase = { kind: 'turn' };
|
||
s.pending = r.pending ?? 0;
|
||
s.direction = 1;
|
||
s.unoWindow = null;
|
||
if (r.drawPile) s.drawPile = r.drawPile.map(card);
|
||
else {
|
||
const used = new Set([...Object.values(r.hands).flat(), ...r.discard]);
|
||
s.drawPile = unoDeck().filter((c) => !used.has(c.id));
|
||
}
|
||
return s;
|
||
}
|
||
|
||
function actE(s: UnoState, p: string, a: UnoAction): { state: UnoState; events: GameEvent[] } {
|
||
const v = uno.validate(s, p, a);
|
||
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
|
||
return uno.apply(s, p, a, { rng: rng(), now: (clock += 1000) });
|
||
}
|
||
const act = (s: UnoState, p: string, a: UnoAction) => actE(s, p, a).state;
|
||
const play = (s: UnoState, p: string, id: string, extra: Partial<Extract<UnoAction, { type: 'play' }>> = {}) => act(s, p, { type: 'play', cardId: id, ...extra });
|
||
const reject = (s: UnoState, p: string, a: UnoAction): string | null => {
|
||
const v = uno.validate(s, p, a);
|
||
return v.ok ? null : v.reason;
|
||
};
|
||
const ids = (s: UnoState, p: string) => s.hands[p]!.map((c) => c.id);
|
||
const topId = (s: UnoState) => s.discard[s.discard.length - 1]!.id;
|
||
|
||
/** First seed (3 players) whose start card has this kind. */
|
||
function seedWithStart(kind: UnoCard['kind'], players = ['A', 'B', 'C']): UnoState {
|
||
for (let i = 1; i < 2000; i++) {
|
||
const s = make({}, players, i);
|
||
if (s.discard[0]!.kind === kind) return s;
|
||
}
|
||
throw new Error(`no seed starts with ${kind}`);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- setup
|
||
|
||
describe('준비 (§4)', () => {
|
||
test('same seed → same deal; 7 cards each; 108 cards; the start card is never a 와일드 드로우4', () => {
|
||
const a = make({}, ['A', 'B', 'C'], 5);
|
||
expect(JSON.stringify(a)).toBe(JSON.stringify(make({}, ['A', 'B', 'C'], 5)));
|
||
expect(JSON.stringify(make({}, ['A', 'B', 'C'], 6).hands)).not.toBe(JSON.stringify(a.hands));
|
||
for (const p of a.seats) expect(a.hands[p]).toHaveLength(7);
|
||
expect(cardTotal(a)).toBe(108);
|
||
expect(new Set(unoDeck().map((c) => c.id)).size).toBe(108);
|
||
for (let i = 1; i <= 300; i++) expect(make({}, ['A', 'B'], i).discard[0]!.kind).not.toBe('wild4');
|
||
const ten = make({}, Array.from({ length: 10 }, (_, k) => `P${k}`));
|
||
expect(cardTotal(ten)).toBe(108);
|
||
expect(() => make({}, ['A'])).toThrow();
|
||
});
|
||
|
||
test('start 드로우2: the first player draws 2 and is skipped', () => {
|
||
const s = seedWithStart('draw2');
|
||
const first = s.roundStarter;
|
||
expect(s.hands[first]).toHaveLength(9);
|
||
expect(s.current).toBe(s.seats[(s.seats.indexOf(first) + 1) % 3]!);
|
||
expect(s.phase.kind).toBe('turn');
|
||
});
|
||
|
||
test('start 스킵: the first player is skipped', () => {
|
||
const s = seedWithStart('skip');
|
||
expect(s.current).toBe(s.seats[(s.seats.indexOf(s.roundStarter) + 1) % 3]!);
|
||
expect(s.hands[s.roundStarter]).toHaveLength(7);
|
||
});
|
||
|
||
test('start 리버스: the dealer (seat before the first player) starts and play goes the other way; 2 players = skip', () => {
|
||
const s = seedWithStart('reverse');
|
||
expect(s.direction).toBe(-1);
|
||
expect(s.current).toBe(s.seats[(s.seats.indexOf(s.roundStarter) + 2) % 3]!);
|
||
const two = seedWithStart('reverse', ['A', 'B']);
|
||
expect(two.direction).toBe(1);
|
||
expect(two.current).not.toBe(two.roundStarter);
|
||
});
|
||
|
||
test('start 와일드: the first player names the colour, then plays', () => {
|
||
let s = seedWithStart('wild');
|
||
const first = s.roundStarter;
|
||
expect(s.phase.kind).toBe('startColor');
|
||
expect(s.color).toBeNull();
|
||
expect(uno.view(s, first).my!.canStartColor).toBe(true);
|
||
expect(uno.view(s, first).my!.playable).toEqual([]);
|
||
expect(reject(s, first, { type: 'draw' })).not.toBeNull();
|
||
s = act(s, first, { type: 'startColor', color: 'G' });
|
||
expect(s.color).toBe('G');
|
||
expect(s.phase.kind).toBe('turn');
|
||
expect(s.current).toBe(first);
|
||
});
|
||
|
||
test('start number: the first player plays; colour = the card colour', () => {
|
||
const s = seedWithStart('num');
|
||
expect(s.current).toBe(s.roundStarter);
|
||
expect(s.color).toBe((s.discard[0] as Extract<UnoCard, { kind: 'num' }>).color);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- playing
|
||
|
||
describe('내기 (§5)', () => {
|
||
test('same colour, number or symbol; anything else is refused', () => {
|
||
const s = rig(make(), { hands: { A: ['R3a', 'B5a', 'G7a', 'YSa', 'W1'], B: ['R1a'], C: ['G1a'] }, discard: ['R5a'] });
|
||
expect(uno.view(s, 'A').my!.playable.sort()).toEqual(['B5a', 'R3a', 'W1']);
|
||
expect(reject(s, 'A', { type: 'play', cardId: 'G7a' })).toBe('같은 색이나 같은 숫자·기호 카드만 낼 수 있어요.');
|
||
expect(reject(s, 'A', { type: 'play', cardId: 'W1' })).toBe('색을 골라 주세요.');
|
||
expect(reject(s, 'A', { type: 'play', cardId: 'R3a', color: 'B' })).not.toBeNull();
|
||
const t = play(s, 'A', 'B5a');
|
||
expect(t.color).toBe('B');
|
||
expect(t.current).toBe('B');
|
||
const sym = rig(make(), { hands: { A: ['GSa', 'Y2a'], B: ['R1a'] }, discard: ['RSb'] });
|
||
expect(uno.view(sym, 'A').my!.playable).toEqual(['GSa']);
|
||
});
|
||
|
||
test('와일드 sets the colour; the next player follows it', () => {
|
||
let s = rig(make(), { hands: { A: ['W1', 'R1a'], B: ['B2a', 'G2a'], C: ['Y1a'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'W1', { color: 'G' });
|
||
expect(s.color).toBe('G');
|
||
expect(uno.view(s, 'B').my!.playable).toEqual(['G2a']);
|
||
expect(s.log.at(-1)).toMatchObject({ t: 'play', p: 'A', color: 'G' });
|
||
});
|
||
|
||
test('스킵 skips one; 리버스 turns the direction (3+ players) or skips (2 players)', () => {
|
||
let s = rig(make(), { hands: { A: ['RSa', 'R1a'], B: ['R2a'], C: ['R3a', 'RRa'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'RSa');
|
||
expect(s.current).toBe('C');
|
||
s = play(s, 'C', 'RRa');
|
||
expect(s.direction).toBe(-1);
|
||
expect(s.current).toBe('B');
|
||
let two = rig(make({}, ['A', 'B']), { hands: { A: ['RRa', 'R1a', 'R2a'], B: ['R3a'] }, discard: ['R5a'] });
|
||
two = play(two, 'A', 'RRa');
|
||
expect(two.current).toBe('A');
|
||
expect(two.direction).toBe(1);
|
||
});
|
||
|
||
test('드로우2: the next player draws 2 and loses the turn', () => {
|
||
let s = rig(make(), { hands: { A: ['RDa', 'R1a'], B: ['R2a'], C: ['R3a'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'RDa');
|
||
expect(s.hands.B).toHaveLength(3);
|
||
expect(s.current).toBe('C');
|
||
expect(s.pending).toBe(0);
|
||
});
|
||
|
||
test('draw: one card; a playable drawn card may be played at once (only that card) or kept', () => {
|
||
let s = rig(make(), { hands: { A: ['R1a', 'B9a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'], drawPile: ['R7a', 'G8a', 'Y8a'] });
|
||
// Drawing is allowed even with a playable card (official).
|
||
s = act(s, 'A', { type: 'draw' });
|
||
expect(s.phase).toEqual({ kind: 'afterDraw', drawnCardId: 'R7a' });
|
||
expect(reject(s, 'A', { type: 'play', cardId: 'R1a' })).toBe('방금 뽑은 카드만 낼 수 있어요.');
|
||
expect(reject(s, 'A', { type: 'draw' })).not.toBeNull();
|
||
const kept = act(s, 'A', { type: 'pass' });
|
||
expect(kept.current).toBe('B');
|
||
expect(ids(kept, 'A')).toContain('R7a');
|
||
const played = play(s, 'A', 'R7a');
|
||
expect(topId(played)).toBe('R7a');
|
||
expect(played.current).toBe('B');
|
||
// Not playable → the turn passes.
|
||
let t = rig(make(), { hands: { A: ['B9a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'], drawPile: ['G8a', 'Y8a'] });
|
||
t = act(t, 'A', { type: 'draw' });
|
||
expect(t.current).toBe('B');
|
||
expect(ids(t, 'A')).toEqual(['B9a', 'G8a']);
|
||
});
|
||
|
||
test('(house rule) 낼 수 있을 때까지 뽑기', () => {
|
||
let s = rig(make({ drawUntilPlayable: true }), { hands: { A: ['B9a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'], drawPile: ['G8a', 'Y8a', 'R2a', 'B1a'] });
|
||
s = act(s, 'A', { type: 'draw' });
|
||
expect(ids(s, 'A')).toEqual(['B9a', 'G8a', 'Y8a', 'R2a']);
|
||
expect(s.phase).toEqual({ kind: 'afterDraw', drawnCardId: 'R2a' });
|
||
});
|
||
|
||
test('the discard pile (all but the top) is shuffled into an empty draw pile', () => {
|
||
let s = rig(make(), { hands: { A: ['B9a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R1a', 'R2a', 'R5a'], drawPile: [] });
|
||
const rest = unoDeck().filter((c) => !['B9a', 'G2a', 'Y3a', 'R1a', 'R2a', 'R5a'].includes(c.id));
|
||
s.hands.C!.push(...rest);
|
||
s = act(s, 'A', { type: 'draw' });
|
||
expect(s.discard.map((c) => c.id)).toEqual(['R5a']);
|
||
expect(s.hands.A).toHaveLength(2);
|
||
expect(s.log.some((e) => e.t === 'reshuffle')).toBe(true);
|
||
expect(cardTotal(s)).toBe(108);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- wild draw four
|
||
|
||
describe('와일드 드로우4와 도전 (§5.3)', () => {
|
||
test('strict rule: refused while holding the colour; allowed otherwise, next draws 4 and is skipped', () => {
|
||
const o = { wild4Rule: 'strict' as const };
|
||
const s = rig(make(o), { hands: { A: ['F1', 'R1a', 'B2a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
expect(reject(s, 'A', { type: 'play', cardId: 'F1', color: 'B' })).toBe('지금 색 카드가 손에 있으면 와일드 드로우4를 낼 수 없어요.');
|
||
// Same number of another colour or a wild doesn't count.
|
||
let t = rig(make(o), { hands: { A: ['F1', 'B5a', 'W1'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
t = play(t, 'A', 'F1', { color: 'B' });
|
||
expect(t.hands.B).toHaveLength(5);
|
||
expect(t.current).toBe('C');
|
||
expect(t.color).toBe('B');
|
||
});
|
||
|
||
test('challenge rule: a bluff may be played; the view warns about it', () => {
|
||
const s = rig(make(), { hands: { A: ['F1', 'R1a', 'B2a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
const v = uno.view(s, 'A').my!;
|
||
expect(v.playable).toContain('F1');
|
||
expect(v.bluff).toEqual(['F1']);
|
||
expect(v.hints.F1).toContain('도전받으면');
|
||
const t = play(s, 'A', 'F1', { color: 'G' });
|
||
expect(t.phase).toMatchObject({ kind: 'wild4', by: 'A', target: 'B', illegal: true });
|
||
expect(t.pending).toBe(4);
|
||
expect(uno.view(t, 'B').my!.canChallenge).toBe(true);
|
||
// The secret flag is not in any view.
|
||
expect(JSON.stringify(uno.view(t, 'B'))).not.toContain('illegal');
|
||
});
|
||
|
||
test('challenge won: the player of the card draws 4, the challenger sees the hand and plays normally', () => {
|
||
let s = rig(make(), { hands: { A: ['F1', 'R1a', 'B2a'], B: ['G2a', 'Y4a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'F1', { color: 'G' });
|
||
s = act(s, 'B', { type: 'challenge' });
|
||
expect(s.hands.A).toHaveLength(6);
|
||
expect(s.hands.B).toHaveLength(2);
|
||
expect(s.current).toBe('B');
|
||
expect(s.color).toBe('G');
|
||
expect(uno.view(s, 'B').reveal).toMatchObject({ by: 'A', illegal: true });
|
||
expect(uno.view(s, 'B').reveal!.cards).toHaveLength(2);
|
||
expect(uno.view(s, 'C').reveal).toBeNull();
|
||
expect(uno.view(s, null).reveal).toBeNull();
|
||
// The reveal goes away with the challenger's next turn action.
|
||
s = play(s, 'B', 'G2a');
|
||
expect(s.reveal).toBeNull();
|
||
});
|
||
|
||
test('challenge lost: the challenger draws 6 and is skipped; accepting: draws 4 and is skipped', () => {
|
||
const base = rig(make(), { hands: { A: ['F1', 'B1a', 'B2a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
const s = play(base, 'A', 'F1', { color: 'B' });
|
||
const lost = act(s, 'B', { type: 'challenge' });
|
||
expect(lost.hands.B).toHaveLength(7);
|
||
expect(lost.current).toBe('C');
|
||
expect(lost.hands.A).toHaveLength(2);
|
||
const accepted = act(s, 'B', { type: 'accept' });
|
||
expect(accepted.hands.B).toHaveLength(5);
|
||
expect(accepted.current).toBe('C');
|
||
expect(accepted.reveal).toBeNull();
|
||
});
|
||
|
||
test('(house rule) stacking: 드로우2 on 드로우2, 와일드 드로우4 on both; drawing takes the whole stack', () => {
|
||
const o = { stacking: true };
|
||
let s = rig(make(o), { hands: { A: ['RDa', 'R1a'], B: ['BDa', 'B1a'], C: ['Y3a', 'G4a'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'RDa');
|
||
expect(s.current).toBe('B');
|
||
expect(s.pending).toBe(2);
|
||
expect(uno.view(s, 'B').my!.playable).toEqual(['BDa']);
|
||
expect(uno.view(s, 'B').my!.drawCount).toBe(2);
|
||
s = play(s, 'B', 'BDa');
|
||
expect(s.pending).toBe(4);
|
||
expect(reject(s, 'C', { type: 'play', cardId: 'Y3a' })).toBe('드로우2나 와일드 드로우4로 쌓거나 카드를 뽑으세요.');
|
||
s = act(s, 'C', { type: 'draw' });
|
||
expect(s.hands.C).toHaveLength(6);
|
||
expect(s.current).toBe('A');
|
||
expect(s.pending).toBe(0);
|
||
// Without stacking a 드로우2 can't answer: the cards are drawn at once.
|
||
let off = rig(make(), { hands: { A: ['RDa', 'R1a'], B: ['BDa', 'B1a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
off = play(off, 'A', 'RDa');
|
||
expect(off.hands.B).toHaveLength(4);
|
||
expect(off.current).toBe('C');
|
||
});
|
||
|
||
test('(house rule) stacking a 와일드 드로우4 during the challenge choice', () => {
|
||
let s = rig(make({ stacking: true }), { hands: { A: ['F1', 'B1a', 'B2a'], B: ['F2', 'G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'F1', { color: 'B' });
|
||
expect(uno.view(s, 'B').my!.playable).toEqual(['F2']);
|
||
s = play(s, 'B', 'F2', { color: 'Y' });
|
||
expect(s.phase).toMatchObject({ kind: 'wild4', by: 'B', target: 'C' });
|
||
s = act(s, 'C', { type: 'accept' });
|
||
expect(s.hands.C).toHaveLength(9);
|
||
expect(s.current).toBe('A');
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- uno call
|
||
|
||
describe('"우노!" 외치기 (§5.4)', () => {
|
||
test('calling while playing the second-to-last card: safe', () => {
|
||
let s = rig(make(), { hands: { A: ['R1a', 'R2a'], B: ['G2a', 'G3a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'R1a', { uno: true });
|
||
expect(s.unoWindow).toEqual({ player: 'A', declared: true });
|
||
expect(reject(s, 'C', { type: 'catchUno' })).toBe('지금은 잡을 사람이 없어요.');
|
||
expect(uno.view(s, 'B').seats.find((x) => x.id === 'A')!.uno).toBe('declared');
|
||
});
|
||
|
||
test('missed call: anyone else can catch it (+2) until the next turn action; the owner can still call first', () => {
|
||
let s = rig(make(), { hands: { A: ['R1a', 'R2a'], B: ['G2a', 'G3a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'R1a');
|
||
expect(s.unoWindow).toEqual({ player: 'A', declared: false });
|
||
expect(uno.view(s, 'C').my!.canCatchUno).toBe(true);
|
||
expect(uno.view(s, 'A').my!.canCatchUno).toBe(false);
|
||
expect(uno.view(s, 'A').my!.canCallUno).toBe(true);
|
||
expect(uno.view(s, null).my).toBeNull();
|
||
// C (not the next player) catches it.
|
||
const caught = act(s, 'C', { type: 'catchUno' });
|
||
expect(caught.hands.A).toHaveLength(3);
|
||
expect(caught.unoWindow).toBeNull();
|
||
expect(caught.current).toBe('B');
|
||
expect(caught.log.at(-2)).toMatchObject({ t: 'caught', p: 'A', by: 'C', n: 2 });
|
||
// The owner calls in time.
|
||
const called = act(s, 'A', { type: 'callUno' });
|
||
expect(called.unoWindow).toEqual({ player: 'A', declared: true });
|
||
expect(reject(called, 'B', { type: 'catchUno' })).not.toBeNull();
|
||
// The next player's turn action closes the window.
|
||
const later = act(s, 'B', { type: 'draw' });
|
||
expect(later.unoWindow).toBeNull();
|
||
expect(reject(later, 'C', { type: 'catchUno' })).not.toBeNull();
|
||
expect(reject(later, 'A', { type: 'callUno' })).not.toBeNull();
|
||
});
|
||
|
||
test('2 players: a 스킵 down to one card comes back to me; the other player can still catch it first', () => {
|
||
let s = rig(make({}, ['A', 'B']), { hands: { A: ['RSa', 'R2a'], B: ['G2a', 'G3a'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'RSa');
|
||
expect(s.current).toBe('A');
|
||
expect(uno.view(s, 'B').my!.canCatchUno).toBe(true);
|
||
const caught = act(s, 'B', { type: 'catchUno' });
|
||
expect(caught.hands.A).toHaveLength(3);
|
||
expect(caught.current).toBe('A');
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- scoring
|
||
|
||
describe('점수와 끝 (§6)', () => {
|
||
test('going out: one game; the winner scores everyone else’s cards (numbers face value, symbols 20, wilds 50)', () => {
|
||
let s = rig(make(), { hands: { A: ['R1a'], B: ['G9a', 'BSa'], C: ['W1', 'F2', 'Y0'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'R1a');
|
||
expect(s.phase.kind).toBe('finished');
|
||
const r = uno.result(s)!;
|
||
expect(r.ranking).toEqual([['A'], ['B'], ['C']]);
|
||
expect(r.scores).toEqual({ A: 129, B: 0, C: 0 });
|
||
expect(r.scoreText).toEqual({ A: '129점', B: '남은 카드 29점', C: '남은 카드 100점' });
|
||
expect(r.summary).toContain('129점');
|
||
});
|
||
|
||
test('going out on a 드로우2: the next player still draws (the cards count)', () => {
|
||
let s = rig(make(), { hands: { A: ['RDa'], B: ['G9a'], C: ['Y1a'] }, discard: ['R5a'], drawPile: ['B5a', 'B6a', 'B7a'] });
|
||
s = play(s, 'A', 'RDa');
|
||
expect(s.hands.B!.map((c) => c.id)).toEqual(['G9a', 'B5a', 'B6a']);
|
||
expect(uno.result(s)!.scores!.A).toBe(9 + 5 + 6 + 1);
|
||
});
|
||
|
||
test('500 points: rounds go on, ready → next deal one seat on; first to 500 wins', () => {
|
||
let s = rig(make({ scoring: 'to500' }), { hands: { A: ['R1a'], B: ['W1', 'W2'], C: ['F1'] }, discard: ['R5a'] });
|
||
const starter = s.roundStarter;
|
||
s = play(s, 'A', 'R1a');
|
||
expect(s.phase.kind).toBe('roundEnd');
|
||
expect(s.scores.A).toBe(150);
|
||
expect(uno.view(s, 'B').my!.canReady).toBe(true);
|
||
for (const p of ['A', 'B']) s = act(s, p, { type: 'ready' });
|
||
expect(s.phase.kind).toBe('roundEnd');
|
||
s = act(s, 'C', { type: 'timeout' });
|
||
expect(s.round).toBe(2);
|
||
expect(s.roundStarter).toBe(s.seats[(s.seats.indexOf(starter) + 1) % 3]!);
|
||
expect(cardTotal(s)).toBe(108);
|
||
for (const p of s.seats) expect(s.hands[p]).toHaveLength(p === s.roundStarter && s.discard[0]!.kind === 'draw2' ? 9 : 7);
|
||
s.scores.A = 490;
|
||
s = rig(s, { hands: { A: ['R1a'], B: ['G9a', 'B5a'], C: ['Y1a'] }, discard: ['R5a'] });
|
||
s = play(s, 'A', 'R1a');
|
||
expect(s.phase.kind).toBe('finished');
|
||
const r = uno.result(s)!;
|
||
expect(r.ranking[0]).toEqual(['A']);
|
||
expect(r.scoreText!.A).toBe('505점');
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- timer and leaving
|
||
|
||
describe('시간 초과와 나가기 (§8.5)', () => {
|
||
test('timeout plays a playable card, a coloured one before a wild', () => {
|
||
let s = rig(make(), { hands: { A: ['W1', 'G5a', 'B9a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
s = act(s, 'A', { type: 'timeout' });
|
||
expect(topId(s)).toBe('G5a');
|
||
expect(s.timeoutsInRow.A).toBe(1);
|
||
expect(s.current).toBe('B');
|
||
});
|
||
|
||
test('timeout with only a wild: the colour is the one held most', () => {
|
||
let s = rig(make(), { hands: { A: ['W1', 'B1a', 'B9a', 'G9a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
s = act(s, 'A', { type: 'timeout' });
|
||
expect(topId(s)).toBe('W1');
|
||
expect(s.color).toBe('B');
|
||
});
|
||
|
||
test('timeout with nothing playable draws and plays the drawn card if it fits; a drawn bluff is kept', () => {
|
||
let s = rig(make(), { hands: { A: ['R9a', 'B1a'], B: ['G2a'], C: ['Y3a'] }, discard: ['G5a'], drawPile: ['G7a', 'Y1a'] });
|
||
s = act(s, 'A', { type: 'timeout' });
|
||
expect(topId(s)).toBe('G7a');
|
||
expect(ids(s, 'A')).toEqual(['R9a', 'B1a']);
|
||
let t = rig(make(), { hands: { A: ['R9a'], B: ['G2a'], C: ['Y3a'] }, discard: ['G5a'], drawPile: ['Y1a'] });
|
||
t = act(t, 'A', { type: 'timeout' });
|
||
expect(ids(t, 'A')).toEqual(['R9a', 'Y1a']);
|
||
expect(t.current).toBe('B');
|
||
// Drawn 와일드 드로우4 while holding the colour: playable by hand (a bluff), but the timer keeps it.
|
||
let b = rig(make(), { hands: { A: ['G9a', 'B1a'], B: ['G2a'], C: ['Y3a'] }, discard: ['G5a'], drawPile: ['F1'] });
|
||
b = act(b, 'A', { type: 'draw' });
|
||
expect(b.phase).toEqual({ kind: 'afterDraw', drawnCardId: 'F1' });
|
||
b = act(b, 'A', { type: 'timeout' });
|
||
expect(ids(b, 'A')).toContain('F1');
|
||
expect(b.current).toBe('B');
|
||
// Only a fair 와일드 드로우4 to play: the timer plays it with the colour held most.
|
||
let f = rig(make(), { hands: { A: ['F1', 'B1a', 'B2a', 'R1a'], B: ['G2a'], C: ['Y3a'] }, discard: ['G5a'] });
|
||
f = act(f, 'A', { type: 'timeout' });
|
||
expect(topId(f)).toBe('F1');
|
||
expect(f.color).toBe('B');
|
||
expect(f.phase).toMatchObject({ kind: 'wild4', illegal: false });
|
||
});
|
||
|
||
test('timeout answers: start colour = most held, challenge = accept, after a draw = play it', () => {
|
||
let s = seedWithStart('wild');
|
||
const first = s.roundStarter;
|
||
s.hands[first] = ['Y1a', 'Y2a', 'B3a'].map(card);
|
||
s = act(s, first, { type: 'timeout' });
|
||
expect(s.color).toBe('Y');
|
||
let w = rig(make(), { hands: { A: ['F1', 'B1a', 'B2a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
w = play(w, 'A', 'F1', { color: 'B' });
|
||
w = act(w, 'B', { type: 'timeout' });
|
||
expect(w.hands.B).toHaveLength(5);
|
||
let d = rig(make(), { hands: { A: ['B9a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'], drawPile: ['R7a'] });
|
||
d = act(d, 'A', { type: 'draw' });
|
||
d = act(d, 'A', { type: 'timeout' });
|
||
expect(topId(d)).toBe('R7a');
|
||
});
|
||
|
||
test('three timeouts in a row → away (5 s turns) until the player acts', () => {
|
||
let s = rig(make(), { hands: { A: ['B9a', 'B8a', 'B7a', 'B6a'], B: ['G2a', 'G3a', 'G4a'], C: ['Y3a', 'Y4a', 'Y5a'] }, discard: ['R5a'] });
|
||
for (let i = 0; i < 3; i++) {
|
||
s.current = 'A';
|
||
s.phase = { kind: 'turn' };
|
||
s = act(s, 'A', { type: 'timeout' });
|
||
}
|
||
expect(s.away.A).toBe(true);
|
||
s.current = 'A';
|
||
s.phase = { kind: 'turn' };
|
||
expect(uno.view(s, 'A').deadlineTotalMs).toBe(5000);
|
||
s = act(s, 'A', { type: 'draw' });
|
||
expect(s.away.A).toBe(false);
|
||
});
|
||
|
||
test('leaving: the hand goes under the draw pile, the turn moves on; the last one left wins', () => {
|
||
let s = rig(make(), { hands: { A: ['R1a', 'R2a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
expect(uno.onLeave!(s, 'A')).toEqual({ type: 'leave' });
|
||
s = act(s, 'A', { type: 'leave' });
|
||
expect(s.hands.A).toEqual([]);
|
||
expect(s.current).toBe('B');
|
||
expect(cardTotal(s)).toBe(108);
|
||
expect(uno.onLeave!(s, 'A')).toBeNull();
|
||
s = act(s, 'B', { type: 'leave' });
|
||
expect(s.phase.kind).toBe('finished');
|
||
expect(uno.result(s)!.ranking).toEqual([['C'], ['B'], ['A']]);
|
||
// The player of a 와일드 드로우4 leaves before the answer: the target just plays on.
|
||
let w = rig(make(), { hands: { A: ['F1', 'B1a', 'B2a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||
w = play(w, 'A', 'F1', { color: 'B' });
|
||
w = act(w, 'A', { type: 'leave' });
|
||
expect(w.phase.kind).toBe('turn');
|
||
expect(w.current).toBe('B');
|
||
expect(w.pending).toBe(0);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- validation & leaks
|
||
|
||
describe('검증과 정보 유출 (§8.3)', () => {
|
||
test('not my turn / card not in hand / resent packet are refused and change nothing', () => {
|
||
const s = rig(make(), { hands: { A: ['R9a', 'G4a'], B: ['R8a', 'B9a'] }, discard: ['R5a'] });
|
||
const before = JSON.stringify(s);
|
||
expect(reject(s, 'B', { type: 'play', cardId: 'R8a' })).toBe('지금은 내 차례가 아니에요.');
|
||
expect(reject(s, 'A', { type: 'play', cardId: 'R8a' })).toBe('손에 없는 카드예요.');
|
||
expect(reject(s, 'Z', { type: 'draw' })).toBe('이 게임의 플레이어가 아니에요.');
|
||
expect(reject(s, 'A', { type: 'pass' })).not.toBeNull();
|
||
expect(reject(s, 'A', { type: 'challenge' })).not.toBeNull();
|
||
expect(JSON.stringify(s)).toBe(before);
|
||
const t = play(s, 'A', 'R9a');
|
||
t.current = 'A';
|
||
expect(reject(t, 'A', { type: 'play', cardId: 'R9a' })).toBe('손에 없는 카드예요.');
|
||
});
|
||
|
||
test('options: defaults and Korean metadata; client schema has no system actions', () => {
|
||
expect(uno.defaultOptions).toEqual({ scoring: 'single', wild4Rule: 'challenge', stacking: false, drawUntilPlayable: false, turnSeconds: 20 });
|
||
const shape = (uno.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(uno.actionSchema.safeParse({ type: 'timeout' }).success).toBe(false);
|
||
expect(uno.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
|
||
expect(uno.actionSchema.safeParse({ type: 'play', cardId: 'W1', color: 'R', uno: true }).success).toBe(true);
|
||
expect(uno.actionSchema.safeParse({ type: 'startColor', color: 'X' }).success).toBe(false);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- properties
|
||
|
||
const TOKEN = /"[^"\\]*"/g;
|
||
|
||
function checkLeaks(s: UnoState, players: PlayerId[]): void {
|
||
const owners = new Map<string, PlayerId>();
|
||
for (const owner of players) for (const secret of uno.secretsOf!(s, owner)) owners.set(`"${secret}"`, owner);
|
||
for (const viewer of [...players, null]) {
|
||
for (const tok of JSON.stringify(uno.view(s, viewer)).match(TOKEN) ?? []) {
|
||
const of = owners.get(tok);
|
||
// Draw-pile ids are every player's secret (owner = last listed): only the holder of a hand card may see it.
|
||
if (of !== undefined && !(viewer && s.hands[viewer]!.some((c) => `"${c.id}"` === tok))) throw new Error(`leak ${tok} to ${viewer}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
function invariants(s: UnoState): void {
|
||
if (cardTotal(s) !== 108) throw new Error(`cards not conserved: ${cardTotal(s)}`);
|
||
const seen = new Set<string>();
|
||
for (const c of [...s.drawPile, ...s.discard, ...s.seats.flatMap((p) => s.hands[p]!)]) {
|
||
if (seen.has(c.id)) throw new Error(`duplicate card ${c.id}`);
|
||
seen.add(c.id);
|
||
}
|
||
if (s.pending < 0) throw new Error('negative pending');
|
||
if (s.unoWindow && s.hands[s.unoWindow.player]!.length !== 1) throw new Error('uno window without exactly one card');
|
||
if (s.phase.kind !== 'finished' && s.phase.kind !== 'roundEnd' && s.leftOrder.includes(s.current)) throw new Error('current player has left');
|
||
if (s.phase.kind === 'turn' && s.color === null) throw new Error('no colour to follow');
|
||
}
|
||
|
||
function playout(players: PlayerId[], options: UnoOptions, seed: RngState, maxSteps: number): { finished: boolean; trace: string; final: UnoState } {
|
||
const r = SeededRng.fromSeed(seed);
|
||
const chooser = SeededRng.fromSeed([seed[3], seed[2], seed[1], seed[0] ^ 0x9e3779b9]);
|
||
let now = 1_700_000_000_000;
|
||
let s = uno.setup({ players, options, rng: r, now });
|
||
const trace: string[] = [];
|
||
for (let step = 0; step < maxSteps; step++) {
|
||
invariants(s);
|
||
if (step % 10 === 0) checkLeaks(s, players);
|
||
for (const p of uno.timeoutPlayers!(s)) {
|
||
const v = uno.validate(s, p, uno.onTimeout(s, p));
|
||
if (!v.ok) throw new Error(`onTimeout rejected for ${p}: ${v.reason}`);
|
||
}
|
||
if (uno.result(s)) return { finished: true, trace: trace.join(';'), final: s };
|
||
// Everyone may act (catching a missed call is open to all), and now and then the clock runs out.
|
||
const actives = chooser.int(8) === 0 ? uno.timeoutPlayers!(s) : players;
|
||
const actor = actives[chooser.int(actives.length)]!;
|
||
const legal = uno.legalActions!(s, actor);
|
||
if (!legal.length) continue;
|
||
const action = actives === players ? legal[chooser.int(legal.length)]! : uno.onTimeout(s, actor);
|
||
const v = uno.validate(s, actor, action);
|
||
if (!v.ok) throw new Error(`generated action rejected: ${v.reason} ${JSON.stringify(action)}`);
|
||
now += 1000;
|
||
const out = uno.apply(s, actor, action, { rng: r, now });
|
||
if (JSON.stringify(out.events).includes('"id"')) throw new Error('event carries a card id');
|
||
s = out.state;
|
||
trace.push(`${actor}:${JSON.stringify(action)}`);
|
||
}
|
||
return { finished: false, trace: trace.join(';'), final: s };
|
||
}
|
||
|
||
const PRESETS: Partial<UnoOptions>[] = [{}, { wild4Rule: 'strict' }, { stacking: true }, { drawUntilPlayable: true, stacking: true }, { scoring: 'to500' }];
|
||
const SEEDS = playoutSeeds(300);
|
||
|
||
describe(`random playouts (${SEEDS} seeds)`, () => {
|
||
test('every game finishes, cards conserved, no leaks, onTimeout always legal, deterministic', () => {
|
||
for (let i = 1; i <= SEEDS; i++) {
|
||
const n = 2 + (i % 9);
|
||
const players = Array.from({ length: n }, (_, k) => `P${k}`);
|
||
const options = uno.optionsSchema.parse(PRESETS[i % PRESETS.length]!);
|
||
const a = playout(players, options, seedN(i), 60_000);
|
||
if (!a.finished) throw new Error(`seed ${i} (${n} players) did not finish`);
|
||
expect(uno.result(a.final)!.ranking.flat().sort()).toEqual([...players].sort());
|
||
if (i % 10 === 0) expect(playout(players, options, seedN(i), 60_000).trace).toBe(a.trace);
|
||
}
|
||
}, 180_000);
|
||
|
||
test.each([
|
||
[2, {}],
|
||
[3, { stacking: true }],
|
||
[4, {}],
|
||
[6, { wild4Rule: 'strict', drawUntilPlayable: true }],
|
||
] as const)('engine randomPlayout (per-step leak / round-trip checks): %i players %o', (n, opts) => {
|
||
const players = Array.from({ length: n }, (_, k) => `P${k}`);
|
||
const options = uno.optionsSchema.parse(opts);
|
||
for (let i = 1; i <= playoutSeeds(3); i++) {
|
||
const a = randomPlayout(uno, { players, options, seed: seedN(100 + i), maxSteps: 60_000, invariant: (st) => invariants(st as UnoState), maxApplyMs: 30 });
|
||
expect(a.finished).toBe(true);
|
||
}
|
||
}, 60_000);
|
||
});
|