Files
joke-app/apps/web/src/games/uno/index.tsx
EJClaw ac37a6a6d8 카드 게임 시간 무제한(우노·뱅!·달무티·고스톱·도둑잡기·포커·바퀴벌레 포커·99), 공통 카드 움직임(card-fx), 우노·달무티·도둑잡기·포커 소리·애니메이션
- 무제한(null): 차례 시계·타임아웃 없음, 자리 비움만 짧은 시계, 연결 끊김은 방 유예 뒤 자동 행동 그대로
- 포커는 리바이 고르는 시간도 무제한 가능, 고스톱은 고·스톱 선택 시간도 무제한 가능, 뱅!은 반응 시간·캐릭터 고르기도
- card-fx: 날아가는 카드·칩(ghost), 제자리 날아오기, 배너, view 변화 감지 훅(처음 렌더·다시 보기는 건너뜀)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:04:11 +09:00

1052 lines
50 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 우노 화면 (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, sfx, sounds, tone } from '../../lib/feedback';
import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useChange, useNewEntries } from '../card-fx';
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';
/** 우노 sounds on top of the shared palette (synthesized, no files). */
const unoSfx = {
skip: () => {
tone(520, 80, 'square', 0.05);
tone(330, 140, 'square', 0.05, 80);
},
reverse: () => {
tone(420, 220, 'triangle', 0.1, 0, { slideTo: 900 });
tone(900, 220, 'triangle', 0.08, 160, { slideTo: 420 });
},
wild: () => [523, 659, 784, 1046].forEach((f, i) => tone(f, 90, 'triangle', 0.08, i * 55)),
/** Heavy "+2 / +4" thump. */
plus: () => {
tone(170, 180, 'sawtooth', 0.07, 0, { slideTo: 80 });
tone(110, 220, 'sine', 0.16);
},
};
/** Where my last played card was (its button is gone once the view arrives), so the pile card flies from there. */
let myPlayRect: DOMRect | null = null;
const rememberPlay = (id: string) => {
myPlayRect = document.querySelector(`.un-card[data-id="${cssEsc(id)}"]`)?.getBoundingClientRect() ?? null;
};
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[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-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 anim-glow' : next ? ' next' : ''}${s.left ? ' gone' : ''}`} data-fx-seat={s.id} 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-fx="uno-deck" 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 anim-pop" 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);
useNewEntries(my.hand, (c) => c.id, (fresh) => {
const deck = fxEl('uno-deck');
fresh.forEach((c, i) => flyFrom(document.querySelector(`.un-card[data-id="${cssEsc(c.id)}"]`), deck, { delay: i * 70, rotate: 8 }));
}, 30);
const send = (id: string, extra: Record<string, unknown> = {}) => {
rememberPlay(id);
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);
sfx.select();
};
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}
data-fx="uno-hand"
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 [banner, showBanner] = useBanner();
useUnoFx(v, me, players, showBanner);
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)) {
rememberPlay(id);
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>
{banner}
</div>
);
}
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
function useUnoFx(v: UnoView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
useNewEntries(v.log, logKey, (fresh) => {
let t = 0;
for (const e of fresh) {
const at = t;
switch (e.t) {
case 'play': {
const top = document.querySelector('.un-discard .un-face.top');
flyFrom(top, e.p === me ? (myPlayRect ?? fxEl('uno-hand')) : seatEl(e.p), { ms: 340, rotate: -14 });
if (e.p === me) myPlayRect = null;
later(at, () => {
sfx.cardPlay();
if (e.card.kind === 'wild') unoSfx.wild();
if (e.card.kind === 'draw2' || e.card.kind === 'wild4') unoSfx.plus();
});
if (e.card.kind === 'wild4') showBanner('+4', 'dark', e.color ? `${COLOR_KO[e.color]}으로` : undefined);
else if (e.card.kind === 'draw2') showBanner('+2', 'red');
t += 120;
break;
}
case 'draw': {
const n = Math.min(e.n, 8);
if (e.p !== me) flyGhost(fxEl('uno-deck'), seatEl(e.p), { count: n, gap: 80 });
later(at, () => sfx.draw(Math.min(n, 4)));
if (e.why === 'penalty' || e.why === 'challenge' || e.why === 'stack' || e.n >= 4) later(at, () => bump(seatEl(e.p), 'shake'));
t += 120;
break;
}
case 'uno':
showBanner('우노!', 'red', e.p === me ? undefined : `${nick(players, e.p)}님`);
later(at, sfx.fanfare);
bump(seatEl(e.p));
break;
case 'caught':
showBanner('잡았다!', 'gold', `${nick(players, e.p)}님 +${e.n}장`);
later(at, sfx.alarm);
break;
case 'challenge':
showBanner(e.illegal ? '도전 성공!' : '도전 실패', e.illegal ? 'green' : 'dark');
later(at + 150, e.illegal ? sfx.good : sfx.bad);
break;
case 'skip':
later(at + 80, unoSfx.skip);
bump(seatEl(e.p), 'shake');
break;
case 'reverse':
later(at + 80, unoSfx.reverse);
bump(document.querySelector('.un-dir b'));
break;
case 'reshuffle':
later(at, sfx.shuffle);
bump(fxEl('uno-deck'), 'shake');
break;
case 'startColor':
later(at, unoSfx.wild);
break;
case 'round':
if (e.winner) {
const to = seatEl(e.winner) ?? fxEl('uno-hand');
for (const s of v.seats) if (s.id !== e.winner && !s.left) flyGhost(seatEl(s.id), to, { count: 3, gap: 60 });
later(at + 200, sfx.collect);
}
break;
case 'timeout':
later(at, sfx.tick);
break;
default:
break;
}
}
});
// A new round (or the very first deal): cards are dealt from the deck to everyone.
// `myHand`: only on mount — on a later round MyHand's own new-card motion already flies my cards in.
const deal = (myHand: boolean) => {
const deck = fxEl('uno-deck');
sfx.shuffle();
setTimeout(() => sfx.deal(7, 60), 300);
if (myHand) document.querySelectorAll('.un-hand .un-card').forEach((el, i) => flyFrom(el, deck, { delay: 280 + i * 60, rotate: 10 }));
for (const s of v.seats) if (s.id !== me && !s.left) flyGhost(deck, seatEl(s.id), { count: 3, gap: 90, delay: 280 });
};
useChange(v.round, () => deal(false));
const started = useRef(false);
useLayoutEffect(() => {
if (started.current) return;
started.current = true;
// Mounted right at the start of the game (nothing played yet): show the deal once.
if (v.round === 1 && v.discardCount <= 1 && !v.log.some((e) => e.t === 'play')) deal(true);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
}
const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`;
// ---------------------------------------------------------------- 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={logKey(e)} 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 | null>({ 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초'], [null, '무제한']]} 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 === null ? '시간 무제한' : `${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>
{o.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 낼 수 있는 카드 하나를 자동으로 내요(와일드는 가장 많이
가진 색). 낼 카드가 없으면 1장 뽑아요.
</p>
</div>
);
}
const ui: GameUI<UnoView, UnoOptions> = {
Board: UnoBoard,
Side: UnoSide,
statusText,
isMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;