우노: 공식 규칙 엔진·컴퓨터 상대·화면·도움말·문서·E2E
- 규칙 모듈 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>
This commit is contained in:
124
packages/games/src/uno/bot.test.ts
Normal file
124
packages/games/src/uno/bot.test.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN } from '@bg/engine';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { botPlayout } from '../bots/playout';
|
||||
import { catchChance, forgetChance } from './bot';
|
||||
import { uno, unoDeck, type UnoOptions, type UnoState } from './index';
|
||||
|
||||
const ALL = unoDeck();
|
||||
const card = (id: string) => ALL.find((x) => x.id === id)!;
|
||||
|
||||
function make(opts: Partial<UnoOptions> = {}, players = ['A', 'B', 'C']): UnoState {
|
||||
return uno.setup({ players, options: uno.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
|
||||
}
|
||||
|
||||
function rig(s: UnoState, hands: Record<string, string[]>, discard: string[]): UnoState {
|
||||
for (const p of s.seats) s.hands[p] = (hands[p] ?? []).map(card);
|
||||
s.discard = discard.map(card);
|
||||
const t = s.discard[s.discard.length - 1]!;
|
||||
s.color = 'color' in t ? t.color : 'R';
|
||||
s.current = s.seats[0]!;
|
||||
s.phase = { kind: 'turn' };
|
||||
s.pending = 0;
|
||||
s.unoWindow = null;
|
||||
const used = new Set([...Object.values(hands).flat(), ...discard]);
|
||||
s.drawPile = unoDeck().filter((c) => !used.has(c.id));
|
||||
return s;
|
||||
}
|
||||
|
||||
const decide = (s: UnoState, p = 'A', level?: number, random: () => number = () => 0.5) =>
|
||||
decideBotAction(uno, s, p, { now: 0, random, level }) as Record<string, unknown>;
|
||||
|
||||
const seq = (seed: number) => {
|
||||
const r = SeededRng.fromSeed(seedN(seed));
|
||||
return () => r.next();
|
||||
};
|
||||
|
||||
describe('uno bot', () => {
|
||||
test('plays a matching card and keeps the wild', () => {
|
||||
const s = rig(make(), { A: ['W1', 'R3a', 'G9a'], B: ['G1a', 'G2a', 'G3a'], C: ['Y1a', 'Y2a', 'Y3a'] }, ['R5a']);
|
||||
expect(decide(s)).toEqual({ type: 'play', cardId: 'R3a' });
|
||||
});
|
||||
|
||||
test('a wild picks the colour it holds most of', () => {
|
||||
const s = rig(make(), { A: ['W1', 'B3a', 'B5a', 'G1a'], B: ['R1a', 'R2a', 'R3a'], C: ['Y1a', 'Y2a', 'Y3a'] }, ['R9a']);
|
||||
expect(decide(s)).toMatchObject({ type: 'play', cardId: 'W1', color: 'B' });
|
||||
});
|
||||
|
||||
test('hard: saves a 드로우2 while the next player is far from out, plays it when they are close', () => {
|
||||
const far = rig(make(), { A: ['RDa', 'R3a', 'G9a'], B: ['G1a', 'G2a', 'G3a', 'G4a'], C: ['Y1a', 'Y2a', 'Y3a'] }, ['R5a']);
|
||||
expect(decide(far, 'A', 55)).toMatchObject({ cardId: 'R3a' });
|
||||
const near = rig(make(), { A: ['RDa', 'R3a', 'G9a'], B: ['G1a', 'G2a'], C: ['Y1a', 'Y2a', 'Y3a'] }, ['R5a']);
|
||||
expect(decide(near, 'A', 55)).toMatchObject({ cardId: 'RDa' });
|
||||
});
|
||||
|
||||
test('hard never bluffs a 와일드 드로우4; the only fair one is played', () => {
|
||||
const s = rig(make(), { A: ['F1', 'R3a', 'G9a'], B: ['G1a', 'G2a'], C: ['Y1a', 'Y2a', 'Y3a'] }, ['R5a']);
|
||||
for (let i = 1; i <= 30; i++) expect(decide(s, 'A', 60, seq(i)).cardId).not.toBe('F1');
|
||||
const fair = rig(make(), { A: ['F1', 'G9a'], B: ['B1a', 'B2a', 'B3a'], C: ['Y1a', 'Y2a', 'Y3a'] }, ['R5a']);
|
||||
expect(decide(fair, 'A', 60)).toMatchObject({ type: 'play', cardId: 'F1', color: 'G', uno: true });
|
||||
});
|
||||
|
||||
test('calls "우노!" with the second-to-last card; easy computers sometimes forget, hard ones never', () => {
|
||||
const s = rig(make(), { A: ['R3a', 'G9a'], B: ['G1a', 'G2a', 'G3a'], C: ['Y1a', 'Y2a', 'Y3a'] }, ['R5a']);
|
||||
expect(decide(s)).toEqual({ type: 'play', cardId: 'R3a', uno: true });
|
||||
let forgot = 0;
|
||||
for (let i = 1; i <= 400; i++) if (!decide(s, 'A', 1, seq(i)).uno) forgot++;
|
||||
expect(forgot).toBeGreaterThan(80);
|
||||
expect(forgot).toBeLessThan(220);
|
||||
for (let i = 1; i <= 100; i++) expect(decide(s, 'A', 60, seq(i)).uno).toBe(true);
|
||||
expect(forgetChance(1)).toBeCloseTo(0.35);
|
||||
expect(forgetChance(20)).toBeCloseTo(0.15);
|
||||
expect(forgetChance(41)).toBe(0);
|
||||
});
|
||||
|
||||
test('catches a missed call when its turn comes up (hard always, easy sometimes)', () => {
|
||||
let s = rig(make(), { A: ['R3a', 'G9a'], B: ['G1a', 'G2a', 'G3a'], C: ['Y1a', 'Y2a', 'Y3a'] }, ['R5a']);
|
||||
s = uno.apply(s, 'A', { type: 'play', cardId: 'R3a' }, { rng: SeededRng.fromSeed(seedN(2)), now: 1 }).state;
|
||||
expect(s.unoWindow).toEqual({ player: 'A', declared: false });
|
||||
expect(decide(s, 'B', 60)).toEqual({ type: 'catchUno' });
|
||||
let caught = 0;
|
||||
for (let i = 1; i <= 400; i++) if (decide(s, 'B', 1, seq(i)).type === 'catchUno') caught++;
|
||||
expect(caught).toBeGreaterThan(80);
|
||||
expect(caught).toBeLessThan(170);
|
||||
expect(catchChance(41)).toBe(1);
|
||||
// A computer that isn't up next is not asked (the game doesn't wait on it).
|
||||
expect(uno.activePlayers(s)).toEqual(['B']);
|
||||
});
|
||||
|
||||
test('challenge: hard challenges a big hand, accepts a small one; stacks a 와일드 드로우4 when allowed', () => {
|
||||
const play = (s: UnoState) => uno.apply(s, 'A', { type: 'play', cardId: 'F1', color: 'B' }, { rng: SeededRng.fromSeed(seedN(3)), now: 1 }).state;
|
||||
const big = play(rig(make(), { A: ['F1', 'R1a', 'R2a', 'G3a', 'G4a'], B: ['G1a', 'G2a'], C: ['Y1a'] }, ['R5a']));
|
||||
expect(decide(big, 'B', 60)).toEqual({ type: 'challenge' });
|
||||
const small = play(rig(make(), { A: ['F1', 'G3a', 'G4a'], B: ['G1a', 'G2a'], C: ['Y1a'] }, ['R5a']));
|
||||
expect(decide(small, 'B', 60)).toEqual({ type: 'accept' });
|
||||
const stack = play(rig(make({ stacking: true }), { A: ['F1', 'G3a', 'G4a'], B: ['F2', 'G2a', 'B1a'], C: ['Y1a'] }, ['R5a']));
|
||||
expect(decide(stack, 'B', 60)).toMatchObject({ type: 'play', cardId: 'F2' });
|
||||
});
|
||||
|
||||
test('start colour: the one it holds most of', () => {
|
||||
const s = rig(make(), { A: ['Y1a', 'Y2a', 'B3a'], B: ['G1a'], C: ['Y3a'] }, ['W1']);
|
||||
s.color = null;
|
||||
s.phase = { kind: 'startColor' };
|
||||
expect(decide(s)).toEqual({ type: 'startColor', color: 'Y' });
|
||||
});
|
||||
|
||||
const modes: [string, Partial<UnoOptions>][] = [
|
||||
['official', {}],
|
||||
['strict +4, stacking', { wild4Rule: 'strict', stacking: true }],
|
||||
['draw until playable', { drawUntilPlayable: true }],
|
||||
['500 points', { scoring: 'to500' }],
|
||||
];
|
||||
for (const [name, opts] of modes) {
|
||||
test(`bots finish a game: ${name}`, () => {
|
||||
const options = uno.optionsSchema.parse(opts);
|
||||
for (let seed = 1; seed <= 2; seed++) {
|
||||
for (const level of [5, 30, 55]) {
|
||||
const r = botPlayout(uno as never, { players: ['h', 'bot:1', 'bot:2', 'bot:3'], options, seed: seedN(seed), isBot: (p) => p.startsWith('bot:'), level });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
}
|
||||
}
|
||||
}, 30_000);
|
||||
}
|
||||
});
|
||||
128
packages/games/src/uno/bot.ts
Normal file
128
packages/games/src/uno/bot.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* 우노 computer player (docs/games/uno.md §9.1). Plays a matching card, keeping wilds for later; saves 드로우2 /
|
||||
* 와일드 드로우4 for when the next player is close to going out (stronger levels save more); a chosen colour is the
|
||||
* one it holds most of. The level decides the human parts: easy computers now and then forget to call "우노!",
|
||||
* notice someone else's missed call less often, challenge at random and may bluff a 와일드 드로우4; hard ones never
|
||||
* bluff and challenge when the player of the card likely still held the colour.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import type { BotLevel } from '../bots/persona';
|
||||
import { humanBest, pick, playable, typeOf } from '../bots/policy';
|
||||
import { COLORS, majorityColor, type Color, type UnoCard } from './cards';
|
||||
import type { PlayAction, UnoAction, UnoView } from './types';
|
||||
|
||||
/** Chance to forget "우노!" when playing down to one card: 35% at level 1, 15% at 20, gone by 40. */
|
||||
export function forgetChance(level: BotLevel | undefined): number {
|
||||
if (level === undefined) return 0;
|
||||
if (level <= 20) return 0.35 - (0.2 * (Math.max(1, level) - 1)) / 19;
|
||||
return level < 40 ? (0.05 * (40 - level)) / 20 : 0;
|
||||
}
|
||||
|
||||
/** Chance to catch someone's missed "우노!" when its own turn comes up: 30% at level 1 … always from level 41. */
|
||||
export function catchChance(level: BotLevel | undefined): number {
|
||||
if (level === undefined) return 1;
|
||||
return Math.min(1, 0.3 + (0.7 * (Math.max(1, level) - 1)) / 40);
|
||||
}
|
||||
|
||||
const hard = (level: BotLevel | undefined) => level === undefined || level > 40;
|
||||
const easy = (level: BotLevel | undefined) => level !== undefined && level <= 20;
|
||||
|
||||
/** Seat that plays after me (skipping players who left). */
|
||||
function nextSeat(view: UnoView): UnoView['seats'][number] | undefined {
|
||||
const n = view.seats.length;
|
||||
const i = view.seats.findIndex((s) => s.id === view.me);
|
||||
for (let k = 1; k < n; k++) {
|
||||
const s = view.seats[(((i + k * view.direction) % n) + n) % n]!;
|
||||
if (!s.left) return s;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function chooseColor(rest: UnoCard[], level: BotLevel | undefined, random: () => number): Color {
|
||||
if (easy(level) && random() < 0.3) return pick(COLORS, random);
|
||||
// Ties between colours are broken at random so the choice doesn't give the hand away.
|
||||
const order = [...COLORS].sort(() => random() - 0.5);
|
||||
return majorityColor(rest, order);
|
||||
}
|
||||
|
||||
function shouldChallenge(view: UnoView, level: BotLevel | undefined, random: () => number): boolean {
|
||||
const by = view.seats.find((s) => s.id === view.wild4?.by);
|
||||
if (!by) return false;
|
||||
// Wrong: 2 more cards. Right: the player of the card takes the 4. Worth it when they likely held the colour.
|
||||
if (hard(level)) return by.cards >= 4;
|
||||
return random() < (easy(level) ? 0.1 : 0.25);
|
||||
}
|
||||
|
||||
export const unoBot: BotStrategy<UnoView, UnoAction> = ({ view, legal, random, level }) => {
|
||||
const types = new Set(legal.map(typeOf));
|
||||
if (types.has('ready')) return { type: 'ready' };
|
||||
const hand = view.my?.hand ?? [];
|
||||
if (types.has('startColor')) return { type: 'startColor', color: chooseColor(hand, level, random) };
|
||||
// Its own call (a forgotten one is remembered when its turn comes back), then a catch when it notices.
|
||||
if (types.has('callUno')) return { type: 'callUno' };
|
||||
if (types.has('catchUno') && random() < catchChance(level)) return { type: 'catchUno' };
|
||||
|
||||
const byId = new Map(hand.map((c) => [c.id, c]));
|
||||
const ids = [...new Set((legal.filter((a) => a.type === 'play') as PlayAction[]).map((a) => a.cardId))];
|
||||
const forgot = hand.length === 2 && random() < forgetChance(level);
|
||||
const finish = (id: string): PlayAction => {
|
||||
const rest = hand.filter((c) => c.id !== id);
|
||||
const c = byId.get(id)!;
|
||||
return {
|
||||
type: 'play',
|
||||
cardId: id,
|
||||
...(c.kind === 'wild' || c.kind === 'wild4' ? { color: chooseColor(rest, level, random) } : {}),
|
||||
...(hand.length === 2 && !forgot ? { uno: true } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
if (types.has('challenge')) {
|
||||
const stack = ids.find((id) => byId.get(id)?.kind === 'wild4');
|
||||
if (stack) return finish(stack);
|
||||
return { type: shouldChallenge(view, level, random) ? 'challenge' : 'accept' };
|
||||
}
|
||||
if (!ids.length) {
|
||||
if (types.has('pass')) return { type: 'pass' };
|
||||
if (types.has('draw')) return { type: 'draw' };
|
||||
return pick(playable(legal), random);
|
||||
}
|
||||
|
||||
const next = nextSeat(view);
|
||||
const nextNear = !!next && next.cards <= 2;
|
||||
const bluffs = new Set(view.my?.bluff ?? []);
|
||||
const score = (id: string): number => {
|
||||
const c = byId.get(id)!;
|
||||
const rest = hand.filter((x) => x.id !== id);
|
||||
if (rest.length === 0) return 100;
|
||||
let v = random() * 0.3;
|
||||
if (view.pending > 0) return v + 10; // stacking beats drawing the pile
|
||||
switch (c.kind) {
|
||||
case 'wild':
|
||||
v -= hard(level) ? 4 : 2.5;
|
||||
break;
|
||||
case 'wild4':
|
||||
v -= 4;
|
||||
if (bluffs.has(id)) v -= hard(level) ? 30 : easy(level) ? 1 : 6;
|
||||
if (nextNear) v += 4;
|
||||
break;
|
||||
case 'draw2':
|
||||
// Draw cards hurt most when the next player is about to go out: stronger computers save them for that.
|
||||
v += nextNear ? 4 : hard(level) ? -0.8 : 0.5;
|
||||
break;
|
||||
case 'skip':
|
||||
case 'reverse':
|
||||
v += nextNear ? 3 : 0.5;
|
||||
break;
|
||||
case 'num':
|
||||
v += c.value / 20; // high numbers first (they count against me if someone goes out)
|
||||
break;
|
||||
}
|
||||
// Keep my colour going: cards of the colour I hold most of.
|
||||
if ('color' in c) v += rest.filter((x) => 'color' in x && x.color === c.color).length * 0.3;
|
||||
return v;
|
||||
};
|
||||
const chosen = humanBest(ids, score, random, level, { small: 1, critical: 50 });
|
||||
// A drawn card that isn't worth playing now (a wild to keep, a bluff) stays in hand.
|
||||
if (types.has('pass') && score(chosen) < -5) return { type: 'pass' };
|
||||
return finish(chosen);
|
||||
};
|
||||
40
packages/games/src/uno/cards.ts
Normal file
40
packages/games/src/uno/cards.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* 우노 cards (docs/games/uno.md §3): the 108-card colour deck, card points and colour helpers are shared with
|
||||
* 원카드's 색깔 카드 mode (`../one-card/cards`, unchanged); only the names are UNO's own.
|
||||
*/
|
||||
import { COLORS, COLOR_KO, cardPoints, colorOf, unoDeck, type Color, type UnoCard } from '../one-card/cards';
|
||||
import type { CardFace } from './types';
|
||||
|
||||
export { COLORS, COLOR_KO, cardPoints, colorOf, unoDeck, type Color, type UnoCard };
|
||||
|
||||
export const isWild = (c: CardFace | UnoCard): boolean => c.kind === 'wild' || c.kind === 'wild4';
|
||||
export const isDrawCard = (c: CardFace | UnoCard): boolean => c.kind === 'draw2' || c.kind === 'wild4';
|
||||
|
||||
export const handPoints = (cards: readonly UnoCard[]): number => cards.reduce((a, c) => a + cardPoints(c), 0);
|
||||
|
||||
/** Korean name, e.g. "빨강 5", "파랑 스킵", "와일드 드로우4". */
|
||||
export function unoCardName(c: CardFace | UnoCard): string {
|
||||
switch (c.kind) {
|
||||
case 'num':
|
||||
return `${COLOR_KO[c.color]} ${c.value}`;
|
||||
case 'skip':
|
||||
return `${COLOR_KO[c.color]} 스킵`;
|
||||
case 'reverse':
|
||||
return `${COLOR_KO[c.color]} 리버스`;
|
||||
case 'draw2':
|
||||
return `${COLOR_KO[c.color]} 드로우2`;
|
||||
case 'wild':
|
||||
return '와일드';
|
||||
case 'wild4':
|
||||
return '와일드 드로우4';
|
||||
}
|
||||
}
|
||||
|
||||
/** Colour most common among `cards` (ties: R, Y, G, B order; no coloured card: R). Used by the timer and bots. */
|
||||
export function majorityColor(cards: readonly (CardFace | UnoCard)[], tieBreak: readonly Color[] = COLORS): Color {
|
||||
const n: Record<Color, number> = { R: 0, Y: 0, G: 0, B: 0 };
|
||||
for (const c of cards) if ('color' in c) n[c.color]++;
|
||||
let best = tieBreak[0]!;
|
||||
for (const k of tieBreak) if (n[k] > n[best]) best = k;
|
||||
return best;
|
||||
}
|
||||
895
packages/games/src/uno/index.ts
Normal file
895
packages/games/src/uno/index.ts
Normal file
@@ -0,0 +1,895 @@
|
||||
/** 우노 (docs/games/uno.md). Official Mattel rules with optional house rules. Pure and deterministic; state is JSON. */
|
||||
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine';
|
||||
import { COLORS, COLOR_KO, colorOf, handPoints, isWild, majorityColor, unoDeck, type Color, type UnoCard } from './cards';
|
||||
import {
|
||||
unoActionSchema,
|
||||
unoOptionsSchema,
|
||||
type CardFace,
|
||||
type LogEntry,
|
||||
type PlayAction,
|
||||
type PlayerResult,
|
||||
type UnoAction,
|
||||
type UnoFinal,
|
||||
type UnoOptions,
|
||||
type UnoState,
|
||||
type UnoView,
|
||||
} from './types';
|
||||
|
||||
export * from './cards';
|
||||
export * from './types';
|
||||
|
||||
export const HAND_SIZE = 7;
|
||||
export const UNO_PENALTY = 2;
|
||||
export const TARGET_SCORE = 500;
|
||||
const AWAY_MS = 5000;
|
||||
const ROUND_END_MS = 8000;
|
||||
const AWAY_AFTER = 3;
|
||||
const LOG_MAX = 30;
|
||||
const LOG_VIEW = 15;
|
||||
|
||||
interface Ctx {
|
||||
rng: Rng;
|
||||
now: number;
|
||||
events: GameEvent[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- small helpers
|
||||
|
||||
/** Copy for `apply`: containers are copied; card objects, log entries and options are never mutated, so shared. */
|
||||
function cloneState(s: UnoState): UnoState {
|
||||
return {
|
||||
...s,
|
||||
seats: [...s.seats],
|
||||
hands: Object.fromEntries(Object.entries(s.hands).map(([p, h]) => [p, [...h]])),
|
||||
drawPile: [...s.drawPile],
|
||||
discard: [...s.discard],
|
||||
phase: { ...s.phase },
|
||||
unoWindow: s.unoWindow ? { ...s.unoWindow } : null,
|
||||
leftOrder: [...s.leftOrder],
|
||||
timeoutsInRow: { ...s.timeoutsInRow },
|
||||
away: { ...s.away },
|
||||
scores: { ...s.scores },
|
||||
rounds: [...s.rounds],
|
||||
ready: [...s.ready],
|
||||
log: [...s.log],
|
||||
};
|
||||
}
|
||||
|
||||
const gone = (s: UnoState, p: PlayerId): boolean => s.leftOrder.includes(p);
|
||||
const alive = (s: UnoState): PlayerId[] => s.seats.filter((p) => !gone(s, p));
|
||||
export const top = (s: UnoState): UnoCard => s.discard[s.discard.length - 1]!;
|
||||
export const faceOf = ({ id: _id, ...face }: UnoCard): CardFace => face as CardFace;
|
||||
/** Every card is in exactly one place (test invariant). */
|
||||
export const cardTotal = (s: UnoState): number => s.drawPile.length + s.discard.length + s.seats.reduce((a, p) => a + (s.hands[p]?.length ?? 0), 0);
|
||||
|
||||
function log(s: UnoState, e: Record<string, unknown> & { t: LogEntry['t'] }): void {
|
||||
s.log.push({ seq: s.seq, ...e } as LogEntry);
|
||||
if (s.log.length > LOG_MAX) s.log.splice(0, s.log.length - LOG_MAX);
|
||||
}
|
||||
|
||||
/** Moves `steps` seats in the current direction over players still in the game (`from` may have left). */
|
||||
function advance(s: UnoState, from: PlayerId, steps: number): PlayerId {
|
||||
const n = s.seats.length;
|
||||
if (alive(s).length === 0) return from;
|
||||
let idx = s.seats.indexOf(from);
|
||||
let moved = 0;
|
||||
while (moved < steps) {
|
||||
idx = (idx + s.direction + n) % n;
|
||||
if (!gone(s, s.seats[idx]!)) moved++;
|
||||
}
|
||||
return s.seats[idx]!;
|
||||
}
|
||||
|
||||
/** Next player after `from` skipping `skips` people; skipping everyone else comes back to `from` (2 players). */
|
||||
function nextAfter(s: UnoState, from: PlayerId, skips: number): PlayerId {
|
||||
const steps = 1 + skips;
|
||||
if (!gone(s, from) && steps >= alive(s).length) return from;
|
||||
return advance(s, from, steps);
|
||||
}
|
||||
|
||||
function startTurn(s: UnoState, p: PlayerId): void {
|
||||
s.current = p;
|
||||
s.phase = { kind: 'turn' };
|
||||
s.turnNo += 1;
|
||||
}
|
||||
|
||||
const symbolMatch = (t: UnoCard, c: UnoCard): boolean =>
|
||||
t.kind === 'num' && c.kind === 'num' ? t.value === c.value : t.kind !== 'num' && !isWild(t) && t.kind === c.kind;
|
||||
|
||||
/** Holds a card of the colour to follow (what makes a 와일드 드로우4 illegal). */
|
||||
const holdsColor = (s: UnoState, hand: readonly UnoCard[], except: string): boolean => s.color !== null && hand.some((h) => h.id !== except && colorOf(h) === s.color);
|
||||
|
||||
/** Normal-turn match; `honest` applies the 와일드 드로우4 rule even when the room lets players bluff it. */
|
||||
function matches(s: UnoState, c: UnoCard, hand: readonly UnoCard[], honest: boolean): boolean {
|
||||
if (c.kind === 'wild') return true;
|
||||
if (c.kind === 'wild4') return !(honest || s.options.wild4Rule === 'strict') || !holdsColor(s, hand, c.id);
|
||||
if (s.color === null) return true;
|
||||
return colorOf(c) === s.color || symbolMatch(top(s), c);
|
||||
}
|
||||
|
||||
/** 드로우 카드 쌓기: 드로우2 on 드로우2, 와일드 드로우4 on either. */
|
||||
const canStack = (t: UnoCard, c: UnoCard): boolean => (t.kind === 'draw2' && (c.kind === 'draw2' || c.kind === 'wild4')) || (t.kind === 'wild4' && c.kind === 'wild4');
|
||||
|
||||
/** May `p` play `c` now (any phase)? `honest` = also within the 와일드 드로우4 rule (timer, hints). */
|
||||
function canPlay(s: UnoState, p: PlayerId, c: UnoCard, honest = false): boolean {
|
||||
const hand = s.hands[p] ?? [];
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'wild4') return ph.target === p && s.options.stacking && c.kind === 'wild4';
|
||||
if (s.current !== p) return false;
|
||||
if (ph.kind === 'afterDraw' && c.id !== ph.drawnCardId) return false;
|
||||
if (ph.kind !== 'turn' && ph.kind !== 'afterDraw') return false;
|
||||
if (s.pending > 0) return s.options.stacking && canStack(top(s), c);
|
||||
return matches(s, c, hand, honest);
|
||||
}
|
||||
|
||||
export function playableIds(s: UnoState, p: PlayerId, honest = false): string[] {
|
||||
if (s.phase.kind === 'finished' || s.phase.kind === 'roundEnd' || s.phase.kind === 'startColor') return [];
|
||||
return (s.hands[p] ?? []).filter((c) => canPlay(s, p, c, honest)).map((c) => c.id);
|
||||
}
|
||||
|
||||
function hintFor(s: UnoState, c: UnoCard, hand: readonly UnoCard[]): string {
|
||||
if (s.pending > 0) return '쌓아서 다음 사람에게 넘겨요';
|
||||
if (c.kind === 'wild') return '와일드는 언제든 낼 수 있어요';
|
||||
if (c.kind === 'wild4') return holdsColor(s, hand, c.id) ? '지금 색 카드가 있어서 원래는 못 내요. 도전받으면 내가 4장을 먹어요' : '지금 색 카드가 없어서 낼 수 있어요';
|
||||
if (s.color === null) return '아무 색이나 낼 수 있어요';
|
||||
if (colorOf(c) === s.color) return `${COLOR_KO[s.color]} 색이 같아요`;
|
||||
return c.kind === 'num' ? '숫자가 같아요' : '기호가 같아요';
|
||||
}
|
||||
|
||||
function reshuffle(s: UnoState, ctx: Ctx): void {
|
||||
const pool = s.discard.slice(0, -1);
|
||||
if (pool.length === 0) return;
|
||||
s.discard = s.discard.slice(-1);
|
||||
s.drawPile = [...s.drawPile, ...ctx.rng.shuffle(pool)];
|
||||
ctx.events.push({ type: 'reshuffled', count: pool.length });
|
||||
log(s, { t: 'reshuffle', n: pool.length });
|
||||
}
|
||||
|
||||
function drawOne(s: UnoState, ctx: Ctx): UnoCard | undefined {
|
||||
if (s.drawPile.length === 0) reshuffle(s, ctx);
|
||||
return s.drawPile.shift();
|
||||
}
|
||||
|
||||
/** Draws up to `n` cards (the discard pile refills the draw pile when needed). */
|
||||
function drawCards(s: UnoState, p: PlayerId, n: number, why: Extract<LogEntry, { t: 'draw' }>['why'], ctx: Ctx): number {
|
||||
const hand = s.hands[p]!;
|
||||
let got = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = drawOne(s, ctx);
|
||||
if (!c) break;
|
||||
hand.push(c);
|
||||
got++;
|
||||
}
|
||||
ctx.events.push({ type: 'cardsDrawn', player: p, count: got, why });
|
||||
log(s, { t: 'draw', p, n: got, why });
|
||||
if (s.unoWindow?.player === p && hand.length !== 1) s.unoWindow = null;
|
||||
return got;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rounds
|
||||
|
||||
function dealRound(s: UnoState, starter: PlayerId, ctx: Ctx): void {
|
||||
const players = alive(s);
|
||||
s.drawPile = ctx.rng.shuffle(unoDeck());
|
||||
s.discard = [];
|
||||
s.hands = Object.fromEntries(s.seats.map((p) => [p, [] as UnoCard[]]));
|
||||
s.color = null;
|
||||
s.direction = 1;
|
||||
s.pending = 0;
|
||||
s.unoWindow = null;
|
||||
s.reveal = null;
|
||||
s.ready = [];
|
||||
s.roundStarter = starter;
|
||||
// One card at a time, starting with the first player.
|
||||
const order: PlayerId[] = [];
|
||||
for (let k = 0, p = starter; k < players.length; k++, p = advance(s, p, 1)) order.push(p);
|
||||
for (let r = 0; r < HAND_SIZE; r++) for (const p of order) s.hands[p]!.push(s.drawPile.shift()!);
|
||||
ctx.events.push({ type: 'dealt', players: order, count: HAND_SIZE, round: s.round });
|
||||
// Start card (official): a 와일드 드로우4 goes back into the deck, which is shuffled again.
|
||||
let c = s.drawPile.shift()!;
|
||||
while (c.kind === 'wild4') {
|
||||
s.drawPile = ctx.rng.shuffle([...s.drawPile, c]);
|
||||
c = s.drawPile.shift()!;
|
||||
}
|
||||
s.discard.push(c);
|
||||
s.color = colorOf(c);
|
||||
ctx.events.push({ type: 'startCard', card: faceOf(c) });
|
||||
switch (c.kind) {
|
||||
case 'draw2':
|
||||
drawCards(s, starter, 2, 'start', ctx);
|
||||
log(s, { t: 'skip', p: starter });
|
||||
startTurn(s, nextAfter(s, starter, 0));
|
||||
break;
|
||||
case 'skip':
|
||||
log(s, { t: 'skip', p: starter });
|
||||
startTurn(s, nextAfter(s, starter, 0));
|
||||
break;
|
||||
case 'reverse':
|
||||
if (players.length <= 2) {
|
||||
// Two players: a reverse works like a skip.
|
||||
log(s, { t: 'skip', p: starter });
|
||||
startTurn(s, nextAfter(s, starter, 0));
|
||||
} else {
|
||||
// The dealer (the seat before the first player) starts and play goes the other way.
|
||||
s.direction = -1;
|
||||
log(s, { t: 'reverse' });
|
||||
startTurn(s, advance(s, starter, 1));
|
||||
}
|
||||
break;
|
||||
case 'wild':
|
||||
s.current = starter;
|
||||
s.phase = { kind: 'startColor' };
|
||||
s.turnNo += 1;
|
||||
break;
|
||||
default:
|
||||
startTurn(s, starter);
|
||||
}
|
||||
}
|
||||
|
||||
/** Points the winner collects from everyone else's remaining cards (official values). */
|
||||
const roundPoints = (s: UnoState, winner: PlayerId): number => s.seats.filter((p) => p !== winner).reduce((a, p) => a + handPoints(s.hands[p]!), 0);
|
||||
|
||||
function endRound(s: UnoState, winner: PlayerId, ctx: Ctx): void {
|
||||
s.unoWindow = null;
|
||||
s.pending = 0;
|
||||
const points = roundPoints(s, winner);
|
||||
if (s.options.scoring === 'single') {
|
||||
finishSingle(s, winner, points, ctx);
|
||||
return;
|
||||
}
|
||||
s.scores[winner] = (s.scores[winner] ?? 0) + points;
|
||||
s.rounds.push({ round: s.round, winner, points });
|
||||
log(s, { t: 'round', round: s.round, winner, points });
|
||||
ctx.events.push({ type: 'roundEnd', round: s.round, winner, points });
|
||||
if (s.scores[winner]! >= TARGET_SCORE || alive(s).length <= 1) {
|
||||
finishMulti(s, ctx);
|
||||
return;
|
||||
}
|
||||
s.phase = { kind: 'roundEnd' };
|
||||
s.ready = [];
|
||||
s.turnNo += 1;
|
||||
}
|
||||
|
||||
function results(s: UnoState, ranking: PlayerId[][], pointsOf: (p: PlayerId) => number): PlayerResult[] {
|
||||
const out: PlayerResult[] = [];
|
||||
let rank = 1;
|
||||
for (const g of ranking) {
|
||||
for (const p of g) out.push({ player: p, rank, left: gone(s, p), cardsLeft: s.hands[p]!.length, handPoints: handPoints(s.hands[p]!), points: pointsOf(p) });
|
||||
rank += g.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function finishSingle(s: UnoState, winner: PlayerId, points: number, ctx: Ctx): void {
|
||||
// Winner first; everyone else by the points left in hand (fewer is better); players who left last.
|
||||
const rest = alive(s)
|
||||
.filter((p) => p !== winner)
|
||||
.sort((a, b) => handPoints(s.hands[a]!) - handPoints(s.hands[b]!) || s.hands[a]!.length - s.hands[b]!.length);
|
||||
const ranking: PlayerId[][] = [[winner]];
|
||||
for (const p of rest) {
|
||||
const last = ranking[ranking.length - 1]!;
|
||||
const prev = last[0]!;
|
||||
if (prev !== winner && handPoints(s.hands[prev]!) === handPoints(s.hands[p]!) && s.hands[prev]!.length === s.hands[p]!.length) last.push(p);
|
||||
else ranking.push([p]);
|
||||
}
|
||||
for (const p of [...s.leftOrder].reverse()) ranking.push([p]);
|
||||
const pointsOf = (p: PlayerId) => (p === winner ? points : 0);
|
||||
const summary = s.hands[winner]!.length === 0 ? `가장 먼저 카드를 모두 내서 ${points}점을 얻었어요` : '다른 사람이 모두 나가서 남은 사람이 이겼어요';
|
||||
s.final = { ranking, players: results(s, ranking, pointsOf), scores: Object.fromEntries(s.seats.map((p) => [p, pointsOf(p)])), summary };
|
||||
finishState(s, ctx);
|
||||
}
|
||||
|
||||
function finishMulti(s: UnoState, ctx: Ctx): void {
|
||||
const remaining = alive(s).sort((a, b) => s.scores[b]! - s.scores[a]!);
|
||||
const ranking: PlayerId[][] = [];
|
||||
for (const p of remaining) {
|
||||
const last = ranking[ranking.length - 1];
|
||||
if (last && s.scores[last[0]!] === s.scores[p]) last.push(p);
|
||||
else ranking.push([p]);
|
||||
}
|
||||
for (const p of [...s.leftOrder].reverse()) ranking.push([p]);
|
||||
const best = remaining[0];
|
||||
const summary =
|
||||
best && s.scores[best]! >= TARGET_SCORE
|
||||
? `${s.round}판 만에 ${s.scores[best]}점으로 ${TARGET_SCORE}점에 먼저 닿았어요`
|
||||
: '다른 사람이 모두 나가서 점수가 가장 높은 사람이 이겼어요';
|
||||
s.final = { ranking, players: results(s, ranking, (p) => s.scores[p] ?? 0), scores: { ...s.scores }, summary };
|
||||
finishState(s, ctx);
|
||||
}
|
||||
|
||||
function finishState(s: UnoState, ctx: Ctx): void {
|
||||
s.phase = { kind: 'finished' };
|
||||
s.unoWindow = null;
|
||||
s.reveal = null;
|
||||
ctx.events.push({ type: 'gameEnd', ranking: s.final!.ranking });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- playing cards
|
||||
|
||||
function playCard(s: UnoState, p: PlayerId, a: PlayAction, ctx: Ctx): void {
|
||||
const o = s.options;
|
||||
const hand = s.hands[p]!;
|
||||
const card = hand.find((c) => c.id === a.cardId)!;
|
||||
const prevColor = s.color;
|
||||
const illegal = card.kind === 'wild4' && holdsColor(s, hand, card.id);
|
||||
s.hands[p] = hand.filter((c) => c.id !== card.id);
|
||||
s.discard.push(card);
|
||||
const left = s.hands[p]!.length;
|
||||
ctx.events.push({ type: 'cardPlayed', player: p, card: faceOf(card) });
|
||||
let skips = 0;
|
||||
let challengeable = false;
|
||||
let immediate = false;
|
||||
switch (card.kind) {
|
||||
case 'num':
|
||||
s.color = card.color;
|
||||
break;
|
||||
case 'skip':
|
||||
s.color = card.color;
|
||||
skips = 1;
|
||||
break;
|
||||
case 'reverse':
|
||||
s.color = card.color;
|
||||
if (alive(s).length <= 2) skips = 1;
|
||||
else {
|
||||
s.direction = s.direction === 1 ? -1 : 1;
|
||||
ctx.events.push({ type: 'directionChanged', direction: s.direction });
|
||||
log(s, { t: 'reverse' });
|
||||
}
|
||||
break;
|
||||
case 'draw2':
|
||||
s.color = card.color;
|
||||
s.pending += 2;
|
||||
immediate = !o.stacking;
|
||||
break;
|
||||
case 'wild':
|
||||
case 'wild4':
|
||||
s.color = a.color!;
|
||||
ctx.events.push({ type: 'colorChosen', color: a.color });
|
||||
if (card.kind === 'wild4') {
|
||||
s.pending += 4;
|
||||
if (o.wild4Rule === 'challenge') challengeable = true;
|
||||
else immediate = !o.stacking;
|
||||
}
|
||||
break;
|
||||
}
|
||||
log(s, { t: 'play', p, card: faceOf(card), ...(isWild(card) ? { color: a.color } : {}) });
|
||||
|
||||
if (left === 0) {
|
||||
ctx.events.push({ type: 'playerOut', player: p });
|
||||
// Going out on a draw card: the next player still takes the cards (they count for the points).
|
||||
if (s.pending > 0) {
|
||||
const victim = nextAfter(s, p, 0);
|
||||
if (victim !== p) drawCards(s, victim, s.pending, card.kind === 'wild4' ? 'wild4' : 'draw2', ctx);
|
||||
s.pending = 0;
|
||||
}
|
||||
endRound(s, p, ctx);
|
||||
return;
|
||||
}
|
||||
|
||||
if (left === 1) {
|
||||
const declared = !!a.uno;
|
||||
s.unoWindow = { player: p, declared };
|
||||
ctx.events.push({ type: 'unoOpen', player: p, declared });
|
||||
if (declared) log(s, { t: 'uno', p });
|
||||
}
|
||||
|
||||
const next = nextAfter(s, p, skips);
|
||||
if (challengeable) {
|
||||
s.current = next;
|
||||
s.phase = { kind: 'wild4', by: p, target: next, prevColor, illegal };
|
||||
s.turnNo += 1;
|
||||
return;
|
||||
}
|
||||
if (immediate) {
|
||||
drawCards(s, next, s.pending, card.kind === 'wild4' ? 'wild4' : 'draw2', ctx);
|
||||
s.pending = 0;
|
||||
ctx.events.push({ type: 'skipped', player: next });
|
||||
log(s, { t: 'skip', p: next });
|
||||
startTurn(s, nextAfter(s, next, 0));
|
||||
return;
|
||||
}
|
||||
if (skips > 0) log(s, { t: 'skip', p: advance(s, p, 1) });
|
||||
startTurn(s, next);
|
||||
}
|
||||
|
||||
/** Card the timer plays: a coloured card first (wilds are worth keeping), never a 와일드 드로우4 against the rule. */
|
||||
function autoCard(s: UnoState, p: PlayerId, ids: string[]): UnoCard | undefined {
|
||||
const hand = s.hands[p]!;
|
||||
const cards = ids.map((id) => hand.find((c) => c.id === id)!);
|
||||
return cards.find((c) => !isWild(c)) ?? cards.find((c) => c.kind === 'wild') ?? cards[0];
|
||||
}
|
||||
|
||||
function autoPlay(s: UnoState, p: PlayerId, c: UnoCard, ctx: Ctx): void {
|
||||
const rest = s.hands[p]!.filter((x) => x.id !== c.id);
|
||||
playCard(s, p, { type: 'play', cardId: c.id, ...(isWild(c) ? { color: majorityColor(rest) } : {}) }, ctx);
|
||||
}
|
||||
|
||||
/** Draw on a turn (button, or the timer with `auto`: then a playable drawn card is played at once). */
|
||||
function drawTurn(s: UnoState, p: PlayerId, ctx: Ctx, auto: boolean): void {
|
||||
if (s.pending > 0) {
|
||||
const n = s.pending;
|
||||
s.pending = 0;
|
||||
drawCards(s, p, n, 'stack', ctx);
|
||||
startTurn(s, nextAfter(s, p, 0));
|
||||
return;
|
||||
}
|
||||
const hand = s.hands[p]!;
|
||||
let drawn: UnoCard | undefined;
|
||||
let n = 0;
|
||||
for (;;) {
|
||||
const c = drawOne(s, ctx);
|
||||
if (!c) break;
|
||||
hand.push(c);
|
||||
n++;
|
||||
drawn = c;
|
||||
// 낼 수 있을 때까지 뽑기 (house rule): keep going while the card can't be played.
|
||||
if (!s.options.drawUntilPlayable || canPlay(s, p, c, auto)) break;
|
||||
}
|
||||
ctx.events.push({ type: 'cardsDrawn', player: p, count: n, why: 'normal' });
|
||||
log(s, { t: 'draw', p, n, why: 'normal' });
|
||||
if (s.unoWindow?.player === p && hand.length !== 1) s.unoWindow = null;
|
||||
if (drawn && canPlay(s, p, drawn, auto)) {
|
||||
if (auto) {
|
||||
autoPlay(s, p, drawn, ctx);
|
||||
return;
|
||||
}
|
||||
s.phase = { kind: 'afterDraw', drawnCardId: drawn.id };
|
||||
return;
|
||||
}
|
||||
startTurn(s, nextAfter(s, p, 0));
|
||||
}
|
||||
|
||||
function resolveWild4(s: UnoState, challenge: boolean, ctx: Ctx): void {
|
||||
const ph = s.phase;
|
||||
if (ph.kind !== 'wild4') throw new Error('not in the wild4 phase');
|
||||
const { by, target, illegal } = ph;
|
||||
const total = s.pending;
|
||||
s.pending = 0;
|
||||
if (!challenge) {
|
||||
drawCards(s, target, total, 'wild4', ctx);
|
||||
log(s, { t: 'skip', p: target });
|
||||
startTurn(s, nextAfter(s, target, 0));
|
||||
return;
|
||||
}
|
||||
s.reveal = { to: target, by, cards: s.hands[by]!.map(faceOf), illegal };
|
||||
ctx.events.push({ type: 'challenged', by, target, illegal });
|
||||
log(s, { t: 'challenge', p: target, by, illegal });
|
||||
if (illegal) {
|
||||
// Caught bluffing: the player of the card draws instead, and the challenger plays normally.
|
||||
drawCards(s, by, total, 'challenge', ctx);
|
||||
startTurn(s, target);
|
||||
} else {
|
||||
drawCards(s, target, total + 2, 'challenge', ctx);
|
||||
startTurn(s, nextAfter(s, target, 0));
|
||||
}
|
||||
}
|
||||
|
||||
function catchUno(s: UnoState, actor: PlayerId, ctx: Ctx): void {
|
||||
const target = s.unoWindow!.player;
|
||||
s.unoWindow = null;
|
||||
ctx.events.push({ type: 'unoCaught', catcher: actor, target, penalty: UNO_PENALTY });
|
||||
log(s, { t: 'caught', p: target, by: actor, n: UNO_PENALTY });
|
||||
drawCards(s, target, UNO_PENALTY, 'penalty', ctx);
|
||||
}
|
||||
|
||||
function leave(s: UnoState, p: PlayerId, ctx: Ctx): void {
|
||||
s.leftOrder.push(p);
|
||||
ctx.events.push({ type: 'left', player: p });
|
||||
log(s, { t: 'left', p });
|
||||
s.ready = s.ready.filter((x) => x !== p);
|
||||
if (s.phase.kind === 'roundEnd') {
|
||||
if (alive(s).length <= 1) finishMulti(s, ctx);
|
||||
else maybeStartNextRound(s, ctx);
|
||||
return;
|
||||
}
|
||||
// The hand goes to the bottom of the draw pile, unshuffled.
|
||||
s.drawPile.push(...s.hands[p]!);
|
||||
s.hands[p] = [];
|
||||
if (s.unoWindow?.player === p) s.unoWindow = null;
|
||||
if (s.reveal?.to === p || s.reveal?.by === p) s.reveal = null;
|
||||
const live = alive(s);
|
||||
if (live.length <= 1) {
|
||||
if (s.options.scoring === 'single') finishSingle(s, live[0]!, roundPoints(s, live[0]!), ctx);
|
||||
else finishMulti(s, ctx);
|
||||
return;
|
||||
}
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'wild4') {
|
||||
if (ph.by === p) {
|
||||
// The 와일드 드로우4 of a player who is gone no longer counts; the target just plays on.
|
||||
s.pending = 0;
|
||||
startTurn(s, ph.target);
|
||||
} else if (ph.target === p) {
|
||||
s.pending = 0;
|
||||
startTurn(s, nextAfter(s, p, 0));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (s.current !== p) return;
|
||||
if (ph.kind === 'startColor') {
|
||||
s.current = nextAfter(s, p, 0);
|
||||
s.turnNo += 1;
|
||||
return;
|
||||
}
|
||||
s.pending = 0;
|
||||
startTurn(s, nextAfter(s, p, 0));
|
||||
}
|
||||
|
||||
function maybeStartNextRound(s: UnoState, ctx: Ctx): void {
|
||||
if (s.phase.kind !== 'roundEnd') return;
|
||||
const players = alive(s);
|
||||
if (!players.every((p) => s.ready.includes(p))) return;
|
||||
s.round += 1;
|
||||
// The deal passes to the left: the next round starts one seat after the previous first player.
|
||||
const n = s.seats.length;
|
||||
let idx = s.seats.indexOf(s.roundStarter);
|
||||
do idx = (idx + 1) % n;
|
||||
while (!players.includes(s.seats[idx]!));
|
||||
dealRound(s, s.seats[idx]!, ctx);
|
||||
}
|
||||
|
||||
function waiting(s: UnoState): PlayerId[] {
|
||||
switch (s.phase.kind) {
|
||||
case 'startColor':
|
||||
case 'turn':
|
||||
case 'afterDraw':
|
||||
return [s.current];
|
||||
case 'wild4':
|
||||
return [s.phase.target];
|
||||
case 'roundEnd':
|
||||
return alive(s).filter((p) => !s.ready.includes(p));
|
||||
case 'finished':
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const inPlay = (s: UnoState): boolean => s.phase.kind !== 'finished' && s.phase.kind !== 'roundEnd';
|
||||
const canCall = (s: UnoState, p: PlayerId): boolean => inPlay(s) && !!s.unoWindow && !s.unoWindow.declared && s.unoWindow.player === p && !gone(s, p);
|
||||
const canCatch = (s: UnoState, p: PlayerId): boolean => inPlay(s) && !!s.unoWindow && !s.unoWindow.declared && s.unoWindow.player !== p && !gone(s, p);
|
||||
|
||||
function validatePlay(s: UnoState, actor: PlayerId, a: PlayAction): Validation {
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'wild4') {
|
||||
if (ph.target !== actor) return fail('지금은 내 차례가 아니에요.');
|
||||
if (!s.options.stacking) return fail('도전하기나 받아들이기를 골라 주세요.');
|
||||
} else {
|
||||
if (ph.kind !== 'turn' && ph.kind !== 'afterDraw') return fail('지금은 카드를 낼 수 없어요.');
|
||||
if (s.current !== actor) return fail('지금은 내 차례가 아니에요.');
|
||||
}
|
||||
const hand = s.hands[actor]!;
|
||||
const c = hand.find((x) => x.id === a.cardId);
|
||||
if (!c) return fail('손에 없는 카드예요.');
|
||||
if (ph.kind === 'afterDraw' && c.id !== ph.drawnCardId) return fail('방금 뽑은 카드만 낼 수 있어요.');
|
||||
if (!canPlay(s, actor, c)) {
|
||||
if (ph.kind === 'wild4') return fail('와일드 드로우4로만 쌓을 수 있어요.');
|
||||
if (s.pending > 0) return fail(top(s).kind === 'wild4' ? '와일드 드로우4로 쌓거나 카드를 뽑으세요.' : '드로우2나 와일드 드로우4로 쌓거나 카드를 뽑으세요.');
|
||||
if (c.kind === 'wild4') return fail('지금 색 카드가 손에 있으면 와일드 드로우4를 낼 수 없어요.');
|
||||
return fail('같은 색이나 같은 숫자·기호 카드만 낼 수 있어요.');
|
||||
}
|
||||
if (isWild(c) && !a.color) return fail('색을 골라 주세요.');
|
||||
if (!isWild(c) && a.color) return fail('와일드만 색을 고를 수 있어요.');
|
||||
return ok;
|
||||
}
|
||||
|
||||
function deadlineMs(s: UnoState): number | null {
|
||||
switch (s.phase.kind) {
|
||||
case 'startColor':
|
||||
case 'turn':
|
||||
case 'afterDraw':
|
||||
return s.away[s.current] ? AWAY_MS : s.options.turnSeconds * 1000;
|
||||
case 'wild4':
|
||||
return s.away[s.phase.target] ? AWAY_MS : s.options.turnSeconds * 1000;
|
||||
case 'roundEnd':
|
||||
return ROUND_END_MS;
|
||||
case 'finished':
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Play actions for one card: a colour for wilds, with and without "우노!" when it leaves one card. */
|
||||
function playVariants(s: UnoState, p: PlayerId, c: UnoCard): PlayAction[] {
|
||||
let out: PlayAction[] = isWild(c) ? COLORS.map((color: Color) => ({ type: 'play', cardId: c.id, color })) : [{ type: 'play', cardId: c.id }];
|
||||
if (s.hands[p]!.length === 2) out = out.flatMap((x) => [x, { ...x, uno: true }]);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- definition
|
||||
|
||||
export const uno: GameDefinition<UnoState, UnoAction, UnoView, UnoOptions> = {
|
||||
id: 'uno',
|
||||
nameKo: '우노',
|
||||
minPlayers: 2,
|
||||
maxPlayers: 10,
|
||||
stateVersion: 1,
|
||||
defaultOptions: unoOptionsSchema.parse({}),
|
||||
optionsSchema: unoOptionsSchema as unknown as GameDefinition<UnoState, UnoAction, UnoView, UnoOptions>['optionsSchema'],
|
||||
actionSchema: unoActionSchema as unknown as GameDefinition<UnoState, UnoAction, UnoView, UnoOptions>['actionSchema'],
|
||||
|
||||
setup({ players, options, rng, now }) {
|
||||
if (players.length < 2 || players.length > 10) throw new Error(`uno: ${players.length} players not allowed`);
|
||||
const s: UnoState = {
|
||||
options,
|
||||
seats: [...players],
|
||||
hands: {},
|
||||
drawPile: [],
|
||||
discard: [],
|
||||
color: null,
|
||||
direction: 1,
|
||||
current: players[0]!,
|
||||
phase: { kind: 'turn' },
|
||||
pending: 0,
|
||||
unoWindow: null,
|
||||
leftOrder: [],
|
||||
turnStartedAt: now,
|
||||
seq: 0,
|
||||
turnNo: 0,
|
||||
timeoutsInRow: Object.fromEntries(players.map((p) => [p, 0])),
|
||||
away: Object.fromEntries(players.map((p) => [p, false])),
|
||||
round: 1,
|
||||
roundStarter: players[0]!,
|
||||
scores: Object.fromEntries(players.map((p) => [p, 0])),
|
||||
rounds: [],
|
||||
ready: [],
|
||||
reveal: null,
|
||||
log: [],
|
||||
final: null,
|
||||
};
|
||||
const ctx: Ctx = { rng, now, events: [] };
|
||||
// The first player is drawn with the same RNG before the shuffle (instead of drawing for the dealer).
|
||||
dealRound(s, players[rng.int(players.length)]!, ctx);
|
||||
return s;
|
||||
},
|
||||
|
||||
validate(s, actor, a) {
|
||||
if (!s.seats.includes(actor)) return fail('이 게임의 플레이어가 아니에요.');
|
||||
if (s.phase.kind === 'finished') return fail('게임이 이미 끝났어요.');
|
||||
if (a.type === 'leave') return gone(s, actor) ? fail('이미 나간 플레이어예요.') : ok;
|
||||
if (gone(s, actor)) return fail('방을 나간 플레이어예요.');
|
||||
const ph = s.phase;
|
||||
switch (a.type) {
|
||||
case 'timeout':
|
||||
return waiting(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.');
|
||||
case 'ready':
|
||||
return ph.kind === 'roundEnd' && !s.ready.includes(actor) ? ok : fail('지금은 다음 판을 기다릴 때가 아니에요.');
|
||||
case 'callUno':
|
||||
return canCall(s, actor) ? ok : fail('지금은 우노를 외칠 때가 아니에요.');
|
||||
case 'catchUno':
|
||||
return canCatch(s, actor) ? ok : fail('지금은 잡을 사람이 없어요.');
|
||||
case 'startColor':
|
||||
return ph.kind === 'startColor' && s.current === actor ? ok : fail('지금은 시작 색을 고를 때가 아니에요.');
|
||||
case 'challenge':
|
||||
case 'accept':
|
||||
return ph.kind === 'wild4' && ph.target === actor ? ok : fail('지금은 도전할 수 없어요.');
|
||||
case 'pass':
|
||||
return ph.kind === 'afterDraw' && s.current === actor ? ok : fail('지금은 넘길 수 없어요.');
|
||||
case 'draw':
|
||||
if (ph.kind === 'afterDraw' && s.current === actor) return fail('뽑은 카드를 내거나 넘기기를 눌러 주세요.');
|
||||
return ph.kind === 'turn' && s.current === actor ? ok : fail('지금은 내 차례가 아니에요.');
|
||||
case 'play':
|
||||
return validatePlay(s, actor, a);
|
||||
}
|
||||
},
|
||||
|
||||
apply(prev, actor, a, { rng, now }) {
|
||||
const s = cloneState(prev);
|
||||
const ctx: Ctx = { rng, now, events: [] };
|
||||
const before = `${s.turnNo}|${s.phase.kind}`;
|
||||
s.seq += 1;
|
||||
const turnAction = ['play', 'draw', 'pass', 'challenge', 'accept', 'startColor', 'timeout'].includes(a.type);
|
||||
if (turnAction && inPlay(s)) {
|
||||
// The next turn action by anyone ends the chance to catch a missed "우노!" (official: before the next player starts).
|
||||
s.unoWindow = null;
|
||||
if (s.reveal?.to === actor) s.reveal = null;
|
||||
}
|
||||
if (a.type !== 'timeout' && a.type !== 'leave' && a.type !== 'catchUno' && a.type !== 'callUno') {
|
||||
s.timeoutsInRow[actor] = 0;
|
||||
s.away[actor] = false;
|
||||
}
|
||||
switch (a.type) {
|
||||
case 'play':
|
||||
playCard(s, actor, a, ctx);
|
||||
break;
|
||||
case 'draw':
|
||||
drawTurn(s, actor, ctx, false);
|
||||
break;
|
||||
case 'pass':
|
||||
ctx.events.push({ type: 'passed', player: actor });
|
||||
log(s, { t: 'pass', p: actor });
|
||||
startTurn(s, nextAfter(s, actor, 0));
|
||||
break;
|
||||
case 'callUno':
|
||||
s.unoWindow!.declared = true;
|
||||
ctx.events.push({ type: 'unoCalled', player: actor });
|
||||
log(s, { t: 'uno', p: actor });
|
||||
break;
|
||||
case 'catchUno':
|
||||
catchUno(s, actor, ctx);
|
||||
break;
|
||||
case 'startColor':
|
||||
s.color = a.color;
|
||||
ctx.events.push({ type: 'colorChosen', color: a.color });
|
||||
log(s, { t: 'startColor', p: actor, color: a.color });
|
||||
startTurn(s, actor);
|
||||
break;
|
||||
case 'challenge':
|
||||
resolveWild4(s, true, ctx);
|
||||
break;
|
||||
case 'accept':
|
||||
resolveWild4(s, false, ctx);
|
||||
break;
|
||||
case 'ready':
|
||||
s.ready.push(actor);
|
||||
maybeStartNextRound(s, ctx);
|
||||
break;
|
||||
case 'leave':
|
||||
leave(s, actor, ctx);
|
||||
break;
|
||||
case 'timeout': {
|
||||
ctx.events.push({ type: 'timeout', player: actor });
|
||||
const ph = s.phase;
|
||||
if (ph.kind !== 'roundEnd') {
|
||||
s.timeoutsInRow[actor] = (s.timeoutsInRow[actor] ?? 0) + 1;
|
||||
if (s.timeoutsInRow[actor]! >= AWAY_AFTER && !s.away[actor]) {
|
||||
s.away[actor] = true;
|
||||
ctx.events.push({ type: 'away', player: actor });
|
||||
}
|
||||
log(s, { t: 'timeout', p: actor });
|
||||
}
|
||||
switch (ph.kind) {
|
||||
case 'startColor': {
|
||||
const color = majorityColor(s.hands[actor]!);
|
||||
s.color = color;
|
||||
log(s, { t: 'startColor', p: actor, color });
|
||||
startTurn(s, actor);
|
||||
break;
|
||||
}
|
||||
case 'turn': {
|
||||
// Plays one of the playable cards (draw-card stacks are taken, not passed on); otherwise draws.
|
||||
const c = s.pending > 0 ? undefined : autoCard(s, actor, playableIds(s, actor, true));
|
||||
if (c) autoPlay(s, actor, c, ctx);
|
||||
else drawTurn(s, actor, ctx, true);
|
||||
break;
|
||||
}
|
||||
case 'afterDraw': {
|
||||
const c = s.hands[actor]!.find((x) => x.id === ph.drawnCardId);
|
||||
if (c && canPlay(s, actor, c, true)) autoPlay(s, actor, c, ctx);
|
||||
else {
|
||||
log(s, { t: 'pass', p: actor });
|
||||
startTurn(s, nextAfter(s, actor, 0));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'wild4':
|
||||
resolveWild4(s, false, ctx);
|
||||
break;
|
||||
case 'roundEnd':
|
||||
s.ready.push(actor);
|
||||
maybeStartNextRound(s, ctx);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (`${s.turnNo}|${s.phase.kind}` !== before) s.turnStartedAt = now;
|
||||
return { state: s, events: ctx.events };
|
||||
},
|
||||
|
||||
view(s, viewer) {
|
||||
const me = viewer && s.seats.includes(viewer) ? viewer : null;
|
||||
const ph = s.phase;
|
||||
const live = inPlay(s);
|
||||
const w = s.unoWindow;
|
||||
let my: UnoView['my'] = null;
|
||||
if (me) {
|
||||
const hand = s.hands[me] ?? [];
|
||||
const playable = live && !gone(s, me) ? playableIds(s, me) : [];
|
||||
my = {
|
||||
hand,
|
||||
playable,
|
||||
hints: Object.fromEntries(playable.map((id) => [id, hintFor(s, hand.find((c) => c.id === id)!, hand)])),
|
||||
bluff: playable.filter((id) => {
|
||||
const c = hand.find((x) => x.id === id)!;
|
||||
return c.kind === 'wild4' && s.pending === 0 && holdsColor(s, hand, id);
|
||||
}),
|
||||
canDraw: ph.kind === 'turn' && s.current === me && !gone(s, me),
|
||||
drawCount: s.pending > 0 ? s.pending : 1,
|
||||
canPass: ph.kind === 'afterDraw' && s.current === me,
|
||||
drawnCardId: ph.kind === 'afterDraw' && s.current === me ? ph.drawnCardId : null,
|
||||
canCallUno: canCall(s, me),
|
||||
canCatchUno: canCatch(s, me),
|
||||
canChallenge: ph.kind === 'wild4' && ph.target === me && !gone(s, me),
|
||||
canStartColor: ph.kind === 'startColor' && s.current === me && !gone(s, me),
|
||||
canReady: ph.kind === 'roundEnd' && !gone(s, me) && !s.ready.includes(me),
|
||||
};
|
||||
}
|
||||
return {
|
||||
options: s.options,
|
||||
me,
|
||||
seats: s.seats.map((p) => ({
|
||||
id: p,
|
||||
cards: s.hands[p]?.length ?? 0,
|
||||
left: gone(s, p),
|
||||
isTurn: live && waiting(s).includes(p),
|
||||
away: !!s.away[p],
|
||||
uno: w?.player === p ? (w.declared ? 'declared' : 'open') : null,
|
||||
score: s.scores[p] ?? 0,
|
||||
ready: ph.kind === 'roundEnd' && s.ready.includes(p),
|
||||
})),
|
||||
current: live ? (ph.kind === 'wild4' ? ph.target : s.current) : null,
|
||||
direction: s.direction,
|
||||
phase: ph.kind,
|
||||
turnNo: s.turnNo,
|
||||
recent: s.discard.slice(-4),
|
||||
color: s.color,
|
||||
pending: s.pending,
|
||||
drawPileCount: s.drawPile.length,
|
||||
discardCount: s.discard.length,
|
||||
unoWindow: w ? { ...w } : null,
|
||||
wild4: ph.kind === 'wild4' ? { by: ph.by, target: ph.target } : null,
|
||||
my,
|
||||
reveal: me && s.reveal && s.reveal.to === me ? { by: s.reveal.by, cards: s.reveal.cards, illegal: s.reveal.illegal } : null,
|
||||
turnStartedAt: s.turnStartedAt,
|
||||
deadlineTotalMs: deadlineMs(s) ?? 0,
|
||||
round: s.round,
|
||||
rounds: s.rounds,
|
||||
log: s.log.slice(-LOG_VIEW),
|
||||
result: s.final,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Only the players the game waits on. Catching a missed "우노!" is open to everyone (buttons in the view), but a
|
||||
* computer only looks for it when its own turn comes up — so it can also miss one, like a person.
|
||||
*/
|
||||
activePlayers: waiting,
|
||||
|
||||
deadline(s) {
|
||||
const ms = deadlineMs(s);
|
||||
return ms === null ? null : s.turnStartedAt + ms;
|
||||
},
|
||||
|
||||
timeoutPlayers: waiting,
|
||||
|
||||
onTimeout() {
|
||||
return { type: 'timeout' };
|
||||
},
|
||||
|
||||
onLeave(s, player) {
|
||||
if (!s.seats.includes(player) || gone(s, player) || s.phase.kind === 'finished') return null;
|
||||
return { type: 'leave' };
|
||||
},
|
||||
|
||||
result(s): GameResult | null {
|
||||
if (!s.final) return null;
|
||||
const f = s.final;
|
||||
const single = s.options.scoring === 'single';
|
||||
const scoreText = Object.fromEntries(
|
||||
f.players.map((r) => [r.player, single && r.rank > 1 ? (r.left ? '나감' : `남은 카드 ${r.handPoints}점`) : `${r.points}점`]),
|
||||
);
|
||||
return { ranking: f.ranking, scores: f.scores, scoreText, summary: f.summary, reason: 'normal' };
|
||||
},
|
||||
|
||||
legalActions(s, p) {
|
||||
if (!s.seats.includes(p) || gone(s, p) || s.phase.kind === 'finished') return [];
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'roundEnd') return s.ready.includes(p) ? [] : [{ type: 'ready' }];
|
||||
const out: UnoAction[] = [];
|
||||
if (canCall(s, p)) out.push({ type: 'callUno' });
|
||||
if (canCatch(s, p)) out.push({ type: 'catchUno' });
|
||||
if (ph.kind === 'startColor') {
|
||||
if (s.current === p) for (const color of COLORS) out.push({ type: 'startColor', color });
|
||||
return out;
|
||||
}
|
||||
if (ph.kind === 'wild4' && ph.target === p) out.push({ type: 'challenge' }, { type: 'accept' });
|
||||
const hand = s.hands[p]!;
|
||||
for (const id of playableIds(s, p)) out.push(...playVariants(s, p, hand.find((c) => c.id === id)!));
|
||||
if (ph.kind === 'turn' && s.current === p) out.push({ type: 'draw' });
|
||||
if (ph.kind === 'afterDraw' && s.current === p) out.push({ type: 'pass' });
|
||||
return out;
|
||||
},
|
||||
|
||||
/** Own hand plus the draw pile — card ids exactly as they would appear in a view. */
|
||||
secretsOf(s, player) {
|
||||
return [...(s.hands[player] ?? []).map((c) => c.id), ...s.drawPile.map((c) => c.id)];
|
||||
},
|
||||
};
|
||||
196
packages/games/src/uno/types.ts
Normal file
196
packages/games/src/uno/types.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
/** 우노 options, actions, state and view types (docs/games/uno.md §2, §8). */
|
||||
import { z } from 'zod';
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
import type { Color, UnoCard } from '../one-card/cards';
|
||||
|
||||
const lit = <T extends string | number>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
|
||||
const colorSchema = z.enum(['R', 'Y', 'G', 'B']);
|
||||
|
||||
export const unoOptionsSchema = z.object({
|
||||
scoring: z
|
||||
.enum(['single', 'to500'])
|
||||
.default('single')
|
||||
.meta({ title: '점수 방식', labels: { single: '한 판(이긴 사람 점수만 계산)', to500: '500점 먼저(여러 판)' } }),
|
||||
wild4Rule: z
|
||||
.enum(['challenge', 'strict'])
|
||||
.default('challenge')
|
||||
.meta({
|
||||
title: '와일드 드로우4',
|
||||
labels: { challenge: '공식: 몰래 낼 수도 있고, 다음 사람이 도전', strict: '쉬운 규칙: 지금 색 카드가 있으면 못 냄' },
|
||||
}),
|
||||
stacking: z.boolean().default(false).meta({ title: '(하우스 룰) 드로우 카드 쌓기' }),
|
||||
drawUntilPlayable: z.boolean().default(false).meta({ title: '(하우스 룰) 낼 수 있을 때까지 뽑기' }),
|
||||
turnSeconds: lit(10, 15, 20, 30, 60)
|
||||
.default(20)
|
||||
.meta({ title: '한 턴 제한 시간', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }),
|
||||
});
|
||||
export type UnoOptions = z.infer<typeof unoOptionsSchema>;
|
||||
|
||||
export const unoActionSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('play'), cardId: z.string().max(8), color: colorSchema.optional(), uno: z.boolean().optional() }),
|
||||
z.object({ type: z.literal('draw') }),
|
||||
z.object({ type: z.literal('pass') }),
|
||||
z.object({ type: z.literal('callUno') }),
|
||||
z.object({ type: z.literal('catchUno') }),
|
||||
z.object({ type: z.literal('challenge') }),
|
||||
z.object({ type: z.literal('accept') }),
|
||||
z.object({ type: z.literal('startColor'), color: colorSchema }),
|
||||
z.object({ type: z.literal('ready') }),
|
||||
]);
|
||||
/** Client actions plus system-only ones (timer, leaving) that are not in the schema. */
|
||||
export type UnoAction = z.infer<typeof unoActionSchema> | { type: 'timeout' } | { type: 'leave' };
|
||||
export type PlayAction = Extract<UnoAction, { type: 'play' }>;
|
||||
|
||||
/** A card without its id (log lines, the challenger's look at a hand): ids must not hint at hidden cards. */
|
||||
export type CardFace = UnoCard extends infer C ? (C extends UnoCard ? Omit<C, 'id'> : never) : never;
|
||||
|
||||
export type Phase =
|
||||
/** The start card was a wild: the first player names the colour. */
|
||||
| { kind: 'startColor' }
|
||||
| { kind: 'turn' }
|
||||
| { kind: 'afterDraw'; drawnCardId: string }
|
||||
/** `illegal`: the 와일드 드로우4 was played while holding a card of `prevColor` (secret until challenged). */
|
||||
| { kind: 'wild4'; by: PlayerId; target: PlayerId; prevColor: Color | null; illegal: boolean }
|
||||
| { kind: 'roundEnd' }
|
||||
| { kind: 'finished' };
|
||||
|
||||
/** Public log line (structured; the screen turns it into Korean with nicknames). */
|
||||
export type LogEntry =
|
||||
| { seq: number; t: 'play'; p: PlayerId; card: CardFace; color?: Color }
|
||||
| { seq: number; t: 'draw'; p: PlayerId; n: number; why: 'normal' | 'stack' | 'penalty' | 'draw2' | 'wild4' | 'challenge' | 'start' }
|
||||
| { seq: number; t: 'pass'; p: PlayerId }
|
||||
| { seq: number; t: 'uno'; p: PlayerId }
|
||||
| { seq: number; t: 'caught'; p: PlayerId; by: PlayerId; n: number }
|
||||
| { seq: number; t: 'left'; p: PlayerId }
|
||||
| { seq: number; t: 'timeout'; p: PlayerId }
|
||||
| { seq: number; t: 'reshuffle'; n: number }
|
||||
| { seq: number; t: 'challenge'; p: PlayerId; by: PlayerId; illegal: boolean }
|
||||
| { seq: number; t: 'skip'; p: PlayerId }
|
||||
| { seq: number; t: 'reverse' }
|
||||
| { seq: number; t: 'startColor'; p: PlayerId; color: Color }
|
||||
| { seq: number; t: 'round'; round: number; winner: PlayerId | null; points: number };
|
||||
|
||||
export interface PlayerResult {
|
||||
player: PlayerId;
|
||||
rank: number;
|
||||
left: boolean;
|
||||
cardsLeft: number;
|
||||
/** Points of the cards left in hand (official card values). */
|
||||
handPoints: number;
|
||||
/** Points won: this game's winner (한 판) or the running total (500점). */
|
||||
points: number;
|
||||
}
|
||||
|
||||
export interface UnoFinal {
|
||||
ranking: PlayerId[][];
|
||||
players: PlayerResult[];
|
||||
scores: Record<PlayerId, number>;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface RoundRecord {
|
||||
round: number;
|
||||
winner: PlayerId | null;
|
||||
points: number;
|
||||
}
|
||||
|
||||
/** "우노!" window: open from the moment a player is down to one card until the next turn action by anyone. */
|
||||
export interface UnoWindow {
|
||||
player: PlayerId;
|
||||
declared: boolean;
|
||||
}
|
||||
|
||||
export interface UnoState {
|
||||
options: UnoOptions;
|
||||
seats: PlayerId[];
|
||||
hands: Record<PlayerId, UnoCard[]>;
|
||||
/** Secret; [0] is the top. */
|
||||
drawPile: UnoCard[];
|
||||
/** Public; the last card is the top. */
|
||||
discard: UnoCard[];
|
||||
/** Colour to follow (null only while the first player picks it after a starting wild). */
|
||||
color: Color | null;
|
||||
direction: 1 | -1;
|
||||
current: PlayerId;
|
||||
phase: Phase;
|
||||
/** Cards the next draw takes (드로우 카드 쌓기, or a 와일드 드로우4 waiting for the challenge answer). */
|
||||
pending: number;
|
||||
unoWindow: UnoWindow | null;
|
||||
leftOrder: PlayerId[];
|
||||
turnStartedAt: number;
|
||||
/** Applied actions. */
|
||||
seq: number;
|
||||
/** Turn counter (changes whenever a new turn starts). */
|
||||
turnNo: number;
|
||||
timeoutsInRow: Record<PlayerId, number>;
|
||||
away: Record<PlayerId, boolean>;
|
||||
round: number;
|
||||
roundStarter: PlayerId;
|
||||
scores: Record<PlayerId, number>;
|
||||
rounds: RoundRecord[];
|
||||
ready: PlayerId[];
|
||||
/** Hand shown to the challenger after a challenge (only in that player's view). */
|
||||
reveal: { to: PlayerId; by: PlayerId; cards: CardFace[]; illegal: boolean } | null;
|
||||
log: LogEntry[];
|
||||
final: UnoFinal | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
export interface SeatView {
|
||||
id: PlayerId;
|
||||
cards: number;
|
||||
left: boolean;
|
||||
isTurn: boolean;
|
||||
away: boolean;
|
||||
/** "우노!" window of this player (declared = safe). */
|
||||
uno: 'open' | 'declared' | null;
|
||||
score: number;
|
||||
ready: boolean;
|
||||
}
|
||||
|
||||
export interface UnoView {
|
||||
options: UnoOptions;
|
||||
me: PlayerId | null;
|
||||
seats: SeatView[];
|
||||
current: PlayerId | null;
|
||||
direction: 1 | -1;
|
||||
phase: Phase['kind'];
|
||||
turnNo: number;
|
||||
/** Last few discards, top last. */
|
||||
recent: UnoCard[];
|
||||
color: Color | null;
|
||||
pending: number;
|
||||
drawPileCount: number;
|
||||
discardCount: number;
|
||||
unoWindow: UnoWindow | null;
|
||||
wild4: { by: PlayerId; target: PlayerId } | null;
|
||||
my: {
|
||||
hand: UnoCard[];
|
||||
/** Cards that may be played now. */
|
||||
playable: string[];
|
||||
/** Why each playable card fits (beginner hint). */
|
||||
hints: Record<string, string>;
|
||||
/** 와일드 드로우4 cards that break the rule right now (challenge rule: playable, but a challenge would win). */
|
||||
bluff: string[];
|
||||
canDraw: boolean;
|
||||
/** Cards a draw takes now. */
|
||||
drawCount: number;
|
||||
canPass: boolean;
|
||||
drawnCardId: string | null;
|
||||
canCallUno: boolean;
|
||||
canCatchUno: boolean;
|
||||
canChallenge: boolean;
|
||||
canStartColor: boolean;
|
||||
canReady: boolean;
|
||||
} | null;
|
||||
reveal: { by: PlayerId; cards: CardFace[]; illegal: boolean } | null;
|
||||
turnStartedAt: number;
|
||||
deadlineTotalMs: number;
|
||||
round: number;
|
||||
rounds: RoundRecord[];
|
||||
log: LogEntry[];
|
||||
result: UnoFinal | null;
|
||||
}
|
||||
602
packages/games/src/uno/uno.test.ts
Normal file
602
packages/games/src/uno/uno.test.ts
Normal file
@@ -0,0 +1,602 @@
|
||||
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);
|
||||
});
|
||||
Reference in New Issue
Block a user