/** 원카드 / 색깔 카드 화면 (docs/games/one-card.md §9). */ import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'; import type { Card, CardFace, Color, LogEntry, OneCardOptions, OneCardView, SeatView, Suit } from '@bg/games/one-card'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar, Sheet } from '../../components/ui'; import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { PLAYING_CARD_CREDIT, PlayingCard } from '../../components/cards/PlayingCard'; import { haptic, sounds, tone } from '../../lib/feedback'; import { useSeatRows } from '../../lib/seat-rows'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, colorCardLabel, patternName } from './ColorCard'; import { FX_CSS, useOneCardFx, type Fx } from './fx'; import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion'; const SUITS: Suit[] = ['S', 'H', 'D', 'C']; const COLORS: Color[] = ['R', 'Y', 'G', 'B']; const SUIT_SYMBOL: Record = { S: '♠', H: '♥', D: '◆', C: '♣' }; const SUIT_KO: Record = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' }; const SUIT_INK: Record = { S: '#111827', H: '#dc2626', D: '#dc2626', C: '#111827' }; const RANK_LABEL: Record = { 1: 'A', 11: 'J', 12: 'Q', 13: 'K' }; const RANK_KO: Record = { 1: '에이스', 11: '잭', 12: '퀸', 13: '킹' }; const TRUMP_RANK: Record = { 1: 'A', 10: 'T', 11: 'J', 12: 'Q', 13: 'K' }; const MODE_KO: Record = { classic: '원카드', 'uno-style': '색깔 카드' }; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; const rankLabel = (r: number) => RANK_LABEL[r] ?? String(r); /** Short name, e.g. "♥7", "흑백 조커", "빨강 5". */ function faceName(c: CardFace): string { if (c.kind === 'std') return `${SUIT_SYMBOL[c.suit]}${rankLabel(c.rank)}`; if (c.kind === 'joker') return c.joker === 'black' ? '흑백 조커' : '컬러 조커'; return colorCardLabel(c); } /** Screen-reader name, e.g. "하트 7", "스페이드 에이스". */ function ariaName(c: CardFace): string { if (c.kind === 'std') return `${SUIT_KO[c.suit]} ${RANK_KO[c.rank] ?? c.rank}`; return faceName(c); } function trumpId(c: CardFace): string { if (c.kind === 'joker') return c.joker === 'black' ? 'X1' : 'X2'; if (c.kind !== 'std') return ''; return `${TRUMP_RANK[c.rank] ?? String(c.rank)}${c.suit}`; } function sortHand(hand: Card[], by: 'suit' | 'rank'): Card[] { const suitIdx = (c: Card) => (c.kind === 'std' ? SUITS.indexOf(c.suit) : 'color' in c ? COLORS.indexOf(c.color) : 9); const rank = (c: Card) => c.kind === 'std' ? (c.rank === 1 ? 14 : c.rank) : c.kind === 'num' ? c.value : c.kind === 'skip' ? 10 : c.kind === 'reverse' ? 11 : c.kind === 'draw2' ? 12 : c.kind === 'wild' ? 20 : c.kind === 'wild4' ? 21 : 30; return [...hand].sort((a, b) => (by === 'suit' ? suitIdx(a) - suitIdx(b) || rank(a) - rank(b) : rank(a) - rank(b) || suitIdx(a) - suitIdx(b))); } const CSS = ` .oc { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 10px; align-self: center; } .oc-opps { display: flex; gap: 8px; overflow-x: auto; padding: 4px 2px 6px; margin: 0; list-style: none; scrollbar-width: thin; } .oc-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; } .oc-seat.turn { border-color: var(--focus); } .oc-seat.gone { opacity: .55; } .oc-seat .nm { font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; } .oc-count { display: inline-flex; align-items: center; gap: 4px; font-weight: 800; font-variant-numeric: tabular-nums; } .oc-count i { display: inline-block; width: 12px; height: 16px; border-radius: 3px; background: #1e3a8a; border: 1.5px solid #93c5fd; } .oc-badge { display: inline-block; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .78rem; line-height: 1.6; } .oc-one { background: #f59e0b; color: #1f2937; animation: oc-pop .25s ease; } .oc-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: 16px; align-items: center; color: #fff; } .oc-pile { position: relative; width: var(--pw); height: calc(var(--pw) * 1.4); padding: 0; border: 0; background: none; border-radius: 10px; cursor: default; } .oc-pile[data-can='true'] { cursor: pointer; } .oc-pile[data-can='true']::after { content: ''; position: absolute; inset: -5px; border-radius: 14px; border: 3px dashed #fde047; } .oc-pile .cnt { position: absolute; right: -6px; bottom: -8px; background: #111827; color: #fff; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .85rem; } .oc-discard { position: relative; width: calc(var(--pw) * 1.12); height: calc(var(--pw) * 1.12 * 1.4); } .oc-discard > .oc-face { position: absolute; inset: 0; } .oc-discard > .oc-face.top { animation: oc-fly .32s cubic-bezier(.2,.8,.3,1.1); } .oc-discard[data-drop='true'] { outline: 3px dashed #fde047; outline-offset: 4px; border-radius: 10px; } .oc-info { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; min-width: 0; text-shadow: 0 1px 2px rgba(0,0,0,.5); } .oc-info .row { gap: 6px; } .oc-attack { background: #b91c1c; color: #fff; font-size: 1.5rem; font-weight: 900; border-radius: 12px; padding: 2px 12px; animation: oc-pop .3s ease; text-shadow: none; } .oc-dir { display: inline-flex; align-items: center; gap: 4px; font-weight: 800; } .oc-dir b { display: inline-block; font-size: 1.5rem; transition: transform .3s ease; } .oc-dir[data-dir='-1'] b { transform: scaleX(-1); } .oc-chip { display: inline-flex; align-items: center; gap: 6px; background: rgba(0,0,0,.35); border-radius: 999px; padding: 2px 10px; font-weight: 800; } .oc-swatch { width: 18px; height: 18px; border-radius: 50%; border: 2px solid #fff; display: inline-block; } .oc-face { display: block; width: 100%; height: 100%; } .oc-face svg, .oc-face > span { width: 100% !important; height: 100% !important; display: block; } .oc-hand-wrap { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; } .oc-hand { display: flex; align-items: flex-end; padding-top: 16px; min-height: calc(var(--cw) * 1.4 + 18px); } .oc-hand.wrap { flex-wrap: wrap; row-gap: 18px; } .oc-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; } .oc-card + .oc-card { margin-left: var(--ov); } .oc-card[data-legal='true'] { box-shadow: 0 0 0 3px var(--success); } .oc-card[data-legal='false'] { opacity: .5; filter: grayscale(.4); cursor: default; } .oc-card[aria-pressed='true'] { transform: translateY(-16px); box-shadow: 0 0 0 4px var(--primary); z-index: 2; } .oc-card:hover[data-legal='true'] { transform: translateY(-6px); z-index: 1; } .oc-card[aria-pressed='true']:hover { transform: translateY(-16px); } .oc-card:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; z-index: 3; } .oc-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } .oc-actions .btn { flex: 1 1 auto; } .oc-onebtn { flex: none !important; width: 76px; height: 76px; border-radius: 50%; border: 3px solid #b45309; background: #fbbf24; color: #1f2937; font-weight: 900; font-size: 1.02rem; line-height: 1.1; padding: 0; cursor: pointer; box-shadow: 0 3px 8px rgba(0,0,0,.25); } .oc-onebtn:disabled { background: var(--surface-2); color: var(--text-sub); border-color: var(--border); box-shadow: none; cursor: not-allowed; } .oc-onebtn:not(:disabled) { animation: oc-shake .3s ease-in-out 3; } .oc-onebtn.urgent { animation: oc-shake .3s ease-in-out 3, oc-urgent 1s ease-in-out .9s infinite; } .oc-onebtn.wait { font-size: .85rem; } @keyframes oc-urgent { 50% { transform: scale(1.1); box-shadow: 0 0 0 6px rgba(251,191,36,.55), 0 0 22px rgba(245,158,11,.9); } } .oc-shuf { display: block; width: 100%; height: 100%; animation: oc-shuffle .6s ease both; } @keyframes oc-shuffle { 20% { transform: translateX(-10px) rotate(-8deg); } 40% { transform: translateX(10px) rotate(8deg); } 60% { transform: translateX(-6px) rotate(-4deg); } 80% { transform: translateY(-6px); } } .oc-tools { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; } .oc-tools .segmented button { min-height: 40px; padding: 0 12px; } .oc-panel { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 8px; } .oc-panel.warn { border: 3px solid var(--warning); } .oc-mini { display: flex; flex-wrap: wrap; gap: 4px; } .oc-mini .oc-face { width: 40px; height: 56px; } .oc-pick { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; } .oc-pick button { min-height: 72px; font-size: 1.3rem; font-weight: 900; border-radius: 14px; border: 3px solid var(--border); background: var(--surface); color: var(--text); cursor: pointer; } .oc-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 240px; overflow: auto; } .oc-rules td, .oc-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); } .oc-rules .oc-face { width: 34px; height: 48px; } @keyframes oc-fly { from { transform: translate(var(--fx, -40px), var(--fy, 30px)) rotate(-25deg) scale(.75); opacity: .4; } } @keyframes oc-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } } @keyframes oc-shake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-8deg); } 75% { transform: rotate(8deg); } } /* PC/tablet: many players stack into even rows (9 → 5 + 4) instead of scrolling sideways. Phones keep one swipeable row. */ @media (min-width: 720px) { .oc-opps { flex-wrap: wrap; justify-content: center; overflow: visible; width: 100%; max-width: calc(var(--cols) * 184px - 4px); margin: 0 auto; } .oc-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) { .oc { max-width: none; align-self: stretch; flex: 1 1 auto; min-height: 0; gap: 12px; } .oc-opps { max-width: calc(var(--cols) * 256px - 4px); } .oc-seat { max-width: 248px; padding: 8px 12px; font-size: clamp(.9rem, calc(var(--play-h) / 62), 1.1rem); } .oc-table { flex: 1 1 auto; grid-template-columns: 1fr auto auto 1fr; gap: clamp(16px, 2vw, 40px); padding: 20px 28px; font-size: clamp(1rem, calc(var(--play-h) / 62), 1.2rem); } .oc-table > .oc-pile { grid-column: 2; } .oc-hand { justify-content: center; } } @media (max-width: 719px) { .oc-table { grid-template-columns: auto auto; padding: 10px; gap: 10px; border-width: 6px; justify-content: center; } .oc-info { grid-column: 1 / -1; align-items: center; } .oc-info .row { justify-content: center; } .oc-seat { min-width: 96px; padding: 5px 6px; } .oc-onebtn { width: 64px; height: 64px; font-size: .92rem; } } `; // ---------------------------------------------------------------- cards function Face({ card, mode }: { card: CardFace | null; mode: OneCardView['mode'] }) { return ( {mode === 'classic' ? : } ); } // ---------------------------------------------------------------- seats function seatLabel(s: SeatView, players: Record, me: string | null, v: OneCardView): string { const parts = [`${nick(players, s.id)}${s.id === me ? '(나)' : ''}`, `카드 ${s.cards}장`]; if (s.status === 'out') parts.push('카드를 모두 냄'); if (s.status === 'bankrupt') parts.push('파산'); if (s.status === 'left') parts.push('나감'); if (s.away) parts.push('자리 비움'); if (s.isTurn) parts.push('차례'); if (s.oneCard === 'open') parts.push('원카드 외치기 전'); if (s.oneCard === 'declared') parts.push('원카드 외침'); if (v.options.unoTargetScore > 0 && v.mode === 'uno-style') parts.push(`${s.score}점`); return parts.join(', '); } function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView; players: Record; me: string | null; deadline: number | null }) { const u = userOf(players, s.id); const place = v.result?.players.find((p) => p.player === s.id)?.rank; // 다 냄 / 파산 and points change once the last card has landed. const status = useAfterMotionValue(s.status); const score = useAfterMotionValue(s.score); return (
  • {u.nickname} {s.isTurn && }
    {s.cards} {s.oneCard && ( {s.oneCard === 'declared' ? '원카드!' : '1장!'} )} {status === 'out' && {place ? `${place}등` : '다 냄'}} {status === 'bankrupt' && 파산} {s.status === 'left' && 나감} {s.away && 자리 비움} {v.mode === 'uno-style' && v.options.unoTargetScore > 0 && {score}점}
  • ); } // ---------------------------------------------------------------- table /** The stacked attack: counts up card by card (with a rising tick) when someone adds to it, and grows with the count. */ function AttackCount({ n, uno }: { n: number; uno: boolean }) { const [shown, setShown] = useState(n); const prev = useRef(n); useEffect(() => { const from = prev.current; prev.current = n; if (n <= from) { setShown(n); return; } let k = Math.max(from, 1); setShown(k); if (k >= n) return; const id = window.setInterval( () => { k += 1; setShown(k); tone(320 + k * 45, 55, 'square', 0.035); if (k >= n) window.clearInterval(id); }, fxMs(Math.max(45, Math.min(110, 420 / (n - from)))), ); return () => window.clearInterval(id); }, [n]); // Counting up card by card (timer steps): results wait for the count. useMotionHold(shown < n); if (n <= 0) return null; return ( +{shown}장! {uno ? '먹을 카드' : '공격 누적'} ); } function TableArea({ v, players, canDraw, onDraw, onDropCard, fx }: { v: OneCardView; players: Record; canDraw: boolean; onDraw: () => void; onDropCard: (id: string) => void; fx: Fx }) { const [over, setOver] = useState(false); const from = fx.playFrom && fx.playFrom.discard === v.discardCount ? fx.playFrom : null; const pw = 'clamp(64px, min(9vw, var(--play-h) * .15), 210px)'; const recent = v.recent; const top = recent[recent.length - 1]; const drawText = v.pendingAttack > 0 ? `${v.pendingAttack}장 먹기` : '1장 먹기'; 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.direction === 1 ? '시계 방향' : '반대 방향'} {v.extraTurn && K: 한 번 더}
    {v.declaredSuit && ( 지정 무늬 {SUIT_SYMBOL[v.declaredSuit]} {SUIT_KO[v.declaredSuit]} )} {v.mode === 'uno-style' && ( {v.currentColor ? ( <> 지금 색: {COLOR_KO[v.currentColor]} {v.declaredColor ? ' (지정)' : ''} ) : ( '아무 색이나 낼 수 있어요' )} )} {v.reference && 조커 밑 기준: {faceName(v.reference)}} {v.wild4 && ( {nick(players, v.wild4.target)}님이 의심할지 고르는 중 )}
    {fx.flash &&
    }
    {fx.banners.map((b) => (
    {b.text} {b.sub && {b.sub}}
    ))}
    ); } // ---------------------------------------------------------------- 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]; } interface PickState { ids: string[]; kind: 'suit' | 'color'; } function MyHand({ v, act, pending, players, arrived }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record; arrived: Record }) { const my = v.my!; const [sortBy, setSortBy] = useState<'suit' | 'rank'>('suit'); const [sel, setSel] = useState([]); 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.legalCardIds); const turnKey = `${v.turnNo}-${v.phase}`; useEffect(() => { setSel([]); setPick(null); setNote(''); }, [turnKey]); const byId = (id: string) => my.hand.find((c) => c.id === id); const sameRank = (a: Card, b: Card) => a.kind === 'std' && b.kind === 'std' && a.rank === b.rank; const leavesOne = sel.length > 0 && my.hand.length - sel.length === 1 && !v.options.autoDeclare; // Playing never calls "원카드!" (§5.3): that is the round button's own press afterwards. const send = (ids: string[], extra: Record = {}) => { act({ type: 'play', cardIds: ids, ...extra }); setSel([]); setPick(null); }; const playIds = (ids: string[]) => { const first = byId(ids[0]!); if (!first || !legal.has(first.id) || pending) return; if (first.kind === 'std' && first.rank === 7) setPick({ ids, kind: 'suit' }); else if (first.kind === 'wild' || first.kind === 'wild4') setPick({ ids, kind: 'color' }); else send(ids); }; const tap = (c: Card) => { if (pending) return; if (sel.includes(c.id)) { if (sel[0] === c.id || !my.multiPlay) playIds(sel); else setSel(sel.filter((x) => x !== c.id)); return; } const first = sel[0] ? byId(sel[0]) : undefined; if (my.multiPlay && first && sameRank(first, c) && v.phase === 'turn') { setSel([...sel, c.id]); return; } if (!legal.has(c.id)) { setNote(`${ariaName(c)}은(는) 지금 낼 수 없어요.`); return; } setNote(''); setSel([c.id]); }; const onKey = (e: KeyboardEvent) => { if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; const btns = Array.from(e.currentTarget.querySelectorAll('button.oc-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(); }; // Layout: one overlapping row on wide screens, wrapped rows on phones (cards ≥ 48 × 68). 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 myTurn = v.current === v.me && (v.phase === 'turn' || v.phase === 'afterDraw' || v.phase === 'wild4Response'); const selCard = sel[0] ? byId(sel[0]) : undefined; const hintText = selCard && hints ? my.hints[selCard.id] : ''; const counters = v.pendingAttack > 0 && myTurn ? my.legalCardIds.map((id) => byId(id)).filter((c): c is Card => !!c) : []; return (
    내 카드 {n}장{my.drawnCardId ? ' · 방금 먹은 카드를 낼 수 있어요' : ''}
    {hand.map((c) => { const isLegal = legal.has(c.id) || (my.multiPlay && !!selCard && sameRank(selCard, c) && v.phase === 'turn'); const picked = sel.includes(c.id); const reason = hints && legal.has(c.id) ? my.hints[c.id] : ''; return ( ); })} {n === 0 && 손에 카드가 없어요.}
    {(note || hintText || counters.length > 0) && (

    {note || hintText} {!note && counters.length > 0 && ` 막을 수 있는 카드: ${counters.map(faceName).join(', ')}`} {!note && v.pendingAttack > 0 && myTurn && counters.length === 0 && ' 막을 카드가 없어요. 카드를 먹어 주세요.'}

    )} 0 && legal.has(sel[0]!)} playLabel={sel.length > 1 ? `${sel.length}장 내기` : '내기'} onPlay={() => playIds(sel)} leavesOne={leavesOne} /> {pick && ( setPick(null)} label={pick.kind === 'suit' ? '무늬 고르기' : '색 고르기'}>

    {pick.kind === 'suit' ? '다음 무늬를 골라 주세요' : '다음 색을 골라 주세요'}

    {pick.kind === 'suit' ? SUITS.map((s) => ( )) : COLORS.map((c) => ( ))}
    )}
    ); } function ActionBar(props: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record; canPlay: boolean; playLabel: string; onPlay: () => void; leavesOne: boolean; }) { const { v, act, pending, players, canPlay, playLabel, onPlay, leavesOne } = props; const my = v.my!; const myTurn = v.current === v.me && (v.phase === 'turn' || v.phase === 'afterDraw' || (v.phase === 'wild4Response' && my.legalCardIds.length > 0)); return (
    {myTurn && ( )} {my.canDraw && ( )} {my.canPass && ( )} {myTurn && leavesOne && ( 내고 나면 1장이 남아요. 낸 다음 [원카드!]를 따로 눌러요. )}
    ); } /** * ms until others may catch the open window's owner (0 = now / not waiting). The owner may call at once; everyone * else waits out the protection time (`oneCardGrace`), counted on the server clock. */ function useCatchWait(v: OneCardView): number { const now = useServerNow(200); const w = v.oneCardWindow; if (!w || w.declared || w.player === v.me) return 0; // A little margin so a press right at the end is not refused for clock drift. return Math.max(0, w.catchFrom + 100 - now); } /** The round "원카드!" button: call my own one card, or catch someone who forgot (after the protection time). */ function OneCardButton({ v, act, pending, players }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record }) { const my = v.my!; const w = v.oneCardWindow; const wait = useCatchWait(v); const mine = !!w && w.player === v.me; const can = my.canDeclare && !pending && wait === 0; const secs = Math.ceil(wait / 1000); const label = !my.canDeclare || !w ? '원카드 (지금은 누를 수 없어요)' : mine ? '원카드 외치기' : wait > 0 ? `${nick(players, w.player)}님 잡기, ${secs}초 뒤에 누를 수 있어요` : `${nick(players, w.player)}님 잡기`; return ( ); } /** For players already out of the round: they may still catch. */ function CatchButton({ v, act, pending, players }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record }) { const wait = useCatchWait(v); const who = v.oneCardWindow ? nick(players, v.oneCardWindow.player) : ''; return ( ); } // ---------------------------------------------------------------- prompts function Wild4Panel({ v, players, act, pending }: { v: OneCardView; 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.pendingAttack}장을 먹고, 아니면 내가 {v.pendingAttack + 2}장을 먹어요. {v.options.unoStacking ? ' 색 바꾸기+4가 있으면 받아칠 수도 있어요.' : ''}
    ); } function RevealPanel({ v, players }: { v: OneCardView; 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: OneCardView; 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(' · ')}{' '} (목표 {v.options.unoTargetScore}점) {v.my?.canReady ? ( ) : ( 다른 사람을 기다리는 중이에요… )}
    ); } // ---------------------------------------------------------------- log function logText(e: LogEntry, players: Record): string { const n = (id: string) => `${nick(players, id)}님`; switch (e.t) { case 'play': { const extra = e.suit ? ` → ${SUIT_SYMBOL[e.suit]} 무늬로` : e.color ? ` → ${COLOR_KO[e.color]}으로` : ''; return `${n(e.p)}: ${e.cards.map(faceName).join(' ')}${extra}`; } case 'draw': switch (e.why) { case 'attack': 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 'blocked': return `${n(e.p)}이 3으로 공격을 막았어요`; case 'declare': return `${n(e.p)}이 원카드를 외쳤어요!`; case 'caught': return `${n(e.by)}이 먼저 외쳐서 ${n(e.p)}이 ${e.n}장 먹었어요`; case 'bankrupt': return `${n(e.p)}이 파산했어요`; case 'out': return `${n(e.p)}이 카드를 모두 냈어요 (${e.place}등)`; 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 'round': return `${e.round}판 끝 · ${e.winner ? `${n(e.winner)} +${e.points}점` : '이긴 사람 없음'}`; } } // ---------------------------------------------------------------- board function OneCardBoard({ 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.pendingAttack > 0 ? `내 차례예요. 공격 ${v.pendingAttack}장을 받고 있어요.` : '내 차례예요.'); } 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 // Opponents in turn order after me (spectators: seat order). 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 rootRef = useRef(null); const layerRef = useRef(null); const fx = useOneCardFx({ view: v, me, nick: (id) => nick(players, id) }, rootRef, layerRef); return (
      {others.map((s) => ( ))}
    act({ type: 'draw' })} onDropCard={(id) => { if (v.my?.legalCardIds.includes(id)) { const c = v.my.hand.find((x) => x.id === id); if (c && !((c.kind === 'std' && c.rank === 7) || c.kind === 'wild' || c.kind === 'wild4')) act({ type: 'play', cardIds: [id] }); } }} /> {v.my && meSeat && meSeat.status === 'playing' && v.phase !== 'roundEnd' && v.phase !== 'finished' && } {meSeat && meSeat.status !== 'playing' && v.phase !== 'finished' && v.phase !== 'roundEnd' && (
    {meSeat.status === 'out' ? '카드를 모두 냈어요! 다른 사람의 게임을 지켜봐요.' : meSeat.status === 'bankrupt' ? '파산했어요. 남은 게임을 지켜봐요.' : '게임에서 나갔어요.'} {meSeat.status === 'out' && v.my?.canDeclare && }
    )}

    {announce}

    ); } // ---------------------------------------------------------------- side function rulesLine(v: Pick): string { const o = v.options; if (v.mode === 'classic') { return `공격: 2 ${o.attack2}장 · A ${o.attackA}장 · ♠A ${o.attackSpadeA}장 · 흑백 조커 ${o.attackBlackJoker}장 · 컬러 조커 ${o.attackColorJoker}장 · 원카드 벌칙 ${v.penalty}장 · ${v.bankruptLimit ? `파산 ${v.bankruptLimit}장` : '파산 없음'}`; } const w4 = o.unoWild4Rule === 'strict' ? '+4는 지금 색이 없을 때만' : o.unoWild4Rule === 'challenge' ? '+4 의심하기 가능' : '+4 제한 없음'; return `${w4} · ${o.unoStacking ? '+2·+4 받아치기 됨' : '받아치기 없음'} · 원카드 벌칙 ${v.penalty}장${v.bankruptLimit ? ` · 파산 ${v.bankruptLimit}장` : ''}${o.unoTargetScore ? ` · 목표 ${o.unoTargetScore}점` : ''}`; } function OneCardSide({ view: v, me, players, deadline }: BoardProps) { const scoreMode = v.mode === 'uno-style' && v.options.unoTargetScore > 0; const waitingId = v.current; // Seats, the 기록 and the final ranking show what happened only after it has played on the table. const lastSeq = v.log.length ? v.log[v.log.length - 1]!.seq : 0; const shownSeq = useAfterMotionValue(lastSeq); const seatKey = useAfterMotionValue(v.seats.map((s) => `${s.status}:${s.score}`).join(',')); const seatShown = seatKey.split(','); const showResult = useAfterMotionValue(!!v.result); return ( <>
    {MODE_KO[v.mode]} {scoreMode ? ` · ${v.round}판` : ''} {v.phase === 'finished' ? ' · 게임 끝' : ''} {waitingId && v.phase !== 'finished' && }
    {rulesLine(v)}
      {v.seats.map((s, i) => { const [status, score] = (seatShown[i] ?? `${s.status}:${s.score}`).split(':') as [SeatView['status'], string]; return (
    1. {s.isTurn ? '▶ ' : ''} {nick(players, s.id)} {s.id === me ? ' (나)' : ''} {status === 'out' ? ' · 다 냄' : status === 'bankrupt' ? ' · 파산' : status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''} {scoreMode && {score}점} {s.cards}
    2. ); })}
    {showResult && v.result && (
    최종 순위 {v.result.players.map((p) => ( {p.rank}등 {nick(players, p.player)} {' '} · {p.status === 'bankrupt' ? '파산' : p.status === 'left' ? '나감' : `남은 카드 ${p.cardsLeft}장`} {v.mode === 'uno-style' ? ` · ${p.points}점` : p.cardsLeft > 0 ? ` (${p.points}점)` : ''} ))} {v.result.summary}
    )} {v.log.length > 0 && (
    기록
      {v.log.filter((e) => e.seq <= shownSeq).reverse().map((e) => (
    1. {logText(e, players)}
    2. ))}
    )}
    특수 카드
    ); } // ---------------------------------------------------------------- status function isMyTurn(v: OneCardView, 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: OneCardView, 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}판이 끝났어요. 다른 사람을 기다리는 중이에요`; if (me && v.current === me) { if (v.phase === 'wild4Response') return '내 차례예요. 색 바꾸기+4를 의심할지 골라 주세요'; if (v.phase === 'afterDraw') return '내 차례예요. 먹은 카드를 낼지 골라 주세요'; if (v.pendingAttack > 0) return `내 차례예요 · 공격 ${v.pendingAttack}장! 막거나 먹어 주세요`; if (v.extraTurn) return '내 차례예요 · K로 한 번 더 해요'; return '내 차례예요'; } const w = v.oneCardWindow; if (w && !w.declared && w.player === me) return '카드가 1장 남았어요. 원카드를 외치세요!'; if (!v.current) return '잠시만 기다려 주세요'; if (v.phase === 'wild4Response') 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}}
    ); } function NumSelect({ value, min, max, onChange, label }: { value: number; min: number; max: number; onChange: (n: number) => void; label: string }) { return ( ); } const onOff: [boolean, string][] = [ [true, '켜기'], [false, '끄기'], ]; function Options({ value: o, onChange }: OptionsProps) { const [more, setMore] = useState(false); const set = (patch: Partial) => onChange({ ...o, ...patch }); const classic = o.mode === 'classic'; return (
    set({ mode })} /> set({ handSize })} /> set({ endCondition })} /> set({ turnSeconds: k === 'none' ? null : (Number(k) as 10 | 15 | 20 | 30 | 60) })} /> {!classic && ( set({ unoWild4Rule })} /> )} {more && classic && ( <>
    set({ threeDefense })} /> set({ kEffect })} /> set({ qInTwoPlayer })} /> set({ lastCardRule })} /> set({ afterJoker })} /> set({ multiPlay })} /> set({ deckCount })} /> )} {more && !classic && ( <> set({ unoStacking })} /> set({ unoTargetScore })} /> )} {more && ( <> set({ oneCardPenalty })} /> set({ oneCardGrace })} /> set({ oneCardBonus })} /> set({ autoDeclare })} /> set({ bankruptLimit })} /> set({ voluntaryDraw })} /> set({ playAfterDraw })} /> )}
    ); } function optionsSummary(o: OneCardOptions): string { const parts = [MODE_KO[o.mode], `${o.handSize}장`]; if (o.mode === 'classic') { parts.push(`2 공격 ${o.attack2}장`); if (o.multiPlay) parts.push('여러 장 내기'); } else { parts.push(o.unoWild4Rule === 'strict' ? '+4 제한' : o.unoWild4Rule === 'challenge' ? '+4 의심하기' : '+4 자유'); if (o.unoStacking) parts.push('받아치기'); if (o.unoTargetScore) parts.push(`${o.unoTargetScore}점까지`); } if (o.endCondition === 'last-standing') parts.push('꼴찌까지'); parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`); return parts.join(' · '); } // ---------------------------------------------------------------- rules function SpecialTable({ mode, o }: { mode: OneCardView['mode']; o: OneCardOptions }) { const C = (c: CardFace) => ; const rows: [ReactNode, string, string][] = mode === 'classic' ? [ [C({ kind: 'std', suit: 'H', rank: 2 }), '공격', `다음 사람이 ${o.attack2}장 먹어요. 2·같은 무늬 A·조커로 받아칠 수 있어요.`], [C({ kind: 'std', suit: 'D', rank: 1 }), '공격', `A는 ${o.attackA}장, ♠A는 ${o.attackSpadeA}장. A에는 A·조커로 받아쳐요.`], [C({ kind: 'joker', joker: 'black' }), '공격', `흑백 조커 ${o.attackBlackJoker}장, 컬러 조커 ${o.attackColorJoker}장. 언제든 낼 수 있어요.`], [C({ kind: 'std', suit: 'C', rank: 3 }), '방어', o.threeDefense === 'same-suit' ? '같은 무늬 2·A 공격을 막아요(조커는 못 막아요).' : '이 방에서는 일반 카드예요.'], [C({ kind: 'std', suit: 'S', rank: 7 }), '무늬 바꾸기', '낸 사람이 다음 무늬를 정해요.'], [C({ kind: 'std', suit: 'H', rank: 11 }), '점프', '다음 사람을 건너뛰어요.'], [C({ kind: 'std', suit: 'S', rank: 12 }), '방향 바꾸기', '진행 방향이 반대로 바뀌어요.'], [C({ kind: 'std', suit: 'D', rank: 13 }), 'K', o.kEffect === 'extra-turn' ? '한 번 더 해요.' : o.kEffect === 'skip-two' ? '두 사람을 건너뛰어요.' : '이 방에서는 일반 카드예요.'], ] : [ [C({ kind: 'skip', color: 'R' }), '건너뛰기', '다음 사람을 건너뛰어요.'], [C({ kind: 'reverse', color: 'Y' }), '방향 바꾸기', '방향이 바뀌어요. 2명이면 건너뛰기와 같아요.'], [C({ kind: 'draw2', color: 'G' }), '+2', '다음 사람이 2장 먹고 차례를 잃어요.'], [C({ kind: 'wild' }), '색 바꾸기', '언제든 내고 다음 색을 정해요.'], [C({ kind: 'wild4' }), '색 바꾸기+4', '색을 정하고 다음 사람이 4장 먹고 차례를 잃어요.'], ]; return ( {rows.map(([pic, name, desc]) => ( ))}
    {pic} {name} {desc}
    ); } function Rules({ options }: { options?: OneCardOptions }) { const o: Partial = options ?? {}; const full: OneCardOptions = { handSize: 7, deckCount: 'auto', attack2: 2, attackA: 3, attackSpadeA: 5, attackBlackJoker: 5, attackColorJoker: 7, threeDefense: 'same-suit', kEffect: 'extra-turn', qInTwoPlayer: 'no-effect', lastCardRule: 'joker', afterJoker: 'previous', multiPlay: false, oneCardPenalty: 'auto', autoDeclare: false, oneCardGrace: 2, oneCardBonus: false, bankruptLimit: 'auto', voluntaryDraw: true, playAfterDraw: 'auto', endCondition: 'first-out', turnSeconds: 20, unoStacking: false, unoWild4Rule: 'strict', unoTargetScore: 0, mode: 'classic', ...o, }; const classic = full.mode === 'classic'; return (

    손에 든 카드를 가장 먼저 모두 내면 이겨요. 바닥 카드와 {classic ? '무늬나 숫자' : '색이나 숫자·기호'}가 같은 카드를 한 장 내요. 낼 카드가 없거나 내기 싫으면 더미에서 1장을 먹고 차례를 넘겨요.

    {classic ? (

    공격: 2·A·조커를 내면 다음 사람이 그만큼 먹어요. 받은 사람은 받아칠 카드를 내서 장수를 더해 넘기거나, 모인 장수만큼 먹어요. 7을 내면 다음 무늬를 정하고, 그다음 사람은 그 무늬나 7만 낼 수 있어요.

    ) : (

    색 바꾸기+4:{' '} {full.unoWild4Rule === 'strict' ? '지금 색 카드가 손에 없을 때만 낼 수 있어요.' : full.unoWild4Rule === 'challenge' ? '아무 때나 낼 수 있지만, 다음 사람이 의심하기를 할 수 있어요. 지금 색 카드가 있었는데 냈다면 낸 사람이 4장, 아니면 의심한 사람이 6장을 먹어요.' : '아무 때나 낼 수 있어요.'}

    )}

    원카드:{' '} {full.autoDeclare ? '카드를 내서 1장이 남으면 저절로 원카드를 외쳐요.' : `카드를 내서 1장이 남으면, 낸 다음 동그란 [원카드!] 버튼을 따로 눌러 외쳐요(카드를 내면서 함께 외칠 수는 없어요). 처음 ${full.oneCardGrace}초는 나만 누를 수 있고, 그 뒤에는 다른 사람이 먼저 눌러 잡을 수 있어요. 잡히면 ${full.oneCardPenalty === 'auto' ? (classic ? 1 : 2) : full.oneCardPenalty}장을 먹어요.`} {full.oneCardBonus ? ' 먼저 외치면 다른 사람이 모두 1장씩 먹어요.' : ''}

    {classic && (

    마지막 카드:{' '} {full.lastCardRule === 'none' ? '어떤 카드로든 끝낼 수 있어요.' : full.lastCardRule === 'joker' ? '조커로는 끝낼 수 없어요.' : full.lastCardRule === 'attack' ? '공격 카드(2·A·조커)로는 끝낼 수 없어요.' : '특수 카드로는 끝낼 수 없어요.'}

    )}

    {full.turnSeconds === null ? '한 턴 시간 제한이 없어요(자리를 비운 사람만 잠깐 기다린 뒤 자동으로 먹어요). ' : `${full.turnSeconds}초 안에 고르지 않으면 카드를 내지 않고 자동으로 먹어요(공격받는 중이면 모인 장수만큼). `} {full.bankruptLimit === 'none' || (full.bankruptLimit === 'auto' && !classic) ? '' : `손에 ${full.bankruptLimit === 'auto' ? 20 : full.bankruptLimit}장 이상 쌓이면 파산해서 탈락해요.`}

    {!classic && full.unoTargetScore > 0 &&

    여러 판을 해요. 이긴 사람은 다른 사람 손에 남은 카드 점수(숫자 그대로, 기능 카드 20점, 색 바꾸기 50점)를 얻고, {full.unoTargetScore}점에 먼저 닿으면 이겨요.

    } {classic &&

    {PLAYING_CARD_CREDIT}

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