우노: 공식 규칙 엔진·컴퓨터 상대·화면·도움말·문서·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:
EJClaw
2026-10-12 22:31:32 +09:00
parent cf7523f862
commit 609f458ed2
20 changed files with 3536 additions and 0 deletions

View 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('게임이 끝났어요');
});

View 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);
}

View 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;

View 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장을 먹어요.',
},
];