/** 우노 화면 (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'; import { fxMs } from '../../lib/motion'; const COLORS: Color[] = ['R', 'Y', 'G', 'B']; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; const userOf = (players: Record, 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; } } /* PC: fill the play column. The felt takes the spare height, piles and hand cards grow with the play area, seats get bigger. */ @media (min-width: 1100px) { .un { max-width: none; align-self: stretch; flex: 1 1 auto; min-height: 0; gap: 12px; } .un-opps { max-width: calc(var(--cols) * 256px - 4px); } .un-seat { max-width: 248px; padding: 8px 12px; font-size: clamp(.9rem, calc(var(--play-h) / 62), 1.1rem); } .un-table { flex: 1 1 auto; grid-template-columns: 1fr auto auto 1fr; gap: clamp(18px, 2vw, 40px); padding: 20px 28px; font-size: clamp(1rem, calc(var(--play-h) / 62), 1.2rem); } .un-table > .un-pile { grid-column: 2; } .un-hand { justify-content: center; } } @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 ( ); } // ---------------------------------------------------------------- seats function seatLabel(s: SeatView, players: Record, 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; me: string | null; deadline: number | null; next: boolean }) { const u = userOf(players, s.id); return (
  • {u.nickname} {s.isTurn && }
    {s.cards} {s.uno && ( {s.uno === 'declared' ? '우노!' : '1장!'} )} {s.left && 나감} {s.away && 자리 비움} {!s.isTurn && next && 다음} {v.options.scoring === 'to500' && {s.score}점}
  • ); } // ---------------------------------------------------------------- table function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: UnoView; players: Record; canDraw: boolean; onDraw: () => void; onDropCard: (id: string) => void }) { const [over, setOver] = useState(false); const pw = 'clamp(64px, min(9vw, var(--play-h) * .15), 210px)'; const recent = v.recent; const top = recent[recent.length - 1]; const drawText = `${v.my?.drawCount ?? 1}장 뽑기`; const next = nextOf(v, v.current); return (
    { 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 ( ); })}
    {v.color ? ( 지금 색: {COLOR_KO[v.color]} ) : ( 시작 색을 고르는 중 )} {v.pending > 0 && ( +{v.pending}장! )}
    ↻ {v.direction === 1 ? '시계 방향' : '반대 방향'} {next && v.current && v.phase !== 'wild4' && 다음: {nick(players, next.id)}}
    {v.wild4 && {nick(players, v.wild4.target)}님이 도전할지 고르는 중}
    ); } // ---------------------------------------------------------------- my hand /** Element width plus the PC play-area height (--play-h on .game-main; 0 under 1100px where it is not measured). */ function useWidth(): [React.RefObject, number, number] { const ref = useRef(null); const [w, setW] = useState(0); const [h, setH] = useState(0); useLayoutEffect(() => { const el = ref.current; if (!el) return; const main = el.closest('.game-main'); const update = () => { setW(el.clientWidth); setH(main && matchMedia('(min-width: 1100px)').matches ? parseFloat(getComputedStyle(main).getPropertyValue('--play-h')) || 0 : 0); }; update(); const ro = new ResizeObserver(update); ro.observe(el); if (main) ro.observe(main); return () => ro.disconnect(); }, []); return [ref, w, h]; } function ColorSheet({ title, onPick, onClose }: { title: string; onPick: (c: Color) => void; onClose: () => void }) { return (

    {title}

    {COLORS.map((c) => ( ))}
    ); } function MyHand({ v, act, pending, players }: { v: UnoView; act: (a: unknown) => void; pending: boolean; players: Record }) { const my = v.my!; const [sortBy, setSortBy] = useState<'color' | 'number'>('color'); const [sel, setSel] = useState(null); const [armed, setArmed] = useState(false); const [hints, setHints] = useState(true); const [pick, setPick] = useState(null); const [note, setNote] = useState(''); const [ref, width, playH] = useWidth(); 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 = {}) => { 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) => { if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; const btns = Array.from(e.currentTarget.querySelectorAll('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 : Math.round(Math.min(156, Math.max(78, playH * 0.12))); 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 (
    내 카드 {n}장{my.drawnCardId ? ' · 방금 뽑은 카드를 낼 수 있어요' : ''}
    {hand.map((c) => { const ok = legal.has(c.id); const picked = sel === c.id; const reason = hints && ok ? my.hints[c.id] : ''; return ( ); })} {n === 0 && 손에 카드가 없어요.}
    {(note || hintText || armed) && (

    {note || hintText} {armed && ' · 우노! 준비됨: 카드를 내면 함께 외쳐요.'}

    )} {/* Next to my cards, so a phone scrolled down to the hand still sees it. */}
    {myTurn && ( )} {my.canDraw && ( )} {my.canPass && ( )}
    {pick && setPick(null)} onPick={(color) => send(pick, { color })} />}
    ); } // ---------------------------------------------------------------- prompts function CatchBar({ v, players, act, pending }: { v: UnoView; players: Record; act: (a: unknown) => void; pending: boolean }) { if (!v.my?.canCatchUno || !v.unoWindow) return null; return ( ); } function StartColorPanel({ v, act, pending }: { v: UnoView; act: (a: unknown) => void; pending: boolean }) { if (!v.my?.canStartColor) return null; return (
    시작 카드가 와일드예요. 처음 낼 색을 골라 주세요.
    {COLORS.map((c) => ( ))}
    ); } function Wild4Panel({ v, players, act, pending }: { v: UnoView; players: Record; act: (a: unknown) => void; pending: boolean }) { if (!v.wild4 || !v.my?.canChallenge) return null; const by = nick(players, v.wild4.by); return (
    {by}님이 와일드 드로우4를 냈어요. {by}님이 그때 바닥 색 카드를 갖고 있었다고 생각하면 도전해요. 맞으면 {by}님이 {v.pending}장을 먹고, 틀리면 내가 {v.pending + 2}장을 먹어요. 도전하면 {by}님 카드를 나만 볼 수 있어요. {v.my.playable.length > 0 ? ' 와일드 드로우4를 내서 쌓을 수도 있어요.' : ''}
    ); } function RevealPanel({ v, players }: { v: UnoView; players: Record }) { if (!v.reveal) return null; const by = nick(players, v.reveal.by); return (
    {v.reveal.illegal ? `도전 성공! ${by}님은 그 색 카드가 있었어요.` : `${by}님은 규칙대로 냈어요. 도전이 틀렸어요.`} {by}님의 카드(나만 볼 수 있어요)
    {v.reveal.cards.map((c, i) => ( ))}
    ); } function RoundPanel({ v, players, act, pending }: { v: UnoView; players: Record; act: (a: unknown) => void; pending: boolean }) { if (v.phase !== 'roundEnd') return null; const last = v.rounds[v.rounds.length - 1]; return (
    {v.round}판 결과: {last?.winner ? `${nick(players, last.winner)}님 +${last.points}점` : '이긴 사람 없음'} {[...v.seats] .sort((a, b) => b.score - a.score) .map((s) => `${nick(players, s.id)} ${s.score}점`) .join(' · ')}{' '} (500점 먼저) {v.my?.canReady ? ( ) : ( 다른 사람을 기다리는 중이에요… )}
    ); } // ---------------------------------------------------------------- log function logText(e: LogEntry, players: Record): 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) { 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(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 (
      {others.map((s) => ( ))}
    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 }); } }} /> {v.my && meSeat && !meSeat.left && v.phase !== 'roundEnd' && v.phase !== 'finished' && } {meSeat?.left && v.phase !== 'finished' && (
    게임에서 나갔어요.
    )}

    {announce}

    {banner}
    ); } /** 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, showBanner: ReturnType[1]) { const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(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), fxMs(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) { const multi = v.options.scoring === 'to500'; return ( <>
    우노{multi ? ` · ${v.round}판` : ''} {v.phase === 'finished' ? ' · 게임 끝' : ''} {v.current && v.phase !== 'finished' && }
    {rulesLine(v.options)}
      {v.seats.map((s) => (
    1. {s.isTurn ? '▶ ' : ''} {nick(players, s.id)} {s.id === me ? ' (나)' : ''} {s.left ? ' · 나감' : s.away ? ' · 자리 비움' : ''} {multi && {s.score}점} {s.cards}
    2. ))}
    {v.result && (
    최종 순위 {v.result.players.map((p) => ( {p.rank}등 {nick(players, p.player)} {' '} · {p.left ? '나감' : multi ? `${p.points}점` : p.rank === 1 ? `${p.points}점` : `남은 카드 ${p.cardsLeft}장(${p.handPoints}점)`} ))} {v.result.summary}
    )} {v.log.length > 0 && (
    기록
      {[...v.log].reverse().map((e) => (
    1. {logText(e, players)}
    2. ))}
    )}
    특수 카드
    ); } // ---------------------------------------------------------------- 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 { 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({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { return (
    {options.map(([k, l]) => ( ))}
    ); } function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) { return (
    {label} {children} {help && {help}}
    ); } const onOff: [boolean, string][] = [ [false, '끄기'], [true, '켜기'], ]; function Options({ value: o, onChange }: OptionsProps) { const set = (patch: Partial) => onChange({ ...o, ...patch }); return (
    set({ scoring })} /> set({ wild4Rule })} /> set({ stacking })} /> set({ drawUntilPlayable })} /> set({ turnSeconds })} />
    ); } 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) => ; 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 ( {rows.map(([pic, name, desc]) => ( ))}
    {pic} {name} {desc}
    ); } function Rules({ options }: { options?: UnoOptions }) { const o: UnoOptions = { scoring: 'single', wild4Rule: 'challenge', stacking: false, drawUntilPlayable: false, turnSeconds: 20, ...(options ?? {}) }; return (

    카드 7장씩 받고, 손에 든 카드를 가장 먼저 모두 내면 이겨요. 바닥 카드와 색이나 숫자·기호가 같은 카드를 한 장 내요. 와일드는 언제든 낼 수 있어요.

    낼 카드가 없거나 내고 싶지 않으면 더미에서 {o.drawUntilPlayable ? '낼 수 있는 카드가 나올 때까지' : '1장을'} 뽑아요. 뽑은 카드가 맞으면 바로 낼 수 있고, 아니면 차례가 넘어가요.

    {o.wild4Rule === 'challenge' && (

    도전: 와일드 드로우4를 받은 사람은 도전할 수 있어요. 낸 사람이 그때 바닥 색 카드를 갖고 있었다면 낸 사람이 4장을 먹고, 아니었다면 도전한 사람이 6장을 먹고 차례를 건너뛰어요.

    )}

    우노!: 카드가 1장 남으면 [우노!] 버튼을 눌러요. 끝에서 두 번째 카드를 내기 전에 눌러 두거나, 내고 나서 바로 눌러도 돼요. 안 누른 걸 다음 사람이 차례를 시작하기 전에 누가 [우노 안 외쳤어요!]로 잡으면 2장을 먹어요.

    시작 카드가 드로우2면 첫 사람이 2장을 먹고 건너뛰고, 스킵이면 건너뛰고, 리버스면 반대 방향으로 시작해요. 와일드면 첫 사람이 색을 골라요. 와일드 드로우4는 다시 섞어요.

    점수: 이긴 사람은 다른 사람 손에 남은 카드 점수(숫자 그대로, 스킵·리버스·드로우2 20점, 와일드 50점)를 얻어요. {o.scoring === 'to500' ? ' 여러 판을 해서 500점에 먼저 닿으면 이겨요.' : ' 이 방은 한 판으로 끝나요.'}

    {o.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 낼 수 있는 카드 하나를 자동으로 내요(와일드는 가장 많이 가진 색). 낼 카드가 없으면 1장 뽑아요.

    ); } const ui: GameUI = { Board: UnoBoard, Side: UnoSide, statusText, isMyTurn, Options, optionsSummary, Rules, quickStart, helpNow, }; export default ui;