우노: 공식 규칙 엔진·컴퓨터 상대·화면·도움말·문서·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:
74
apps/server/src/rooms/uno.room.test.ts
Normal file
74
apps/server/src/rooms/uno.room.test.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/** 우노 with computers in a real room (docs/games/uno.md §9.1): a person and three computers play to the end. */
|
||||
import { afterEach, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import type { UnoState } from '@bg/games/uno';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import type { Conn, Room } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function practice(options: Record<string, unknown> = {}) {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const room = manager.createPractice('A', 'uno') as Room;
|
||||
rooms.push(room);
|
||||
const msgs: ServerMessage[] = [];
|
||||
const a: Conn = { userId: 'A', send: (m) => msgs.push(m), close: () => {} };
|
||||
room.join(a, 'player');
|
||||
room.addBot('A');
|
||||
room.addBot('A');
|
||||
room.configure('A', { options: { ...(room.config.options as object), ...options } });
|
||||
expect(room.start('A')).toBeNull();
|
||||
return { room, clock, msgs };
|
||||
}
|
||||
|
||||
/** Bots move at once; when the game waits on the person, they play their first legal action (or the clock runs out). */
|
||||
function playToEnd(room: Room, clock: { advance: (ms: number) => void }, humanActs: boolean): number {
|
||||
const def = GAMES.uno!;
|
||||
let cs = 0;
|
||||
let steps = 0;
|
||||
for (; steps < 20_000 && !room.game!.finished; steps++) {
|
||||
if (room.bots.dueAt !== null) {
|
||||
room.bots.fire();
|
||||
continue;
|
||||
}
|
||||
const s = room.game!.state as UnoState;
|
||||
const legal = def.legalActions!(s, 'A');
|
||||
if (humanActs && legal.length && def.activePlayers(s).includes('A')) {
|
||||
room.act('A', ++cs, legal.find((x) => (x as { type: string }).type !== 'catchUno') ?? legal[0]);
|
||||
continue;
|
||||
}
|
||||
clock.advance(61_000);
|
||||
room.onTimer();
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
|
||||
test('a person and three computers finish a game of 우노 (person plays)', () => {
|
||||
const { room, clock } = practice();
|
||||
expect(room.game!.players.filter(isBotId)).toHaveLength(3);
|
||||
playToEnd(room, clock, true);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(room.status).toBe('finished');
|
||||
});
|
||||
|
||||
test('500 points with house rules: the person only times out, the computers still finish', () => {
|
||||
const { room, clock, msgs } = practice({ scoring: 'to500', stacking: true, drawUntilPlayable: true });
|
||||
playToEnd(room, clock, false);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
const s = room.game!.state as UnoState;
|
||||
expect(s.rounds.length).toBeGreaterThanOrEqual(1);
|
||||
expect(msgs.some((m) => m.t === 'state')).toBe(true);
|
||||
// The person's screen shows card counts only for the computers.
|
||||
const view = JSON.stringify(GAMES.uno!.view(s, 'A'));
|
||||
for (const bot of s.seats.filter(isBotId)) for (const c of s.hands[bot]!) expect(view).not.toContain(`"${c.id}"`);
|
||||
});
|
||||
@@ -32,6 +32,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
mafia: () => import('./mafia'),
|
||||
apple: () => import('./apple'),
|
||||
clue: () => import('./clue'),
|
||||
uno: () => import('./uno'),
|
||||
};
|
||||
|
||||
const cache = new Map<string, GameUI>();
|
||||
|
||||
81
apps/web/src/games/uno/help.test.ts
Normal file
81
apps/web/src/games/uno/help.test.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { applyAction, setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const users = usersOf(['A', 'B', 'C']);
|
||||
const view = (s: unknown, who: string | null) => GAMES.uno!.view(s, who) as any;
|
||||
const nickOf = (id: string) => users[id]!.nickname;
|
||||
const R = (v: number, c = 'a') => ({ id: `R${v}${c}`, kind: 'num', color: 'R', value: v });
|
||||
|
||||
/** A plain turn for the first seat with a red 5 on the table. */
|
||||
function plain() {
|
||||
const { state } = setupGame('uno', 3);
|
||||
state.discard = [R(5)];
|
||||
state.color = 'R';
|
||||
state.phase = { kind: 'turn' };
|
||||
state.current = 'A';
|
||||
state.pending = 0;
|
||||
state.unoWindow = null;
|
||||
return state;
|
||||
}
|
||||
|
||||
test('우노: 내 차례 / 상대 차례 / 관전', () => {
|
||||
const state = plain();
|
||||
const mine = helpNow(view(state, 'A'), 'A', users);
|
||||
expect(mine).toContain('내 차례예요');
|
||||
expect(mine).toContain('지금 색(빨강)');
|
||||
expect(mine).toMatch(/초록 테두리|낼 수 있는 카드가 없어요/);
|
||||
expect(helpNow(view(state, 'B'), 'B', users)).toContain(`${nickOf('A')}님 차례예요. 기다려 주세요`);
|
||||
const spec = helpNow(view(state, null), null, users);
|
||||
expect(spec).toContain(`${nickOf('A')}님 차례예요`);
|
||||
expect(spec).not.toContain('내 차례');
|
||||
});
|
||||
|
||||
test('우노: 2장일 때 우노 안내, 안 외친 사람 잡기', () => {
|
||||
const state = plain();
|
||||
state.hands.A = [R(1), R(2)];
|
||||
expect(helpNow(view(state, 'A'), 'A', users)).toContain('[우노!]를 눌러 두면');
|
||||
state.hands.B = [R(3)];
|
||||
state.unoWindow = { player: 'B', declared: false };
|
||||
expect(helpNow(view(state, 'B'), 'B', users)).toContain('[우노!] 버튼을 빨리 눌러요');
|
||||
expect(helpNow(view(state, 'C'), 'C', users)).toContain(`${nickOf('B')}님이 1장 남았는데`);
|
||||
});
|
||||
|
||||
test('우노: 와일드 드로우4 도전, 쌓인 카드, 시작 색', () => {
|
||||
const state = plain();
|
||||
state.phase = { kind: 'wild4', by: 'A', target: 'B', prevColor: 'R', illegal: false };
|
||||
state.pending = 4;
|
||||
state.current = 'B';
|
||||
const t = helpNow(view(state, 'B'), 'B', users);
|
||||
expect(t).toContain('[도전하기]');
|
||||
expect(t).toContain('6장을 먹어요');
|
||||
expect(helpNow(view(state, 'A'), 'A', users)).toContain('도전할지 고르는 중');
|
||||
expect(helpNow(view(state, null), null, users)).toContain('도전할지 고르는 중');
|
||||
|
||||
const st = setupGame('uno', 3, { stacking: true }).state;
|
||||
st.discard = [{ id: 'RDa', kind: 'draw2', color: 'R' }];
|
||||
st.color = 'R';
|
||||
st.phase = { kind: 'turn' };
|
||||
st.current = 'A';
|
||||
st.pending = 2;
|
||||
st.hands.A = [R(1)];
|
||||
expect(helpNow(view(st, 'A'), 'A', users)).toContain('[2장 뽑기]');
|
||||
|
||||
const sc = plain();
|
||||
sc.phase = { kind: 'startColor' };
|
||||
sc.color = null;
|
||||
expect(helpNow(view(sc, 'A'), 'A', users)).toContain('처음 낼 색');
|
||||
expect(helpNow(view(sc, 'B'), 'B', users)).toContain('시작 색을 고르는 중');
|
||||
});
|
||||
|
||||
test('우노: 끝나면 결과 안내', () => {
|
||||
const def = GAMES.uno!;
|
||||
let { state: s } = setupGame('uno', 2);
|
||||
for (let i = 0; i < 3000 && !def.result(s); i++) {
|
||||
const actor = def.activePlayers(s)[0]!;
|
||||
s = applyAction('uno', s, actor, def.legalActions!(s, actor)[0]);
|
||||
}
|
||||
expect(def.result(s)).toBeTruthy();
|
||||
expect(helpNow(view(s, 'A'), 'A', usersOf(['A', 'B']))).toContain('게임이 끝났어요');
|
||||
});
|
||||
85
apps/web/src/games/uno/help.ts
Normal file
85
apps/web/src/games/uno/help.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
/** 우노 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { UnoView } from '@bg/games/uno';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const COLOR_KO = { R: '빨강', Y: '노랑', G: '초록', B: '파랑' } as const;
|
||||
|
||||
const nm = (players: Record<string, PublicUser>, id: string | null | undefined) => `${(id && players[id]?.nickname) || '다른 사람'}님`;
|
||||
|
||||
function myTurn(v: UnoView): string[] {
|
||||
const my = v.my!;
|
||||
const lines: string[] = [];
|
||||
const legal = my.playable.length;
|
||||
if (v.phase === 'startColor') return ['내 차례예요. 시작 카드가 와일드라서 처음 낼 색을 골라요.', '내가 가진 카드가 많은 색을 고르면 좋아요.'];
|
||||
if (v.phase === 'afterDraw') return ['내 차례예요. 방금 뽑은 카드를 바로 낼 수 있어요.', '그 카드를 눌러 [내기]를 누르거나, 내지 않으려면 [넘기기]를 눌러요.'];
|
||||
if (v.pending > 0) {
|
||||
lines.push(`내 차례예요. 드로우 카드 ${v.pending}장이 쌓여 있어요.`);
|
||||
lines.push(legal > 0 ? `초록 테두리 카드로 더 쌓아 다음 사람에게 넘기거나, [${my.drawCount}장 뽑기]를 눌러요.` : `쌓을 카드가 없어요. [${my.drawCount}장 뽑기]를 눌러요.`);
|
||||
return lines;
|
||||
}
|
||||
lines.push('내 차례예요.');
|
||||
lines.push(v.color ? `지금 색(${COLOR_KO[v.color]})이 같거나 숫자·기호가 같은 카드, 또는 와일드를 낼 수 있어요.` : '아무 카드나 낼 수 있어요.');
|
||||
if (legal > 0) {
|
||||
lines.push('초록 테두리 카드만 낼 수 있어요. 카드를 눌러 올린 뒤 한 번 더 누르거나 [내기]를 눌러요.');
|
||||
if (my.bluff.length > 0) lines.push('노란 테두리 와일드 드로우4는 지금 색 카드가 있어서 원래 못 내는 카드예요. 내면 도전받을 수 있어요.');
|
||||
if (my.hand.length === 2) lines.push('내고 나면 1장이 남아요. 내기 전에 [우노!]를 눌러 두면 함께 외쳐요.');
|
||||
lines.push('내고 싶지 않으면 [1장 뽑기]를 눌러도 돼요.');
|
||||
} else lines.push(`낼 수 있는 카드가 없어요. [1장 뽑기]를 누르거나 카드 더미를 눌러요.`);
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function helpNow(v: UnoView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const goal = '손에 든 카드를 가장 먼저 모두 내면 이겨요.';
|
||||
if (v.phase === 'finished') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.';
|
||||
|
||||
const seat = me ? v.seats.find((s) => s.id === me) : undefined;
|
||||
const my = seat && !seat.left ? v.my : null;
|
||||
const w = v.unoWindow;
|
||||
|
||||
if (v.phase === 'roundEnd') {
|
||||
const last = v.rounds[v.rounds.length - 1];
|
||||
const res = last?.winner ? `${v.round}판은 ${nm(players, last.winner)}이 이겨서 ${last.points}점을 얻었어요.` : `${v.round}판이 끝났어요.`;
|
||||
if (my?.canReady) return `${res} 500점에 먼저 닿는 사람이 이겨요.\n[다음 판으로]를 눌러 주세요.`;
|
||||
return `${res} 500점에 먼저 닿는 사람이 이겨요.\n다른 사람이 준비하기를 기다리는 중이에요.`;
|
||||
}
|
||||
|
||||
const catchLine = (() => {
|
||||
if (!w || w.declared || !my) return '';
|
||||
if (my.canCallUno) return '카드가 1장 남았어요! 동그란 [우노!] 버튼을 빨리 눌러요. 다른 사람이 먼저 잡으면 2장을 먹어요.';
|
||||
if (my.canCatchUno) return `${nm(players, w.player)}이 1장 남았는데 우노를 안 외쳤어요. [우노 안 외쳤어요!]를 누르면 ${nm(players, w.player)}이 2장을 먹어요.`;
|
||||
return '';
|
||||
})();
|
||||
const withCatch = (lines: string[]) => (catchLine ? [catchLine, ...lines] : lines).join('\n');
|
||||
const cur = v.current;
|
||||
const curNick = nm(players, cur);
|
||||
|
||||
if (!seat || !my) {
|
||||
const lines: string[] = [];
|
||||
if (seat?.left) lines.push('게임에서 나갔어요.');
|
||||
if (v.phase === 'wild4' && v.wild4) lines.push(`${nm(players, v.wild4.by)}이 와일드 드로우4를 냈어요. ${nm(players, v.wild4.target)}이 도전할지 고르는 중이에요.`);
|
||||
else if (v.phase === 'startColor') lines.push(`${curNick}이 시작 색을 고르는 중이에요.`);
|
||||
else if (cur) lines.push(`${curNick} 차례예요.`);
|
||||
if (!seat) lines.push(goal);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
if (v.phase === 'wild4' && v.wild4) {
|
||||
const by = nm(players, v.wild4.by);
|
||||
if (my.canChallenge) {
|
||||
const lines = [
|
||||
`${by}이 와일드 드로우4를 냈어요. 도전할지 골라요.`,
|
||||
`[도전하기]: ${by}이 그때 바닥 색 카드를 갖고 있었으면 ${by}이 ${v.pending}장을 먹어요. 아니면 내가 ${v.pending + 2}장을 먹어요.`,
|
||||
`[받아들이기]: 내가 ${v.pending}장을 먹고 차례를 넘겨요.`,
|
||||
];
|
||||
if (my.playable.length > 0) lines.push('내 와일드 드로우4를 내서 쌓을 수도 있어요.');
|
||||
return withCatch(lines);
|
||||
}
|
||||
return withCatch([`${by}이 와일드 드로우4를 냈어요. ${nm(players, v.wild4.target)}이 도전할지 고르는 중이에요. 기다려 주세요.`]);
|
||||
}
|
||||
|
||||
if (cur === me) return withCatch(myTurn(v));
|
||||
|
||||
const lines = [v.phase === 'startColor' ? `${curNick}이 시작 색을 고르는 중이에요. 기다려 주세요.` : `${curNick} 차례예요. 기다려 주세요.`];
|
||||
lines.push(`내 카드는 ${my.hand.length}장이에요. ${goal}`);
|
||||
return withCatch(lines);
|
||||
}
|
||||
917
apps/web/src/games/uno/index.tsx
Normal file
917
apps/web/src/games/uno/index.tsx
Normal file
@@ -0,0 +1,917 @@
|
||||
/** 우노 화면 (docs/games/uno.md §9). Card art is the 색깔 카드 artwork of 원카드 (own design). */
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import type { CardFace, Color, LogEntry, SeatView, UnoCard, UnoOptions, UnoView } from '@bg/games/uno';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, Sheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { useSeatRows } from '../../lib/seat-rows';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, patternName } from '../one-card/ColorCard';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const COLORS: Color[] = ['R', 'Y', 'G', 'B'];
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
|
||||
/** Korean name, e.g. "빨강 5", "파랑 스킵", "와일드 드로우4". */
|
||||
function cardName(c: CardFace): 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';
|
||||
}
|
||||
}
|
||||
|
||||
const isWild = (c: CardFace) => c.kind === 'wild' || c.kind === 'wild4';
|
||||
|
||||
function sortHand(hand: UnoCard[], by: 'color' | 'number'): UnoCard[] {
|
||||
const col = (c: UnoCard) => ('color' in c ? COLORS.indexOf(c.color) : 9);
|
||||
const num = (c: UnoCard) => (c.kind === 'num' ? c.value : c.kind === 'skip' ? 10 : c.kind === 'reverse' ? 11 : c.kind === 'draw2' ? 12 : c.kind === 'wild' ? 20 : 21);
|
||||
return [...hand].sort((a, b) => (by === 'color' ? col(a) - col(b) || num(a) - num(b) : num(a) - num(b) || col(a) - col(b)));
|
||||
}
|
||||
|
||||
/** Seat that plays after `from` in the current direction (players who left are skipped). */
|
||||
function nextOf(v: UnoView, from: string | null): SeatView | undefined {
|
||||
if (!from) return undefined;
|
||||
const n = v.seats.length;
|
||||
const i = v.seats.findIndex((s) => s.id === from);
|
||||
for (let k = 1; k < n; k++) {
|
||||
const s = v.seats[(((i + k * v.direction) % n) + n) % n]!;
|
||||
if (!s.left) return s;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.un { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 10px; align-self: center; }
|
||||
.un-opps { display: flex; gap: 8px; overflow-x: auto; padding: 4px 2px 6px; margin: 0; list-style: none; scrollbar-width: thin; }
|
||||
.un-seat { flex: none; min-width: 112px; max-width: 170px; background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 8px;
|
||||
border: 3px solid transparent; box-shadow: var(--shadow); display: flex; flex-direction: column; gap: 3px; font-size: .9rem; }
|
||||
.un-seat.turn { border-color: var(--focus); }
|
||||
.un-seat.next { border-style: dashed; border-color: var(--border); }
|
||||
.un-seat.gone { opacity: .55; }
|
||||
.un-seat .nm { font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
|
||||
.un-count { display: inline-flex; align-items: center; gap: 4px; font-weight: 800; font-variant-numeric: tabular-nums; }
|
||||
.un-count i { display: inline-block; width: 12px; height: 16px; border-radius: 3px; background: #1f2433; border: 1.5px solid #f8fafc; box-shadow: 0 0 0 1px #94a3b8; }
|
||||
.un-badge { display: inline-block; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .78rem; line-height: 1.6; }
|
||||
.un-one { background: #f59e0b; color: #1f2937; animation: un-pop .25s ease; }
|
||||
.un-one.open { background: #dc2626; color: #fff; }
|
||||
.un-table { position: relative; border-radius: 24px; background: radial-gradient(ellipse at center, rgba(255,255,255,.12), rgba(255,255,255,0) 65%), var(--felt);
|
||||
border: 8px solid var(--wood); box-shadow: var(--shadow); padding: 14px; display: grid; grid-template-columns: auto auto 1fr; gap: 18px; align-items: center; color: #fff; }
|
||||
.un-pile { position: relative; width: var(--pw); height: calc(var(--pw) * 1.4); padding: 0; border: 0; background: none; border-radius: 10px; cursor: default; }
|
||||
.un-pile[data-can='true'] { cursor: pointer; }
|
||||
.un-pile[data-can='true']::after { content: ''; position: absolute; inset: -5px; border-radius: 14px; border: 3px dashed #fde047; }
|
||||
.un-pile .cnt { position: absolute; right: -6px; bottom: -8px; background: #111827; color: #fff; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .85rem; }
|
||||
.un-discard { position: relative; width: calc(var(--pw) * 1.12); height: calc(var(--pw) * 1.12 * 1.4); border-radius: 12px; }
|
||||
.un-discard::before { content: ''; position: absolute; inset: -9px; border-radius: 18px; border: 5px solid var(--cc, transparent); box-shadow: 0 0 18px var(--cc, transparent); transition: border-color .3s, box-shadow .3s; }
|
||||
.un-discard > .un-face { position: absolute; inset: 0; }
|
||||
.un-discard > .un-face.top { animation: un-fly .28s ease-out; }
|
||||
.un-discard[data-drop='true'] { outline: 3px dashed #fde047; outline-offset: 12px; }
|
||||
.un-info { display: flex; flex-direction: column; gap: 8px; align-items: flex-start; min-width: 0; text-shadow: 0 1px 2px rgba(0,0,0,.5); }
|
||||
.un-info .row { gap: 6px; }
|
||||
.un-color { display: inline-flex; align-items: center; gap: 8px; border-radius: 14px; padding: 4px 14px 4px 6px; font-weight: 900; font-size: 1.15rem; text-shadow: none;
|
||||
border: 3px solid #fff; box-shadow: 0 2px 6px rgba(0,0,0,.35); }
|
||||
.un-color .sw { width: 28px; height: 28px; border-radius: 50%; border: 3px solid rgba(255,255,255,.9); background: rgba(255,255,255,.25); }
|
||||
.un-pending { background: #b91c1c; color: #fff; font-size: 1.5rem; font-weight: 900; border-radius: 12px; padding: 2px 12px; animation: un-pop .3s ease; text-shadow: none; }
|
||||
.un-dir { display: inline-flex; align-items: center; gap: 6px; font-weight: 800; background: rgba(0,0,0,.35); border-radius: 999px; padding: 2px 12px 2px 6px; }
|
||||
.un-dir b { display: inline-block; font-size: 1.6rem; line-height: 1; transition: transform .35s ease; }
|
||||
.un-dir[data-dir='-1'] b { transform: scaleX(-1); }
|
||||
.un-chip { display: inline-flex; align-items: center; gap: 6px; background: rgba(0,0,0,.35); border-radius: 999px; padding: 2px 10px; font-weight: 800; }
|
||||
.un-face { display: block; width: 100%; height: 100%; }
|
||||
.un-face svg { width: 100% !important; height: 100% !important; display: block; }
|
||||
.un-hand-wrap { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.un-hand { display: flex; align-items: flex-end; padding-top: 16px; min-height: calc(var(--cw) * 1.4 + 18px); }
|
||||
.un-hand.wrap { flex-wrap: wrap; row-gap: 18px; }
|
||||
.un-card { position: relative; flex: none; width: var(--cw); height: calc(var(--cw) * 1.4); padding: 0; border: 0; background: none; border-radius: 9px;
|
||||
transition: transform .12s ease, opacity .12s ease; cursor: pointer; }
|
||||
.un-card + .un-card { margin-left: var(--ov); }
|
||||
.un-card[data-legal='true'] { box-shadow: 0 0 0 3px var(--success); }
|
||||
.un-card[data-bluff='true'] { box-shadow: 0 0 0 3px var(--warning); }
|
||||
.un-card[data-legal='false'] { opacity: .5; filter: grayscale(.4); cursor: default; }
|
||||
.un-card[aria-pressed='true'] { transform: translateY(-16px); box-shadow: 0 0 0 4px var(--primary); z-index: 2; }
|
||||
.un-card:hover[data-legal='true'] { transform: translateY(-6px); z-index: 1; }
|
||||
.un-card[aria-pressed='true']:hover { transform: translateY(-16px); }
|
||||
.un-card:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; z-index: 3; }
|
||||
.un-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.un-actions .btn { flex: 1 1 auto; }
|
||||
.un-unobtn { flex: none !important; width: 76px; height: 76px; border-radius: 50%; border: 3px solid #7f1d1d; background: #dc2626; color: #fff;
|
||||
font-weight: 900; font-size: 1.1rem; line-height: 1.1; padding: 0; cursor: pointer; box-shadow: 0 3px 8px rgba(0,0,0,.25); }
|
||||
.un-unobtn[aria-pressed='true'] { background: #f59e0b; color: #1f2937; border-color: #b45309; }
|
||||
.un-unobtn:disabled { background: var(--surface-2); color: var(--text-sub); border-color: var(--border); box-shadow: none; cursor: not-allowed; }
|
||||
.un-unobtn.call:not(:disabled) { animation: un-shake .3s ease-in-out 3; }
|
||||
.un-tools { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; }
|
||||
.un-tools .segmented button { min-height: 40px; padding: 0 12px; }
|
||||
.un-panel { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.un-panel.warn { border: 3px solid var(--warning); }
|
||||
.un-catch { width: 100%; min-height: 56px; border-radius: 14px; border: 3px solid #7f1d1d; background: #dc2626; color: #fff; font-weight: 900; font-size: 1.1rem; cursor: pointer; animation: un-pop .3s ease; }
|
||||
.un-mini { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.un-mini .un-face { width: 40px; height: 56px; }
|
||||
.un-pick { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
|
||||
.un-pick button { min-height: 72px; font-size: 1.3rem; font-weight: 900; border-radius: 14px; border: 3px solid var(--border); cursor: pointer; }
|
||||
.un-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 240px; overflow: auto; }
|
||||
.un-rules td, .un-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); }
|
||||
.un-rules .un-face { width: 34px; height: 48px; }
|
||||
@keyframes un-fly { from { transform: translate(-40px, 30px) scale(.8); opacity: .3; } to { transform: none; opacity: 1; } }
|
||||
@keyframes un-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
||||
@keyframes un-shake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-8deg); } 75% { transform: rotate(8deg); } }
|
||||
@media (min-width: 720px) {
|
||||
.un-opps { flex-wrap: wrap; justify-content: center; overflow: visible; width: 100%; max-width: calc(var(--cols) * 184px - 4px); margin: 0 auto; }
|
||||
.un-seat { flex: 0 1 calc((100% - (var(--cols) - 1) * 8px) / var(--cols)); min-width: 0; max-width: 176px; }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.un-table { grid-template-columns: auto auto; padding: 12px 10px 10px; gap: 14px; border-width: 6px; justify-content: center; }
|
||||
.un-info { grid-column: 1 / -1; align-items: center; }
|
||||
.un-info .row { justify-content: center; }
|
||||
.un-seat { min-width: 96px; padding: 5px 6px; }
|
||||
.un-unobtn { width: 64px; height: 64px; font-size: .98rem; }
|
||||
}
|
||||
`;
|
||||
|
||||
function Face({ card }: { card: CardFace | null }) {
|
||||
return (
|
||||
<span className="un-face" aria-hidden>
|
||||
<ColorCardArt card={card} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- seats
|
||||
|
||||
function seatLabel(s: SeatView, players: Record<string, PublicUser>, me: string | null, v: UnoView): string {
|
||||
const parts = [`${nick(players, s.id)}${s.id === me ? '(나)' : ''}`, `카드 ${s.cards}장`];
|
||||
if (s.left) parts.push('나감');
|
||||
if (s.away) parts.push('자리 비움');
|
||||
if (s.isTurn) parts.push('차례');
|
||||
if (s.uno === 'open') parts.push('1장 남음, 우노 안 외침');
|
||||
if (s.uno === 'declared') parts.push('우노 외침');
|
||||
if (v.options.scoring === 'to500') parts.push(`${s.score}점`);
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; next: boolean }) {
|
||||
const u = userOf(players, s.id);
|
||||
return (
|
||||
<li className={`un-seat${s.isTurn ? ' turn' : next ? ' next' : ''}${s.left ? ' gone' : ''}`} aria-label={seatLabel(s, players, me, v)}>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={24} />
|
||||
<span className="nm">{u.nickname}</span>
|
||||
{s.isTurn && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={s.id === me} size={28} />}
|
||||
</div>
|
||||
<div className="row" style={{ gap: 6 }}>
|
||||
<span className="un-count" aria-hidden>
|
||||
<i />
|
||||
{s.cards}
|
||||
</span>
|
||||
{s.uno && (
|
||||
<span className={`un-badge un-one${s.uno === 'open' ? ' open' : ''}`} aria-hidden>
|
||||
{s.uno === 'declared' ? '우노!' : '1장!'}
|
||||
</span>
|
||||
)}
|
||||
{s.left && <span className="un-badge" style={{ background: 'var(--text-sub)', color: '#fff' }}>나감</span>}
|
||||
{s.away && <span className="un-badge" style={{ background: 'var(--warning)', color: '#fff' }}>자리 비움</span>}
|
||||
{!s.isTurn && next && <span className="small muted">다음</span>}
|
||||
{v.options.scoring === 'to500' && <span className="small muted">{s.score}점</span>}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- table
|
||||
|
||||
function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: UnoView; players: Record<string, PublicUser>; canDraw: boolean; onDraw: () => void; onDropCard: (id: string) => void }) {
|
||||
const [over, setOver] = useState(false);
|
||||
const pw = 'clamp(64px, 9vw, 92px)';
|
||||
const recent = v.recent;
|
||||
const top = recent[recent.length - 1];
|
||||
const drawText = `${v.my?.drawCount ?? 1}장 뽑기`;
|
||||
const next = nextOf(v, v.current);
|
||||
return (
|
||||
<div className="un-table" role="region" aria-label="카드 판" style={{ '--pw': pw } as CSSProperties}>
|
||||
<button type="button" className="un-pile" data-can={canDraw} disabled={!canDraw} onClick={onDraw} aria-label={`카드 더미 ${v.drawPileCount}장${canDraw ? `. 눌러서 ${drawText}` : ''}`}>
|
||||
<Face card={null} />
|
||||
<span className="cnt" aria-hidden>
|
||||
{v.drawPileCount}
|
||||
</span>
|
||||
</button>
|
||||
<div
|
||||
className="un-discard"
|
||||
data-drop={over}
|
||||
aria-label={top ? `바닥 카드 ${cardName(top)}${v.color ? `, 지금 색 ${COLOR_KO[v.color]}` : ''}` : '바닥 카드 없음'}
|
||||
role="img"
|
||||
style={{ '--cc': v.color ? COLOR_HEX[v.color] : 'transparent' } as CSSProperties}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setOver(true);
|
||||
}}
|
||||
onDragLeave={() => setOver(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setOver(false);
|
||||
const id = e.dataTransfer.getData('text/plain');
|
||||
if (id) onDropCard(id);
|
||||
}}
|
||||
>
|
||||
{recent.slice(-3).map((c, i, arr) => {
|
||||
const last = i === arr.length - 1;
|
||||
const rot = last ? 0 : (i - arr.length + 1) * 9;
|
||||
return (
|
||||
<span key={`${v.discardCount - arr.length + i}`} className={`un-face${last ? ' top' : ''}`} style={{ transform: `rotate(${rot}deg) translate(${rot * 0.6}px, 0)` }}>
|
||||
<Face card={c} />
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="un-info">
|
||||
{v.color ? (
|
||||
<span key={v.color} className="un-color" style={{ background: COLOR_HEX[v.color], color: COLOR_INK[v.color] }} aria-live="polite">
|
||||
<span className="sw" aria-hidden />
|
||||
지금 색: {COLOR_KO[v.color]}
|
||||
</span>
|
||||
) : (
|
||||
<span className="un-chip">시작 색을 고르는 중</span>
|
||||
)}
|
||||
{v.pending > 0 && (
|
||||
<span key={v.pending} className="un-pending" aria-live="polite">
|
||||
+{v.pending}장!
|
||||
</span>
|
||||
)}
|
||||
<div className="row">
|
||||
<span className="un-dir" data-dir={v.direction} aria-label={v.direction === 1 ? '진행 방향: 시계 방향' : '진행 방향: 반대 방향'}>
|
||||
<b aria-hidden>↻</b>
|
||||
{v.direction === 1 ? '시계 방향' : '반대 방향'}
|
||||
</span>
|
||||
{next && v.current && v.phase !== 'wild4' && <span className="un-chip">다음: {nick(players, next.id)}</span>}
|
||||
</div>
|
||||
{v.wild4 && <span className="un-chip">{nick(players, v.wild4.target)}님이 도전할지 고르는 중</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- my hand
|
||||
|
||||
function useWidth<T extends HTMLElement>(): [React.RefObject<T | null>, number] {
|
||||
const ref = useRef<T>(null);
|
||||
const [w, setW] = useState(0);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
setW(el.clientWidth);
|
||||
const ro = new ResizeObserver(() => setW(el.clientWidth));
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
return [ref, w];
|
||||
}
|
||||
|
||||
function ColorSheet({ title, onPick, onClose }: { title: string; onPick: (c: Color) => void; onClose: () => void }) {
|
||||
return (
|
||||
<Sheet onClose={onClose} label="색 고르기">
|
||||
<h2>{title}</h2>
|
||||
<div className="un-pick">
|
||||
{COLORS.map((c) => (
|
||||
<button key={c} type="button" style={{ background: COLOR_HEX[c], color: COLOR_INK[c], borderColor: COLOR_HEX[c] }} onClick={() => onPick(c)}>
|
||||
{COLOR_KO[c]} <span className="small">({patternName(c)})</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button type="button" className="btn btn-secondary btn-block" onClick={onClose}>
|
||||
취소
|
||||
</button>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function MyHand({ v, act, pending, players }: { v: UnoView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
const my = v.my!;
|
||||
const [sortBy, setSortBy] = useState<'color' | 'number'>('color');
|
||||
const [sel, setSel] = useState<string | null>(null);
|
||||
const [armed, setArmed] = useState(false);
|
||||
const [hints, setHints] = useState(true);
|
||||
const [pick, setPick] = useState<string | null>(null);
|
||||
const [note, setNote] = useState('');
|
||||
const [ref, width] = useWidth<HTMLDivElement>();
|
||||
const hand = sortHand(my.hand, sortBy);
|
||||
const legal = new Set(my.playable);
|
||||
const bluff = new Set(my.bluff);
|
||||
const turnKey = `${v.turnNo}-${v.phase}`;
|
||||
useEffect(() => {
|
||||
setSel(null);
|
||||
setPick(null);
|
||||
setNote('');
|
||||
setArmed(false);
|
||||
}, [turnKey]);
|
||||
|
||||
const myTurn = v.current === v.me && (v.phase === 'turn' || v.phase === 'afterDraw' || (v.phase === 'wild4' && my.playable.length > 0));
|
||||
const byId = (id: string) => my.hand.find((c) => c.id === id);
|
||||
const send = (id: string, extra: Record<string, unknown> = {}) => {
|
||||
act({ type: 'play', cardId: id, ...extra, ...(armed && my.hand.length === 2 ? { uno: true } : {}) });
|
||||
setSel(null);
|
||||
setPick(null);
|
||||
};
|
||||
const playId = (id: string) => {
|
||||
const c = byId(id);
|
||||
if (!c || !legal.has(id) || pending) return;
|
||||
if (isWild(c)) setPick(id);
|
||||
else send(id);
|
||||
};
|
||||
const tap = (c: UnoCard) => {
|
||||
if (pending) return;
|
||||
if (sel === c.id) return playId(c.id);
|
||||
if (!legal.has(c.id)) {
|
||||
setNote(myTurn ? `${cardName(c)}은(는) 지금 낼 수 없어요.` : '');
|
||||
return;
|
||||
}
|
||||
setNote('');
|
||||
setSel(c.id);
|
||||
};
|
||||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||||
const btns = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>('button.un-card'));
|
||||
const i = btns.indexOf(document.activeElement as HTMLButtonElement);
|
||||
if (i < 0) return;
|
||||
e.preventDefault();
|
||||
btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length]?.focus();
|
||||
};
|
||||
|
||||
// One overlapping row on wide screens, wrapped rows on phones (cards ≥ 54 × 76).
|
||||
const n = hand.length;
|
||||
const phone = width > 0 && width < 600;
|
||||
const cw = phone ? 54 : 78;
|
||||
let ov = 6;
|
||||
if (!phone && n > 1) ov = Math.max(-cw * 0.6, Math.min(6, (width - cw * n) / (n - 1)));
|
||||
if (phone) ov = n > 12 ? -14 : 4;
|
||||
const selCard = sel ? byId(sel) : undefined;
|
||||
const hintText = selCard && hints ? my.hints[selCard.id] : '';
|
||||
// "우노!" button: call it now (one card left), or get it ready before playing the second-to-last card.
|
||||
const canArm = myTurn && my.hand.length === 2 && my.playable.length > 0;
|
||||
const unoLabel = my.canCallUno ? '우노! 외치기' : armed ? '우노! 준비됨. 다시 누르면 취소' : canArm ? '우노! 준비하기. 카드를 낼 때 함께 외쳐요' : '우노 (지금은 누를 수 없어요)';
|
||||
|
||||
return (
|
||||
<div className="un-hand-wrap">
|
||||
<div className="un-tools">
|
||||
<strong>
|
||||
내 카드 {n}장{my.drawnCardId ? ' · 방금 뽑은 카드를 낼 수 있어요' : ''}
|
||||
</strong>
|
||||
<div className="row" style={{ gap: 6 }}>
|
||||
<div className="segmented" role="group" aria-label="손패 정렬">
|
||||
<button type="button" aria-pressed={sortBy === 'color'} onClick={() => setSortBy('color')}>
|
||||
색깔별
|
||||
</button>
|
||||
<button type="button" aria-pressed={sortBy === 'number'} onClick={() => setSortBy('number')}>
|
||||
숫자별
|
||||
</button>
|
||||
</div>
|
||||
<label className="row small" style={{ gap: 4, cursor: 'pointer' }}>
|
||||
<input type="checkbox" checked={hints} onChange={(e) => setHints(e.target.checked)} style={{ width: 20, height: 20 }} />
|
||||
힌트
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
ref={ref}
|
||||
className={`un-hand${phone ? ' wrap' : ''}`}
|
||||
role="group"
|
||||
aria-label="내 카드. 좌우 방향키로 고르고 Enter로 들어 올리거나 내요"
|
||||
onKeyDown={onKey}
|
||||
style={{ '--cw': `${cw}px`, '--ov': `${ov}px` } as CSSProperties}
|
||||
>
|
||||
{hand.map((c) => {
|
||||
const ok = legal.has(c.id);
|
||||
const picked = sel === c.id;
|
||||
const reason = hints && ok ? my.hints[c.id] : '';
|
||||
return (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
className="un-card"
|
||||
data-legal={myTurn ? ok : undefined}
|
||||
data-bluff={myTurn && hints && bluff.has(c.id) ? true : undefined}
|
||||
data-id={c.id}
|
||||
aria-pressed={picked}
|
||||
draggable={ok && !pending}
|
||||
onDragStart={(e) => e.dataTransfer.setData('text/plain', c.id)}
|
||||
onClick={() => tap(c)}
|
||||
aria-label={`${cardName(c)}${my.drawnCardId === c.id ? ', 방금 뽑은 카드' : ''}${myTurn ? (ok ? ', 낼 수 있음' : ', 낼 수 없음') : ''}${picked ? ', 골랐음. 한 번 더 누르면 내요' : ''}`}
|
||||
title={reason || undefined}
|
||||
>
|
||||
<Face card={c} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{n === 0 && <span className="muted">손에 카드가 없어요.</span>}
|
||||
</div>
|
||||
{(note || hintText || armed) && (
|
||||
<p className="small" style={{ margin: 0 }} aria-live="polite">
|
||||
{note || hintText}
|
||||
{armed && ' · 우노! 준비됨: 카드를 내면 함께 외쳐요.'}
|
||||
</p>
|
||||
)}
|
||||
{/* Next to my cards, so a phone scrolled down to the hand still sees it. */}
|
||||
<CatchBar v={v} players={players} act={act} pending={pending} />
|
||||
<div className="un-actions">
|
||||
{myTurn && (
|
||||
<button type="button" className="btn btn-primary" disabled={!sel || !legal.has(sel) || pending} onClick={() => sel && playId(sel)}>
|
||||
내기
|
||||
</button>
|
||||
)}
|
||||
{my.canDraw && (
|
||||
<button type="button" className={`btn ${v.pending > 0 ? 'btn-danger' : 'btn-secondary'}`} disabled={pending} onClick={() => act({ type: 'draw' })}>
|
||||
{my.drawCount}장 뽑기
|
||||
</button>
|
||||
)}
|
||||
{my.canPass && (
|
||||
<button type="button" className="btn btn-secondary" disabled={pending} onClick={() => act({ type: 'pass' })}>
|
||||
넘기기
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={`un-unobtn${my.canCallUno ? ' call' : ''}`}
|
||||
disabled={pending || !(my.canCallUno || canArm)}
|
||||
aria-pressed={!my.canCallUno && canArm ? armed : undefined}
|
||||
aria-label={unoLabel}
|
||||
onClick={() => {
|
||||
haptic(40);
|
||||
if (my.canCallUno) act({ type: 'callUno' });
|
||||
else setArmed(!armed);
|
||||
}}
|
||||
>
|
||||
우노!
|
||||
</button>
|
||||
</div>
|
||||
{pick && <ColorSheet title="다음 색을 골라 주세요" onClose={() => setPick(null)} onPick={(color) => send(pick, { color })} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- prompts
|
||||
|
||||
function CatchBar({ v, players, act, pending }: { v: UnoView; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean }) {
|
||||
if (!v.my?.canCatchUno || !v.unoWindow) return null;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="un-catch"
|
||||
disabled={pending}
|
||||
onClick={() => {
|
||||
haptic(40);
|
||||
act({ type: 'catchUno' });
|
||||
}}
|
||||
>
|
||||
{nick(players, v.unoWindow.player)}님 우노 안 외쳤어요! (2장 벌칙)
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function StartColorPanel({ v, act, pending }: { v: UnoView; act: (a: unknown) => void; pending: boolean }) {
|
||||
if (!v.my?.canStartColor) return null;
|
||||
return (
|
||||
<div className="un-panel warn" role="group" aria-label="시작 색 고르기">
|
||||
<strong>시작 카드가 와일드예요. 처음 낼 색을 골라 주세요.</strong>
|
||||
<div className="un-pick">
|
||||
{COLORS.map((c) => (
|
||||
<button key={c} type="button" disabled={pending} style={{ background: COLOR_HEX[c], color: COLOR_INK[c], borderColor: COLOR_HEX[c] }} onClick={() => act({ type: 'startColor', color: c })}>
|
||||
{COLOR_KO[c]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Wild4Panel({ v, players, act, pending }: { v: UnoView; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean }) {
|
||||
if (!v.wild4 || !v.my?.canChallenge) return null;
|
||||
const by = nick(players, v.wild4.by);
|
||||
return (
|
||||
<div className="un-panel warn" role="group" aria-label="와일드 드로우4 도전">
|
||||
<strong>{by}님이 와일드 드로우4를 냈어요.</strong>
|
||||
<span className="small">
|
||||
{by}님이 그때 바닥 색 카드를 갖고 있었다고 생각하면 도전해요. 맞으면 {by}님이 {v.pending}장을 먹고, 틀리면 내가 {v.pending + 2}장을 먹어요. 도전하면 {by}님 카드를 나만 볼 수 있어요.
|
||||
{v.my.playable.length > 0 ? ' 와일드 드로우4를 내서 쌓을 수도 있어요.' : ''}
|
||||
</span>
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'challenge' })}>
|
||||
도전하기
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'accept' })}>
|
||||
받아들이기({v.pending}장 먹기)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RevealPanel({ v, players }: { v: UnoView; players: Record<string, PublicUser> }) {
|
||||
if (!v.reveal) return null;
|
||||
const by = nick(players, v.reveal.by);
|
||||
return (
|
||||
<div className="un-panel" aria-live="polite">
|
||||
<strong>{v.reveal.illegal ? `도전 성공! ${by}님은 그 색 카드가 있었어요.` : `${by}님은 규칙대로 냈어요. 도전이 틀렸어요.`}</strong>
|
||||
<span className="small muted">{by}님의 카드(나만 볼 수 있어요)</span>
|
||||
<div className="un-mini">
|
||||
{v.reveal.cards.map((c, i) => (
|
||||
<span key={i} title={cardName(c)}>
|
||||
<Face card={c} />
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RoundPanel({ v, players, act, pending }: { v: UnoView; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean }) {
|
||||
if (v.phase !== 'roundEnd') return null;
|
||||
const last = v.rounds[v.rounds.length - 1];
|
||||
return (
|
||||
<div className="un-panel" aria-live="polite">
|
||||
<strong>
|
||||
{v.round}판 결과: {last?.winner ? `${nick(players, last.winner)}님 +${last.points}점` : '이긴 사람 없음'}
|
||||
</strong>
|
||||
<span className="small">
|
||||
{[...v.seats]
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map((s) => `${nick(players, s.id)} ${s.score}점`)
|
||||
.join(' · ')}{' '}
|
||||
(500점 먼저)
|
||||
</span>
|
||||
{v.my?.canReady ? (
|
||||
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'ready' })}>
|
||||
다음 판으로
|
||||
</button>
|
||||
) : (
|
||||
<span className="small muted">다른 사람을 기다리는 중이에요…</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- log
|
||||
|
||||
function logText(e: LogEntry, players: Record<string, PublicUser>): string {
|
||||
const n = (id: string) => `${nick(players, id)}님`;
|
||||
switch (e.t) {
|
||||
case 'play':
|
||||
return `${n(e.p)}: ${cardName(e.card)}${e.color ? ` → ${COLOR_KO[e.color]}` : ''}`;
|
||||
case 'draw':
|
||||
switch (e.why) {
|
||||
case 'stack':
|
||||
return `${n(e.p)}이 쌓인 ${e.n}장을 먹었어요`;
|
||||
case 'penalty':
|
||||
return `${n(e.p)}이 우노를 안 외쳐서 ${e.n}장 먹었어요`;
|
||||
case 'draw2':
|
||||
case 'wild4':
|
||||
return `${n(e.p)}이 ${e.n}장 먹었어요`;
|
||||
case 'challenge':
|
||||
return `도전 결과로 ${n(e.p)}이 ${e.n}장 먹었어요`;
|
||||
case 'start':
|
||||
return `시작 카드가 드로우2라서 ${n(e.p)}이 ${e.n}장 먹었어요`;
|
||||
default:
|
||||
return `${n(e.p)}이 ${e.n}장 뽑았어요`;
|
||||
}
|
||||
case 'pass':
|
||||
return `${n(e.p)}이 넘겼어요`;
|
||||
case 'uno':
|
||||
return `${n(e.p)}: 우노!`;
|
||||
case 'caught':
|
||||
return `${n(e.by)}이 잡았어요! ${n(e.p)}이 우노를 안 외쳐서 ${e.n}장 먹어요`;
|
||||
case 'left':
|
||||
return `${n(e.p)}이 나갔어요`;
|
||||
case 'timeout':
|
||||
return `${n(e.p)}의 시간이 다 됐어요`;
|
||||
case 'reshuffle':
|
||||
return `버린 카드 ${e.n}장을 섞어 더미를 채웠어요`;
|
||||
case 'challenge':
|
||||
return `${n(e.p)}이 도전했어요: ${e.illegal ? `성공! ${n(e.by)}이 규칙을 어겼어요` : '실패, 규칙대로 냈어요'}`;
|
||||
case 'skip':
|
||||
return `${n(e.p)} 차례를 건너뛰어요`;
|
||||
case 'reverse':
|
||||
return '진행 방향이 바뀌었어요';
|
||||
case 'startColor':
|
||||
return `${n(e.p)}이 시작 색을 ${COLOR_KO[e.color]}으로 골랐어요`;
|
||||
case 'round':
|
||||
return `${e.round}판 끝 · ${e.winner ? `${n(e.winner)} +${e.points}점` : '이긴 사람 없음'}`;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<UnoView>) {
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const mine = isMyTurn(v, me);
|
||||
const prevMine = useRef(false);
|
||||
const lastLog = v.log[v.log.length - 1];
|
||||
useEffect(() => {
|
||||
if (mine && !prevMine.current) {
|
||||
haptic(40);
|
||||
sounds.myTurn();
|
||||
setAnnounce(v.pending > 0 ? `내 차례예요. ${v.pending}장이 쌓여 있어요.` : `내 차례예요.${v.color ? ` 지금 색은 ${COLOR_KO[v.color]}이에요.` : ''}`);
|
||||
}
|
||||
prevMine.current = mine;
|
||||
}, [mine]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (lastLog && !mine) setAnnounce(logText(lastLog, players));
|
||||
}, [lastLog?.seq, lastLog?.t]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const myIdx = v.seats.findIndex((s) => s.id === me);
|
||||
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
||||
const opps = useSeatRows<HTMLUListElement>(others.length);
|
||||
const canDraw = !!v.my?.canDraw && !pending;
|
||||
const meSeat = v.seats.find((s) => s.id === me);
|
||||
const next = v.phase === 'wild4' ? undefined : nextOf(v, v.current);
|
||||
return (
|
||||
<div className="un">
|
||||
<style>{CSS}</style>
|
||||
<ul className="un-opps" aria-label="다른 사람" ref={opps.ref} style={opps.style}>
|
||||
{others.map((s) => (
|
||||
<SeatChip key={s.id} s={s} v={v} players={players} me={me} deadline={deadline} next={next?.id === s.id} />
|
||||
))}
|
||||
</ul>
|
||||
<TableArea
|
||||
v={v}
|
||||
players={players}
|
||||
canDraw={canDraw}
|
||||
onDraw={() => act({ type: 'draw' })}
|
||||
onDropCard={(id) => {
|
||||
const c = v.my?.hand.find((x) => x.id === id);
|
||||
if (c && v.my!.playable.includes(id) && !isWild(c)) act({ type: 'play', cardId: id });
|
||||
}}
|
||||
/>
|
||||
<StartColorPanel v={v} act={act} pending={pending} />
|
||||
<Wild4Panel v={v} players={players} act={act} pending={pending} />
|
||||
<RevealPanel v={v} players={players} />
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
{v.my && meSeat && !meSeat.left && v.phase !== 'roundEnd' && v.phase !== 'finished' && <MyHand v={v} act={act} pending={pending} players={players} />}
|
||||
{meSeat?.left && v.phase !== 'finished' && (
|
||||
<div className="un-panel">
|
||||
<strong>게임에서 나갔어요.</strong>
|
||||
</div>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function rulesLine(o: UnoOptions): string {
|
||||
return [
|
||||
o.wild4Rule === 'challenge' ? '와일드 드로우4 도전 있음' : '와일드 드로우4는 지금 색이 없을 때만',
|
||||
o.stacking ? '드로우 카드 쌓기' : '',
|
||||
o.drawUntilPlayable ? '낼 수 있을 때까지 뽑기' : '',
|
||||
'우노 안 외치면 2장',
|
||||
o.scoring === 'to500' ? '500점 먼저' : '한 판',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
}
|
||||
|
||||
function UnoSide({ view: v, me, players, deadline }: BoardProps<UnoView>) {
|
||||
const multi = v.options.scoring === 'to500';
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>
|
||||
우노{multi ? ` · ${v.round}판` : ''}
|
||||
{v.phase === 'finished' ? ' · 게임 끝' : ''}
|
||||
</strong>
|
||||
{v.current && v.phase !== 'finished' && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={isMyTurn(v, me)} size={36} />}
|
||||
</div>
|
||||
<span className="small muted">{rulesLine(v.options)}</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{v.seats.map((s) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.left ? 0.55 : 1 }} aria-label={seatLabel(s, players, me, v)}>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }}>
|
||||
{s.isTurn ? '▶ ' : ''}
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{s.left ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
</span>
|
||||
{multi && <span className="small">{s.score}점</span>}
|
||||
<span className="un-count" aria-hidden>
|
||||
<i />
|
||||
{s.cards}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.players.map((p) => (
|
||||
<span key={p.player}>
|
||||
{p.rank}등 {nick(players, p.player)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {p.left ? '나감' : multi ? `${p.points}점` : p.rank === 1 ? `${p.points}점` : `남은 카드 ${p.cardsLeft}장(${p.handPoints}점)`}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
{v.log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
<ol className="un-log">
|
||||
{[...v.log].reverse().map((e) => (
|
||||
<li key={`${e.seq}-${e.t}-${'p' in e ? e.p : ''}`} className="small">
|
||||
{logText(e, players)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
<details className="card" style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>특수 카드</summary>
|
||||
<SpecialTable o={v.options} />
|
||||
</details>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- status
|
||||
|
||||
function isMyTurn(v: UnoView, me: string | null): boolean {
|
||||
if (!me || !v.my) return false;
|
||||
if (v.phase === 'roundEnd') return v.my.canReady;
|
||||
if (v.phase === 'finished') return false;
|
||||
return v.current === me;
|
||||
}
|
||||
|
||||
function statusText(v: UnoView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.phase === 'roundEnd') return v.my?.canReady ? `${v.round}판이 끝났어요. 다음 판으로 넘어가 주세요` : `${v.round}판이 끝났어요. 다른 사람을 기다리는 중이에요`;
|
||||
const w = v.unoWindow;
|
||||
if (me && v.current === me) {
|
||||
if (v.phase === 'startColor') return '내 차례예요. 시작 색을 골라 주세요';
|
||||
if (v.phase === 'wild4') return '내 차례예요. 와일드 드로우4에 도전할지 골라 주세요';
|
||||
if (v.phase === 'afterDraw') return '내 차례예요. 뽑은 카드를 낼지 골라 주세요';
|
||||
if (v.pending > 0) return `내 차례예요 · ${v.pending}장이 쌓였어요! 쌓거나 뽑아 주세요`;
|
||||
return '내 차례예요';
|
||||
}
|
||||
if (w && !w.declared && w.player === me) return '카드가 1장 남았어요. 우노!를 누르세요!';
|
||||
if (!v.current) return '잠시만 기다려 주세요';
|
||||
if (v.phase === 'startColor') return `${nick(players, v.current)}님이 시작 색을 고르는 중이에요`;
|
||||
if (v.phase === 'wild4') return `${nick(players, v.current)}님이 도전할지 고르는 중이에요`;
|
||||
return `${nick(players, v.current)}님 차례예요`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>{label}</strong>
|
||||
{children}
|
||||
{help && <span className="small muted">{help}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const onOff: [boolean, string][] = [
|
||||
[false, '끄기'],
|
||||
[true, '켜기'],
|
||||
];
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<UnoOptions>) {
|
||||
const set = (patch: Partial<UnoOptions>) => onChange({ ...o, ...patch });
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<Field label="점수 방식" help={o.scoring === 'single' ? '한 판만 해요. 이긴 사람이 남의 카드 점수를 얻어요.' : '여러 판을 하며 점수를 모아 500점에 먼저 닿으면 이겨요.'}>
|
||||
<Seg label="점수 방식" value={o.scoring} options={[['single', '한 판'], ['to500', '500점 먼저']]} onChange={(scoring) => set({ scoring })} />
|
||||
</Field>
|
||||
<Field
|
||||
label="와일드 드로우4"
|
||||
help={o.wild4Rule === 'challenge' ? '공식 규칙: 지금 색 카드가 있어도 몰래 낼 수 있지만, 다음 사람이 도전할 수 있어요.' : '지금 색 카드가 손에 있으면 아예 낼 수 없어요(도전 없음).'}
|
||||
>
|
||||
<Seg label="와일드 드로우4" value={o.wild4Rule} options={[['challenge', '공식(도전)'], ['strict', '쉬운 규칙']]} onChange={(wild4Rule) => set({ wild4Rule })} />
|
||||
</Field>
|
||||
<Field label="(하우스 룰) 드로우 카드 쌓기" help="드로우2에 드로우2·와일드 드로우4를, 와일드 드로우4에 와일드 드로우4를 쌓아 다음 사람에게 넘겨요.">
|
||||
<Seg label="드로우 카드 쌓기" value={o.stacking} options={onOff} onChange={(stacking) => set({ stacking })} />
|
||||
</Field>
|
||||
<Field label="(하우스 룰) 낼 수 있을 때까지 뽑기" help="뽑을 때 낼 수 있는 카드가 나올 때까지 계속 뽑아요.">
|
||||
<Seg label="낼 수 있을 때까지 뽑기" value={o.drawUntilPlayable} options={onOff} onChange={(drawUntilPlayable) => set({ drawUntilPlayable })} />
|
||||
</Field>
|
||||
<Field label="한 턴 제한 시간">
|
||||
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: UnoOptions): string {
|
||||
const parts = [o.scoring === 'to500' ? '500점 먼저' : '한 판', o.wild4Rule === 'challenge' ? '+4 도전' : '+4 제한'];
|
||||
if (o.stacking) parts.push('쌓기');
|
||||
if (o.drawUntilPlayable) parts.push('나올 때까지 뽑기');
|
||||
parts.push(`${o.turnSeconds}초`);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
|
||||
function SpecialTable({ o }: { o: UnoOptions }) {
|
||||
const C = (c: CardFace) => <Face card={c} />;
|
||||
const rows: [ReactNode, string, string][] = [
|
||||
[C({ kind: 'skip', color: 'R' }), '스킵', '다음 사람 차례를 건너뛰어요. (20점)'],
|
||||
[C({ kind: 'reverse', color: 'Y' }), '리버스', '진행 방향이 반대로 바뀌어요. 2명이면 스킵과 같아요. (20점)'],
|
||||
[C({ kind: 'draw2', color: 'G' }), '드로우2', `다음 사람이 2장을 먹고 차례를 건너뛰어요.${o.stacking ? ' 드로우2·와일드 드로우4로 쌓을 수 있어요.' : ''} (20점)`],
|
||||
[C({ kind: 'wild' }), '와일드', '언제든 내고 다음 색을 골라요. (50점)'],
|
||||
[
|
||||
C({ kind: 'wild4' }),
|
||||
'와일드 드로우4',
|
||||
`색을 고르고, 다음 사람이 4장을 먹고 차례를 건너뛰어요. 지금 색 카드가 없을 때만 낼 수 있어요${o.wild4Rule === 'challenge' ? '(몰래 냈다면 도전받아요)' : ''}. (50점)`,
|
||||
],
|
||||
];
|
||||
return (
|
||||
<table className="un-rules small" style={{ borderCollapse: 'collapse', width: '100%', marginTop: 8 }}>
|
||||
<tbody>
|
||||
{rows.map(([pic, name, desc]) => (
|
||||
<tr key={name}>
|
||||
<td style={{ width: 44 }}>{pic}</td>
|
||||
<th scope="row" style={{ whiteSpace: 'nowrap' }}>
|
||||
{name}
|
||||
</th>
|
||||
<td>{desc}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: UnoOptions }) {
|
||||
const o: UnoOptions = { scoring: 'single', wild4Rule: 'challenge', stacking: false, drawUntilPlayable: false, turnSeconds: 20, ...(options ?? {}) };
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
카드 7장씩 받고, 손에 든 카드를 가장 먼저 모두 내면 이겨요. 바닥 카드와 <strong>색</strong>이나 <strong>숫자·기호</strong>가 같은 카드를 한 장 내요. 와일드는 언제든 낼 수 있어요.
|
||||
</p>
|
||||
<p>
|
||||
낼 카드가 없거나 내고 싶지 않으면 더미에서 {o.drawUntilPlayable ? '낼 수 있는 카드가 나올 때까지' : '1장을'} 뽑아요. 뽑은 카드가 맞으면 바로 낼 수 있고, 아니면 차례가 넘어가요.
|
||||
</p>
|
||||
<SpecialTable o={o} />
|
||||
{o.wild4Rule === 'challenge' && (
|
||||
<p>
|
||||
<strong>도전</strong>: 와일드 드로우4를 받은 사람은 도전할 수 있어요. 낸 사람이 그때 바닥 색 카드를 갖고 있었다면 낸 사람이 4장을 먹고, 아니었다면 도전한 사람이 6장을 먹고 차례를 건너뛰어요.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
<strong>우노!</strong>: 카드가 1장 남으면 [우노!] 버튼을 눌러요. 끝에서 두 번째 카드를 내기 전에 눌러 두거나, 내고 나서 바로 눌러도 돼요. 안 누른 걸 다음 사람이 차례를 시작하기 전에 누가
|
||||
[우노 안 외쳤어요!]로 잡으면 2장을 먹어요.
|
||||
</p>
|
||||
<p>
|
||||
시작 카드가 드로우2면 첫 사람이 2장을 먹고 건너뛰고, 스킵이면 건너뛰고, 리버스면 반대 방향으로 시작해요. 와일드면 첫 사람이 색을 골라요. 와일드 드로우4는 다시 섞어요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>점수</strong>: 이긴 사람은 다른 사람 손에 남은 카드 점수(숫자 그대로, 스킵·리버스·드로우2 20점, 와일드 50점)를 얻어요.
|
||||
{o.scoring === 'to500' ? ' 여러 판을 해서 500점에 먼저 닿으면 이겨요.' : ' 이 방은 한 판으로 끝나요.'}
|
||||
</p>
|
||||
<p>시간 안에 고르지 않으면 낼 수 있는 카드 하나를 자동으로 내요(와일드는 가장 많이 가진 색). 낼 카드가 없으면 1장 뽑아요.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<UnoView, UnoOptions> = {
|
||||
Board: UnoBoard,
|
||||
Side: UnoSide,
|
||||
statusText,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
83
apps/web/src/games/uno/quick.tsx
Normal file
83
apps/web/src/games/uno/quick.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
/** 우노 30초 규칙 요약 (docs/07 §5). */
|
||||
import type { CSSProperties } from 'react';
|
||||
import type { CardFace } from '@bg/games/uno';
|
||||
import { ColorCardArt } from '../one-card/ColorCard';
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
const row = { display: 'flex', alignItems: 'center', gap: 8 } as const;
|
||||
const label = { fontSize: 13, fontWeight: 800, color: '#374151', textAlign: 'center' } as const;
|
||||
|
||||
function Card({ card, w = 50, ring, dim }: { card: CardFace | null; w?: number; ring?: boolean; dim?: boolean }) {
|
||||
const style: CSSProperties = { width: w, height: w * 1.4, display: 'inline-block', borderRadius: 8, opacity: dim ? 0.45 : 1, boxShadow: ring ? '0 0 0 3px #16a34a' : undefined };
|
||||
return (
|
||||
<span style={style}>
|
||||
<ColorCardArt card={card} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<div style={row} aria-hidden>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'center' }}>
|
||||
<Card card={{ kind: 'num', color: 'R', value: 7 }} w={60} />
|
||||
<span style={label}>바닥</span>
|
||||
</div>
|
||||
<span style={{ fontSize: 26, fontWeight: 900 }}>←</span>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'center' }}>
|
||||
<div style={{ display: 'flex', gap: 4 }}>
|
||||
<Card card={{ kind: 'num', color: 'R', value: 2 }} ring />
|
||||
<Card card={{ kind: 'num', color: 'B', value: 7 }} ring />
|
||||
<Card card={{ kind: 'num', color: 'G', value: 4 }} dim />
|
||||
</div>
|
||||
<span style={label}>내 카드</span>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
alt: '바닥에 빨강 7이 있고, 내 카드 중 빨강 2와 파랑 7은 밝게, 초록 4는 어둡게 보여요',
|
||||
title: '색이나 숫자를 맞춰요',
|
||||
text: '바닥 카드와 색이나 숫자·기호가 같은 카드를 1장 내요. 낼 카드가 없으면 1장 뽑고, 맞으면 바로 내도 돼요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<div style={{ ...row, gap: 6 }} aria-hidden>
|
||||
<Card card={{ kind: 'skip', color: 'Y' }} />
|
||||
<Card card={{ kind: 'reverse', color: 'G' }} />
|
||||
<Card card={{ kind: 'draw2', color: 'B' }} />
|
||||
<Card card={{ kind: 'wild' }} />
|
||||
<Card card={{ kind: 'wild4' }} />
|
||||
</div>
|
||||
),
|
||||
alt: '노랑 스킵, 초록 리버스, 파랑 드로우2, 와일드, 와일드 드로우4 카드',
|
||||
title: '특수 카드',
|
||||
text: '스킵은 건너뛰기, 리버스는 방향 바꾸기, 드로우2는 2장 먹이기. 와일드는 색을 고르고, 드로우4는 4장도 먹여요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<div style={row} aria-hidden>
|
||||
<Card card={{ kind: 'num', color: 'Y', value: 5 }} w={60} />
|
||||
<span
|
||||
style={{
|
||||
width: 76,
|
||||
height: 76,
|
||||
borderRadius: '50%',
|
||||
border: '3px solid #7f1d1d',
|
||||
background: '#dc2626',
|
||||
color: '#fff',
|
||||
fontWeight: 900,
|
||||
fontSize: 18,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
우노!
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
alt: '카드 1장과 빨간 우노 버튼',
|
||||
title: '1장 남으면 우노!',
|
||||
text: '카드를 먼저 다 내면 이겨요. 1장 남으면 [우노!]를 눌러요. 안 누른 걸 다른 사람이 먼저 잡으면 2장을 먹어요.',
|
||||
},
|
||||
];
|
||||
@@ -29,6 +29,7 @@ export const GAME_ICON: Record<string, string> = {
|
||||
apple: '🍎',
|
||||
clue: '🔎',
|
||||
'connect-four': '🔴',
|
||||
uno: '🌈',
|
||||
};
|
||||
|
||||
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
|
||||
@@ -42,5 +43,7 @@ export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'apple'] },
|
||||
{ key: 'board', label: '판·주사위', ids: ['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'one-card', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] },
|
||||
{ key: 'board', label: '판·주사위', ids: ['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'mahjong', 'rummikub', 'davinci-code'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia'] },
|
||||
];
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
| `clue` | 클루 | 3~6 | M9 |
|
||||
| `connect-four` | 커넥트 포(사목) | 2 | M9 |
|
||||
| `old-maid` | 도둑잡기 | 2~8 | M9 |
|
||||
| `uno` | 우노 | 2~10 | M9 |
|
||||
|
||||
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).
|
||||
|
||||
|
||||
197
docs/games/uno.md
Normal file
197
docs/games/uno.md
Normal file
@@ -0,0 +1,197 @@
|
||||
# 우노 (`uno`)
|
||||
|
||||
> 마일스톤: M9 · 인원: 최소 2 ~ 최대 10명 · 예상 시간: 약 10~20분 · 난이도: 쉬움
|
||||
|
||||
## 1. 개요
|
||||
- 같은 색이나 같은 숫자·기호의 카드를 내서 손패를 가장 먼저 비우는 카드 게임. 한 장 남으면 "우노!"를 외쳐야 하고, 와일드 드로우4는 "도전"으로 거짓말을 잡을 수 있다.
|
||||
- 미국 3년 연속 판매 1위, 한국 KBG 2025 상반기 2위, 일본 설문 1위(조사 노트 `notes/game-research-20261012/synth.md` 84번). 원카드와 비슷해서 쉽게 배운다.
|
||||
- 인원: 공식 설명서 2~10명.
|
||||
- 규칙 출처: Mattel 공식 설명서(UNO 기본판). 새 게임 설명 노트에는 84번 설명 섹션이 없어 공식 규칙을 기준으로 정했다.
|
||||
- 원카드의 `uno-style`(색깔 카드) 모드와 별도 게임이다. 덱(108장)·카드 점수·카드 그림만 원카드 코드를 그대로 가져다 쓰고(`packages/games/src/one-card/cards.ts`, `apps/web/src/games/one-card/ColorCard.tsx`, 둘 다 수정 없음), 규칙 엔진·컴퓨터·화면은 따로 있다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `scoring` | 점수 방식 | `single`(한 판, 이긴 사람 점수만 계산) / `to500`(여러 판, 500점 먼저) | `single` |
|
||||
| `wild4Rule` | 와일드 드로우4 | `challenge`(공식: 몰래 낼 수 있고 다음 사람이 도전) / `strict`(쉬운 규칙: 지금 색 카드가 있으면 못 냄, 도전 없음) | `challenge` |
|
||||
| `stacking` | (하우스 룰) 드로우 카드 쌓기 | on / off | off |
|
||||
| `drawUntilPlayable` | (하우스 룰) 낼 수 있을 때까지 뽑기 | on / off | off |
|
||||
| `turnSeconds` | 턴 제한 시간 | 10 / 15 / 20 / 30 / 60초 | 20 |
|
||||
|
||||
- 손패는 공식대로 7장 고정, "우노" 벌칙은 공식대로 2장 고정이다.
|
||||
- 일부러 넣지 않은 것: 7-0 규칙(7로 손패 교환, 0으로 모두 돌리기), 점프인, 쇼앰 노머시 카드, 낮은 점수 방식(각자 자기 남은 점수를 쌓는 변형), 팀전.
|
||||
|
||||
## 3. 구성물
|
||||
108장 (원카드 색깔 카드 모드와 같은 덱)
|
||||
|
||||
| 카드 | 장수 | 점수 |
|
||||
|---|---|---|
|
||||
| 숫자 0 | 색마다 1장 (4장) | 0 |
|
||||
| 숫자 1~9 | 색마다 2장씩 (72장) | 숫자 그대로 |
|
||||
| 스킵 | 색마다 2장 (8장) | 20 |
|
||||
| 리버스 | 색마다 2장 (8장) | 20 |
|
||||
| 드로우2 | 색마다 2장 (8장) | 20 |
|
||||
| 와일드 | 4장 | 50 |
|
||||
| 와일드 드로우4 | 4장 | 50 |
|
||||
|
||||
- 색: 빨강·노랑·초록·파랑. 색약을 위해 색마다 무늬(점·줄·격자·물결)와 색 이름이 카드에 있다.
|
||||
- 카드 id: `R0`, `R1a`…`R9b`, `RSa`(스킵) `RRa`(리버스) `RDa`(드로우2), `W1`~`W4`(와일드), `F1`~`F4`(와일드 드로우4).
|
||||
|
||||
## 4. 준비(셋업)
|
||||
1. 첫 사람을 시드 RNG로 정한다(원작의 "카드를 뽑아 딜러 정하기" 대신). 딜러는 첫 사람의 바로 앞자리로 본다.
|
||||
2. 108장을 섞어 첫 사람부터 한 장씩 7장을 나눈다.
|
||||
3. 더미 맨 위 카드를 뒤집어 버린 카드 더미를 시작한다. 공식 처리:
|
||||
- 와일드 드로우4: 더미에 다시 넣고 섞은 뒤 새로 뒤집는다(드로우4가 아닐 때까지).
|
||||
- 드로우2: 첫 사람이 2장을 먹고 차례를 건너뛴다.
|
||||
- 스킵: 첫 사람을 건너뛴다.
|
||||
- 리버스: 딜러(첫 사람 앞자리)가 먼저 하고 방향이 반대(오른쪽)로 바뀐다. 2명이면 스킵과 같다(방향 표시는 그대로).
|
||||
- 와일드: 첫 사람이 시작 색을 고른 뒤(`startColor` 단계) 그 색에 맞춰 한다.
|
||||
- 숫자: 첫 사람부터 그대로 한다.
|
||||
4. 500점 방식에서 다음 판은 이전 판 첫 사람의 다음 자리부터(딜러가 왼쪽으로 넘어감) 시작한다.
|
||||
|
||||
## 5. 진행 규칙
|
||||
### 5.1 차례
|
||||
- 바닥 맨 위 카드와 **색**이 같거나, **숫자**가 같거나(숫자 카드끼리), **기호**가 같은(스킵·리버스·드로우2끼리) 카드를 1장 낸다. 와일드는 언제든 낼 수 있다. 바닥이 와일드면 고른 색만 맞춘다.
|
||||
- 내지 않고 더미에서 1장 뽑아도 된다(공식: 낼 카드가 있어도 뽑을 수 있음). 뽑은 카드가 낼 수 있으면 바로 그 카드만 낼 수 있고(`afterDraw` 단계), 안 내면 [넘기기]로 차례를 넘긴다. 손에 있던 다른 카드는 낼 수 없다.
|
||||
- (하우스 룰 `drawUntilPlayable`) 낼 수 있는 카드가 나올 때까지 계속 뽑고, 나온 카드를 바로 내거나 넘긴다.
|
||||
- 더미가 비면 버린 카드 더미(맨 위 1장 제외)를 섞어 채운다. 둘 다 비면 뽑지 못하고 차례가 넘어간다.
|
||||
|
||||
### 5.2 특수 카드
|
||||
- 스킵: 다음 사람을 건너뛴다.
|
||||
- 리버스: 방향을 바꾼다. 2명이면 스킵과 같다(낸 사람이 한 번 더).
|
||||
- 드로우2: 다음 사람이 2장을 먹고 차례를 건너뛴다.
|
||||
- 와일드: 다음 색을 고른다.
|
||||
- 와일드 드로우4: 다음 색을 고르고, 다음 사람이 4장을 먹고 차례를 건너뛴다. **지금 바닥 색과 같은 색 카드가 손에 없을 때만** 낼 수 있다(같은 숫자·기호의 다른 색 카드나 와일드는 있어도 됨).
|
||||
|
||||
### 5.3 와일드 드로우4 도전 (`wild4Rule = challenge`, 공식)
|
||||
- 규칙을 어기고(지금 색 카드가 있는데) 낼 수도 있다. 화면은 그런 카드에 노란 테두리와 "도전받으면 내가 4장을 먹어요" 힌트를 보여 준다.
|
||||
- 다음 사람은 [도전하기] / [받아들이기] 중 고른다(`wild4` 단계).
|
||||
- 받아들이기: 4장을 먹고 차례를 건너뛴다.
|
||||
- 도전: 낸 사람의 손패를 도전한 사람만 본다(`reveal`). 규칙을 어겼으면 낸 사람이 4장을 먹고, 도전한 사람은 평소처럼 자기 차례를 한다. 규칙대로 냈으면 도전한 사람이 6장(4+2)을 먹고 차례를 건너뛴다.
|
||||
- 어느 경우든 낸 사람이 고른 색은 그대로다.
|
||||
- 규칙 위반 여부(`illegal`)는 내는 순간 서버가 기록하고, 도전 전에는 어떤 화면에도 보내지 않는다.
|
||||
- `strict`이면 규칙에 어긋난 와일드 드로우4는 아예 낼 수 없고 도전 단계가 없다.
|
||||
|
||||
### 5.4 "우노!" 외치기 (직접 정한 세부)
|
||||
- 공식: 한 장 남을 때 "우노"를 외쳐야 하고, 안 외친 걸 **다음 사람이 차례를 시작하기 전에** 누가 잡으면 2장을 먹는다.
|
||||
- 화면에서는 이렇게 한다.
|
||||
- 내 차례에 카드가 2장이면 동그란 [우노!] 버튼이 켜진다. 누르면 "준비됨"이 되고, 카드를 낼 때 함께 외친다(`play.uno = true`).
|
||||
- 깜빡하고 냈으면 1장이 남은 순간부터 [우노!] 버튼이 흔들린다. 눌러서 외치면(`callUno`) 안전하다. 내 차례가 아니어도 된다.
|
||||
- 그사이 다른 사람(게임 중인 사람 누구나)에게는 [○○님 우노 안 외쳤어요! (2장 벌칙)] 버튼이 뜬다. 먼저 누르면(`catchUno`) 그 사람이 2장을 먹는다.
|
||||
- 기회는 **다음 차례 행동(누구든 카드 내기·뽑기·넘기기·도전 답·시간 초과)이 처리될 때** 끝난다. 그 뒤에는 외칠 필요도, 잡을 수도 없다.
|
||||
- 외치기 전에 다시 카드를 먹어 1장이 아니게 되면 기회도 끝난다.
|
||||
- 공정성: 서버가 먼저 도착한 요청만 처리한다. 외치기와 잡기가 거의 동시에 오면 먼저 온 쪽이 이긴다. 외친 뒤에는 잡기가 거절되고, 잡힌 뒤에는 외치기가 거절된다.
|
||||
- 컴퓨터는 자기 차례가 올 때(= 다음 사람일 때)만 잡기를 본다(아래 §9.1). 사람은 아무 때나 누를 수 있다.
|
||||
|
||||
### 5.5 (하우스 룰) 드로우 카드 쌓기 `stacking`
|
||||
- 드로우2 위에 드로우2나 와일드 드로우4, 와일드 드로우4 위에 와일드 드로우4를 내서 쌓인 장수를 다음 사람에게 넘긴다. 와일드 드로우4 위에 드로우2는 못 낸다.
|
||||
- 쌓을 카드가 없거나 안 쌓으면 [N장 뽑기]로 쌓인 장수를 모두 먹고 차례를 넘긴다.
|
||||
- 도전 규칙과 함께 쓰면 와일드 드로우4를 받은 사람은 도전·받아들이기·와일드 드로우4로 쌓기 중 고른다. 도전이 성공하면 낸 사람이 쌓인 장수 전부를 먹는다.
|
||||
|
||||
## 6. 승패와 점수 계산
|
||||
- 손패를 다 낸 사람이 그 판의 승자다. 마지막 카드가 드로우2·와일드 드로우4면 다음 사람이 그 장수를 먹은 뒤 점수를 센다(공식). 마지막 와일드 드로우4는 도전할 수 없다.
|
||||
- 점수(공식): 승자가 다른 사람 손에 남은 카드 점수를 모두 얻는다. 숫자 = 숫자 그대로, 스킵·리버스·드로우2 = 20, 와일드·와일드 드로우4 = 50.
|
||||
- 예: 남은 카드가 초록 9, 파랑 스킵 / 와일드, 와일드 드로우4, 노랑 0 → 9+20+50+50+0 = 129점.
|
||||
- `single`: 한 판으로 끝. 순위는 승자, 나머지는 남은 카드 점수가 적은 순(같으면 장수가 적은 순, 둘 다 같으면 공동 순위), 나간 사람은 맨 뒤. 결과 화면 점수: 승자 "129점", 나머지 "남은 카드 29점".
|
||||
- `to500`: 판마다 점수를 더해 500점 이상이 되는 순간 게임이 끝난다. 순위는 누적 점수 순(같으면 공동). 판 사이에는 모두 [다음 판으로]를 누르거나 8초가 지나면 다음 판을 나눈다.
|
||||
|
||||
## 7. 지역 룰 / 하우스 룰
|
||||
- 넣은 것(기본 끄기): 드로우 카드 쌓기, 낼 수 있을 때까지 뽑기.
|
||||
- 넣은 것(기본 켜기, 공식): 와일드 드로우4 도전. 끄면 "쉬운 규칙"(어긋난 드로우4는 못 냄).
|
||||
- 뺀 것: 7-0 규칙, 점프인, 쇼앰 노머시, 팀전, 우노 자동 외치기.
|
||||
|
||||
## 8. 엔진 설계
|
||||
### 8.1 상태(State)
|
||||
```ts
|
||||
interface UnoState {
|
||||
options: UnoOptions;
|
||||
seats: PlayerId[];
|
||||
hands: Record<PlayerId, UnoCard[]>; // 비공개
|
||||
drawPile: UnoCard[]; // 비공개, [0]이 맨 위
|
||||
discard: UnoCard[]; // 공개, 마지막이 맨 위
|
||||
color: Color | null; // 따라야 할 색 (시작 와일드에서 고르는 동안만 null)
|
||||
direction: 1 | -1;
|
||||
current: PlayerId;
|
||||
phase: { kind: 'startColor' } | { kind: 'turn' } | { kind: 'afterDraw'; drawnCardId }
|
||||
| { kind: 'wild4'; by; target; prevColor; illegal } | { kind: 'roundEnd' } | { kind: 'finished' };
|
||||
pending: number; // 쌓인 드로우 장수 / 도전 답을 기다리는 4장
|
||||
unoWindow: { player; declared } | null;
|
||||
leftOrder, turnStartedAt, seq, turnNo, timeoutsInRow, away,
|
||||
round, roundStarter, scores, rounds, ready,
|
||||
reveal: { to; by; cards: CardFace[]; illegal } | null; // 도전한 사람에게만
|
||||
log: LogEntry[]; // 공개 기록, 카드 id 없이 앞면만
|
||||
final: UnoFinal | null;
|
||||
}
|
||||
```
|
||||
### 8.2 액션
|
||||
| type | payload | 누가 / 언제 | 검증 조건 |
|
||||
|---|---|---|---|
|
||||
| `play` | `cardId`, `color?`, `uno?` | 차례인 사람(`turn`/`afterDraw`), 쌓기 켜짐이면 `wild4` 대상 | 손에 있음, 맞는 카드(§5.1~5.5), `afterDraw`면 뽑은 카드만, 와일드는 `color` 필수(와일드 아니면 금지) |
|
||||
| `draw` | - | 차례인 사람, `turn` | 언제든(공식). 쌓인 장수가 있으면 그만큼 |
|
||||
| `pass` | - | 차례인 사람, `afterDraw` | |
|
||||
| `callUno` | - | 1장 남은 본인 | 창이 열려 있고 아직 안 외침 |
|
||||
| `catchUno` | - | 게임 중인 다른 사람 누구나 | 창이 열려 있고 아직 안 외침 |
|
||||
| `challenge` / `accept` | - | `wild4` 대상 | |
|
||||
| `startColor` | `color` | 첫 사람, `startColor` | |
|
||||
| `ready` | - | `roundEnd`의 모든 사람 | 아직 준비 안 함 |
|
||||
| `timeout` / `leave` | - | 시스템 | 스키마에 없음 |
|
||||
### 8.3 공개/비공개 정보 (view)
|
||||
- 내 손패와 낼 수 있는 카드(`playable`), 카드별 힌트, 규칙에 어긋난 드로우4(`bluff`), 버튼 상태(`canDraw`·`canPass`·`canCallUno`·`canCatchUno`·`canChallenge`·`canStartColor`·`canReady`)만 내 화면에 있다.
|
||||
- 다른 사람은 장수(`cards`)·우노 상태(`uno: open|declared`)·점수만. 더미는 장수만. 버린 카드는 최근 4장(공개).
|
||||
- 도전 결과의 손패(`reveal`)는 도전한 사람 화면에만. `illegal`은 도전 전 어디에도 없다.
|
||||
- 이벤트·기록에는 카드 id를 넣지 않는다(앞면만): 다시 섞인 카드 id가 숨은 카드를 짐작하게 하지 않도록.
|
||||
- `secretsOf` = 내 손패 id + 더미 id. 테스트가 모든 화면을 검사한다.
|
||||
### 8.4 랜덤 요소
|
||||
- `setup`: 첫 사람(`rng.int`) → 덱 섞기 → 시작 드로우4면 다시 섞기.
|
||||
- 더미가 비었을 때 버린 카드 섞기, 다음 판 덱 섞기. 모두 `ctx.rng`.
|
||||
### 8.5 타이머·시간 초과·연결 끊김
|
||||
- 제한 시간 = `turnSeconds`(시작 색·도전 답도 같음). 판 사이 8초. 시간 초과가 3번 이어지면 "자리 비움"이 되어 5초만 기다린다(직접 행동하면 풀림).
|
||||
- 시간 초과 자동 행동(원카드 관례: 낼 수 있으면 낸다)
|
||||
- `turn`: 쌓인 드로우가 있으면 다 먹는다(자동으로 쌓지 않음). 아니면 낼 수 있는 카드 중 색 카드를 먼저(손패 순서 첫 장), 없으면 와일드, 그다음 규칙에 맞는 와일드 드로우4를 낸다. 와일드 색은 남은 손패에 가장 많은 색(같으면 빨강·노랑·초록·파랑 순). 낼 카드가 없으면 1장(하우스 룰이면 나올 때까지) 뽑고, 뽑은 카드가 맞으면 바로 낸다.
|
||||
- `afterDraw`: 뽑은 카드가 규칙에 맞으면 내고, 아니면(어긋난 드로우4) 넘긴다.
|
||||
- `wild4`: 받아들이기. `startColor`: 가장 많이 가진 색. `roundEnd`: 준비.
|
||||
- 자동으로 낸 카드로 1장이 남아도 "우노"는 자동으로 외치지 않는다(곧바로 [우노!]를 누를 수는 있음).
|
||||
- 나가기(`onLeave`): 손패를 더미 맨 아래에 그대로 넣고, 그 사람 차례였으면 다음 사람으로. 도전 답을 기다리던 드로우4를 낸 사람이 나가면 그 4장은 없어지고 대상이 평소처럼 한다. 한 명만 남으면 그 사람이 이긴다.
|
||||
### 8.6 종료 조건과 결과(GameResult)
|
||||
- `ranking`(§6), `scores`(한 판: 승자만 점수, 나머지 0 / 500점: 누적), `scoreText`(§6), `summary` 예: "가장 먼저 카드를 모두 내서 129점을 얻었어요", "3판 만에 512점으로 500점에 먼저 닿았어요".
|
||||
|
||||
## 9. UI/UX
|
||||
- 위: 다른 사람 칩(아바타·이름·남은 장수·"1장!"(빨강, 안 외침) / "우노!"(노랑, 외침) 배지·점수·차례 타이머). 다음 차례인 사람은 점선 테두리와 "다음".
|
||||
- 판: 더미(뽑을 수 있으면 노란 점선, 남은 장수) · 버린 카드(최근 3장, 맨 위 카드 둘레에 **지금 색 링**) · 정보(지금 색 큰 칩, 쌓인 장수 "+4장!", 진행 방향 화살표와 "시계 방향/반대 방향", "다음: ○○").
|
||||
- 내 카드: 색깔별/숫자별 정렬, 낼 수 있는 카드 초록 테두리, 어긋난 드로우4 노란 테두리, 눌러 올리고 한 번 더 누르거나 [내기], 판으로 끌어다 놓기(와일드 제외), 좌우 방향키 이동. 휴대폰은 두 줄로 감김.
|
||||
- 버튼: [내기] [N장 뽑기] [넘기기] 동그란 [우노!]. 잡기 버튼은 내 카드 바로 위(휴대폰에서 손패까지 내려도 보이게).
|
||||
- 창: 시작 색 고르기, 와일드 색 고르기(색 이름·무늬), 와일드 드로우4 도전, 도전 결과 손패(나만), 판 결과(500점).
|
||||
- 오른쪽: 규칙 요약 한 줄, 자리 목록, 최종 순위, 기록, 특수 카드 표.
|
||||
- 도움말: 30초 요약 3장(맞추기, 특수 카드, 우노!), [?] 지금 할 수 있는 것.
|
||||
- 카드 그림은 원카드 색깔 카드 그림을 그대로 쓴다(흰 마름모, 색마다 무늬). 와일드 카드 아래 글자는 "색 바꾸기"로 나온다.
|
||||
|
||||
### 9.1 컴퓨터 상대 (`packages/games/src/uno/bot.ts`)
|
||||
- 공통: 낼 수 있는 카드 중 점수를 매겨 고른다(`humanBest`로 레벨만큼 가끔 실수). 와일드는 아끼고, 같은 색이 많이 남는 카드, 높은 숫자를 먼저 낸다. 다음 사람이 2장 이하면 스킵·리버스·드로우2·드로우4를 먼저 쓴다. 고르는 색은 남은 손패에 가장 많은 색(같으면 무작위).
|
||||
- 쉬움(1~20): 우노를 깜빡하는 확률 35%(1단계)→15%(20단계), 남의 안 외침을 잡는 확률 30%부터, 고르는 색 30%는 아무 색, 도전 10%, 어긋난 드로우4를 가끔 냄.
|
||||
- 보통(21~40): 깜빡 5%→0%, 잡기 확률이 레벨 따라 올라감, 도전 25%.
|
||||
- 어려움(41~60): 우노를 절대 안 깜빡하고 항상 잡음, 드로우2는 다음 사람이 거의 끝날 때까지 아낌, 어긋난 드로우4는 절대 안 냄(뽑은 카드라도 넘김), 낸 사람 손패가 4장 이상이면 도전(그 색을 갖고 있었을 가능성이 큼).
|
||||
- 컴퓨터는 자기 차례가 왔을 때만 잡기를 판단한다(게임이 기다리는 사람 = `activePlayers`는 차례인 사람뿐). 그래서 컴퓨터도 사람처럼 놓칠 수 있고, 사람은 컴퓨터가 생각하는 동안 먼저 잡을 수 있다. 깜빡한 컴퓨터는 자기 차례가 다시 오면 외친다.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 같은 시드 같은 판, 7장씩, 108장 보존, 시작 드로우4 없음 (`uno.test.ts`)
|
||||
- [x] 시작 카드 드로우2·스킵·리버스(3명/2명)·와일드·숫자 처리
|
||||
- [x] 색·숫자·기호 맞추기, 와일드 색, 스킵, 리버스(2명=스킵), 드로우2
|
||||
- [x] 뽑기: 낼 카드가 있어도 뽑기, 뽑은 카드만 바로 내기/넘기기, 낼 수 있을 때까지 뽑기, 더미 다시 섞기
|
||||
- [x] 와일드 드로우4: 쉬운 규칙 거절, 몰래 내기, 도전 성공/실패, 받아들이기, 도전 결과는 도전한 사람만
|
||||
- [x] 쌓기: 드로우2 위 드로우2, 쌓인 장수 뽑기, 도전 단계에서 드로우4 쌓기
|
||||
- [x] 우노: 내면서 외치기, 깜빡 → 아무나 잡기 2장, 늦게 외치기, 다음 차례 행동 뒤에는 못 잡음, 2명 스킵
|
||||
- [x] 점수: 공식 값(129점 예시), 마지막 드로우2 먹이기, 500점 여러 판·다음 판 첫 사람
|
||||
- [x] 시간 초과: 색 카드 우선, 와일드 색, 뽑고 바로 내기, 어긋난 드로우4는 안 냄, 시작 색, 도전 답, 자리 비움
|
||||
- [x] 나가기: 손패 더미 아래, 차례 넘김, 드로우4 낸 사람이 나감, 마지막 1명 승리
|
||||
- [x] 무작위 300판(빠른 테스트 30판): 끝까지, 카드 보존, 화면·이벤트 유출 없음, onTimeout 항상 합법, 결정적 / 엔진 randomPlayout
|
||||
- [x] 컴퓨터: 맞는 카드, 와일드 아끼기, 색 고르기, 드로우2 아끼기, 드로우4 거짓말 안 함, 깜빡·잡기 확률(레벨별), 도전, 레벨별 끝까지 (`bot.test.ts`)
|
||||
- [x] 방에서 사람 1 + 컴퓨터 3이 끝까지 (`apps/server/src/rooms/uno.room.test.ts`)
|
||||
- [x] 도움말 (`apps/web/src/games/uno/help.test.ts`), E2E 3명 끝까지 (`e2e/games.e2e.ts uno`)
|
||||
|
||||
## 11. 참고 자료
|
||||
- Mattel UNO 공식 설명서(기본판): 108장 구성, 시작 카드 처리, 와일드 드로우4 도전(4장/6장), "UNO" 2장 벌칙, 점수(20/50점), 500점.
|
||||
- 원카드 문서 `docs/games/one-card.md` §4~§6(색깔 카드 모드): 같은 덱과 점수.
|
||||
|
||||
## 12. 메모 (상표·법적 주의 등)
|
||||
- "UNO"는 Mattel의 등록 상표다. 원카드 문서(§12)는 상표 때문에 "우노"라는 이름을 피했지만, 이 게임은 사용자가 이름(`uno`, "우노")을 정해 요청했다. 공개 서비스로 홍보한다면 이름을 다시 검토할 것.
|
||||
- 원작 로고·빨간 타원·카드 디자인은 쓰지 않는다. 카드 그림은 직접 만든 색깔 카드 그림(흰 마름모, 색마다 무늬)이다. 규칙 설명은 설명서 문장을 옮기지 않고 직접 썼다.
|
||||
103
e2e/games.e2e.ts
103
e2e/games.e2e.ts
@@ -1141,6 +1141,109 @@ const PLANS: Record<string, Plan> = {
|
||||
console.log(` one-card: ${turns} turns (${plays} plays, ${draws} draws)${finished ? ', game finished' : ''}`);
|
||||
},
|
||||
},
|
||||
uno: {
|
||||
// 3 players (PC host + 2 phones), official rules: whoever has the turn picks a start colour, answers a 와일드 드로우4
|
||||
// (challenges now and then), presses [우노!] before the second-to-last card (or not, to be caught), plays a
|
||||
// highlighted card (colour sheet for wilds) or draws / passes; a lit catch button is pressed. Until the game ends.
|
||||
players: 3,
|
||||
drive: async (pages) => {
|
||||
const statusOf = (p: Page) => p.locator('.turn-status').innerText().catch(() => '');
|
||||
const st = { turns: 0, plays: 0, draws: 0, wilds: 0, challenges: 0, armed: 0, missed: 0, unoCalls: 0, catches: 0, startColors: 0 };
|
||||
const shot = new Set<string>();
|
||||
const once = async (p: Page, name: string) => {
|
||||
if (shot.has(name)) return;
|
||||
shot.add(name);
|
||||
await p.screenshot({ path: join(SHOTS, `uno-${name}.png`) });
|
||||
};
|
||||
let finished = false;
|
||||
let shots = false;
|
||||
for (let t = 0; t < 3000 && st.turns < 400; t++) {
|
||||
if (await pages[0]!.getByRole('dialog', { name: '게임 결과' }).count()) {
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
let acted = false;
|
||||
for (const p of pages) {
|
||||
const catchBtn = p.locator('.un-catch');
|
||||
if ((await catchBtn.count()) && (await catchBtn.isEnabled().catch(() => false))) {
|
||||
await catchBtn.scrollIntoViewIfNeeded().catch(() => {});
|
||||
await once(p, 'catch');
|
||||
if (await catchBtn.click({ timeout: 1000 }).then(() => true, () => false)) st.catches++;
|
||||
}
|
||||
// The first missed call is left for the others to catch.
|
||||
const call = p.locator('.un-unobtn.call');
|
||||
if (st.catches > 0 && (await call.count()) && (await call.isEnabled().catch(() => false))) {
|
||||
if (await call.click({ timeout: 1000 }).then(() => true, () => false)) st.unoCalls++;
|
||||
}
|
||||
const before = await statusOf(p);
|
||||
if (!before.includes('내 차례예요')) continue;
|
||||
const startColor = p.getByRole('group', { name: '시작 색 고르기' }).getByRole('button').first();
|
||||
const challenge = p.getByRole('button', { name: '도전하기' });
|
||||
const accept = p.getByRole('button', { name: /^받아들이기/ });
|
||||
const card = p.locator('button.un-card[data-legal="true"]').first();
|
||||
if (await startColor.count()) {
|
||||
await once(p, 'start-color');
|
||||
await startColor.click();
|
||||
st.startColors++;
|
||||
} else if (await accept.count()) {
|
||||
await once(p, 'challenge');
|
||||
if (st.challenges < 2) {
|
||||
await challenge.click();
|
||||
st.challenges++;
|
||||
} else await accept.click();
|
||||
} else if (await card.count()) {
|
||||
// Two cards left: get "우노!" ready first, except the first time (so somebody can catch it).
|
||||
const uno = p.locator('.un-unobtn:not(.call)');
|
||||
if ((await p.locator('button.un-card').count()) === 2 && (await uno.isEnabled().catch(() => false))) {
|
||||
if (st.missed === 0) st.missed++;
|
||||
else {
|
||||
await uno.click();
|
||||
await p.locator('.un-unobtn[aria-pressed="true"]').waitFor({ timeout: 2000 });
|
||||
st.armed++;
|
||||
}
|
||||
}
|
||||
await card.click();
|
||||
await card.click();
|
||||
const pick = p.locator('.un-pick button').first();
|
||||
if (await pick.waitFor({ timeout: 400 }).then(() => true, () => false)) {
|
||||
await pick.click();
|
||||
st.wilds++;
|
||||
}
|
||||
st.plays++;
|
||||
} else {
|
||||
const pass = p.getByRole('button', { name: '넘기기' });
|
||||
if (await pass.count()) await pass.click();
|
||||
else await p.getByRole('button', { name: /장 뽑기$/ }).first().click();
|
||||
st.draws++;
|
||||
}
|
||||
await p.waitForFunction((s) => document.querySelector('.turn-status')?.textContent?.trim() !== s, before.trim(), { timeout: 5000 }).catch(() => {});
|
||||
st.turns++;
|
||||
acted = true;
|
||||
if (st.turns === 12 && !shots) {
|
||||
shots = true;
|
||||
const [host, phone] = pages as [Page, Page];
|
||||
await host.waitForTimeout(300);
|
||||
await host.screenshot({ path: join(SHOTS, 'uno-mid-pc.png') });
|
||||
await phone.screenshot({ path: join(SHOTS, 'uno-mid-phone.png') });
|
||||
await phone.screenshot({ path: join(SHOTS, 'uno-mid-phone-full.png'), fullPage: true });
|
||||
await host.emulateMedia({ colorScheme: 'dark' });
|
||||
await phone.emulateMedia({ colorScheme: 'dark' });
|
||||
await host.screenshot({ path: join(SHOTS, 'uno-mid-pc-dark.png') });
|
||||
await phone.screenshot({ path: join(SHOTS, 'uno-mid-phone-dark.png') });
|
||||
await host.emulateMedia({ colorScheme: 'light' });
|
||||
await phone.emulateMedia({ colorScheme: 'light' });
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (!acted) await pages[0]!.waitForTimeout(120);
|
||||
}
|
||||
if (!finished) throw new Error(`game did not finish after ${st.turns} turns ${JSON.stringify(st)}`);
|
||||
await pages[0]!.waitForTimeout(400);
|
||||
await pages[0]!.screenshot({ path: join(SHOTS, 'uno-result-pc.png') });
|
||||
await pages[1]!.screenshot({ path: join(SHOTS, 'uno-result-phone.png') });
|
||||
console.log(` uno: game finished ${JSON.stringify(st)}`);
|
||||
},
|
||||
},
|
||||
'davinci-code': {
|
||||
// 2 players, default options (choose colours): both pick 2+2 start tiles, then several real turns:
|
||||
// draw from a pile, tap an opponent's hidden tile, pick a number, confirm; after a hit press "여기서 멈추기".
|
||||
|
||||
@@ -34,6 +34,7 @@ import { mafiaBot } from '../mafia/bot';
|
||||
import { appleBot } from '../apple/bot';
|
||||
import { clueBot } from '../clue/bot';
|
||||
import { connectFourBot } from '../connect-four/bot';
|
||||
import { unoBot } from '../uno/bot';
|
||||
|
||||
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
|
||||
@@ -66,6 +67,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
clue: clueBot,
|
||||
'connect-four': connectFourBot,
|
||||
'old-maid': oldMaidBot,
|
||||
uno: unoBot,
|
||||
};
|
||||
|
||||
/** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */
|
||||
|
||||
@@ -29,6 +29,7 @@ import { mafia } from './mafia';
|
||||
import { apple } from './apple';
|
||||
import { clue } from './clue';
|
||||
import { connectFour } from './connect-four';
|
||||
import { uno } from './uno';
|
||||
|
||||
export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[omok.id]: omok,
|
||||
@@ -61,4 +62,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[apple.id]: apple,
|
||||
[clue.id]: clue,
|
||||
[connectFour.id]: connectFour,
|
||||
[uno.id]: uno,
|
||||
};
|
||||
|
||||
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);
|
||||
});
|
||||
@@ -54,6 +54,7 @@ export const BOT_GAMES: readonly string[] = [
|
||||
'apple',
|
||||
'clue',
|
||||
'connect-four',
|
||||
'uno',
|
||||
];
|
||||
|
||||
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1). */
|
||||
|
||||
@@ -41,6 +41,7 @@ export const CATALOG: CatalogEntry[] = [
|
||||
{ id: 'connect-four', nameKo: '커넥트 포', minPlayers: 2, maxPlayers: 2, minutes: '3~10', level: '쉬움', blurb: '열을 골라 돌을 떨어뜨려 네 개를 먼저 한 줄로! · 사목', available: true },
|
||||
{ id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },
|
||||
{ id: 'clue', nameKo: '클루', minPlayers: 3, maxPlayers: 6, minutes: '30~50', level: '보통', blurb: '저택 살인 사건! 질문과 소거법으로 범인·흉기·장소를 맞혀요', available: true },
|
||||
{ id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true },
|
||||
];
|
||||
|
||||
export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);
|
||||
|
||||
Reference in New Issue
Block a user