Files
joke-app/apps/web/src/games/one-card/index.tsx
EJClaw 4e0eb4d52c 모든 게임: 결과·팝업은 애니메이션이 끝난 뒤에, 증강 윷놀이: 이의있음!이 다음 판에도 뜨게, 증강 고르는 목록·나오게 할 증강을 팝업 목록으로
- lib/motion: motionBusy / useMotionHold / useMotionSettled / useAfterMotionValue / AfterMotion
- 방 화면: 결과 창과 상태 줄은 판이 멈춘 뒤에(실시간 게임은 상태 줄 그대로), 새 판마다 판 화면을 새로 그림
  (결과 창에 둔 채 다음 판이 시작되면 이전 판의 효과 번호가 남아 이의있음!·알림이 안 뜨던 문제)
- 41개 게임: 결과 패널·배너·점수·팝업이 마지막 움직임 뒤에 나오도록 게임별로 정리
- 증강 윷놀이: 명탐정·배달·손버릇·따라쟁이·착각 대상은 아이콘과 설명이 다 보이는 목록에서,
  방 설정의 나오게 할 증강은 팝업 목록에서 스위치로 켜고 끔
- e2e: 늦게 바뀌는 상태 줄·결과 창과 새 증강 화면에 맞춤

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:22 +09:00

1270 lines
64 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/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<Suit, string> = { S: '♠', H: '♥', D: '◆', C: '♣' };
const SUIT_KO: Record<Suit, string> = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' };
const SUIT_INK: Record<Suit, string> = { S: '#111827', H: '#dc2626', D: '#dc2626', C: '#111827' };
const RANK_LABEL: Record<number, string> = { 1: 'A', 11: 'J', 12: 'Q', 13: 'K' };
const RANK_KO: Record<number, string> = { 1: '에이스', 11: '잭', 12: '퀸', 13: '킹' };
const TRUMP_RANK: Record<number, string> = { 1: 'A', 10: 'T', 11: 'J', 12: 'Q', 13: 'K' };
const MODE_KO: Record<OneCardOptions['mode'], string> = { classic: '원카드', 'uno-style': '색깔 카드' };
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' };
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 (
<span className="oc-face" aria-hidden>
{mode === 'classic' ? <PlayingCard card={card ? trumpId(card) : null} size="md" style={{ width: '100%', height: '100%', filter: 'none' }} /> : <ColorCardArt card={card} />}
</span>
);
}
// ---------------------------------------------------------------- seats
function seatLabel(s: SeatView, players: Record<string, PublicUser>, 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<string, PublicUser>; 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 (
<li className={`oc-seat${s.isTurn ? ' turn' : ''}${status === 'bankrupt' || status === 'left' ? ' gone' : ''}`} data-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="oc-count" aria-hidden>
<i />
{s.cards}
</span>
{s.oneCard && (
<span className="oc-badge oc-one" aria-hidden>
{s.oneCard === 'declared' ? '원카드!' : '1장!'}
</span>
)}
{status === 'out' && <span className="oc-badge" style={{ background: 'var(--success)', color: '#fff' }}>{place ? `${place}등` : '다 냄'}</span>}
{status === 'bankrupt' && <span className="oc-badge" style={{ background: 'var(--danger)', color: '#fff' }}>파산</span>}
{s.status === 'left' && <span className="oc-badge" style={{ background: 'var(--text-sub)', color: '#fff' }}>나감</span>}
{s.away && <span className="oc-badge" style={{ background: 'var(--warning)', color: '#fff' }}>자리 비움</span>}
{v.mode === 'uno-style' && v.options.unoTargetScore > 0 && <span className="small muted">{score}점</span>}
</div>
</li>
);
}
// ---------------------------------------------------------------- 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 (
<span key={shown} className="oc-attack grow" aria-live="polite" aria-label={`${uno ? '먹을 카드' : '공격'} ${n}장`} style={{ fontSize: `${1.4 + Math.min(shown, 15) * 0.07}rem` }}>
+{shown}장!
<small aria-hidden>{uno ? '먹을 카드' : '공격 누적'}</small>
</span>
);
}
function TableArea({ v, players, canDraw, onDraw, onDropCard, fx }: { v: OneCardView; players: Record<string, PublicUser>; 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 (
<div className="oc-table" role="region" aria-label="카드 판" style={{ '--pw': pw } as CSSProperties}>
<button
type="button"
className="oc-pile"
data-can={canDraw}
disabled={!canDraw}
onClick={onDraw}
aria-label={`카드 더미 ${v.drawPileCount}장${canDraw ? `. 눌러서 ${drawText}` : ''}`}
>
<span key={fx.shuffle} className={fx.shuffle ? 'oc-shuf' : undefined} style={{ display: 'block', width: '100%', height: '100%' }}>
<Face card={null} mode={v.mode} />
</span>
<span className="cnt" aria-hidden>
{v.drawPileCount}
</span>
</button>
<div
className="oc-discard"
data-drop={over}
aria-label={top ? `바닥 카드 ${ariaName(top)}` : '바닥 카드 없음'}
role="img"
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={`oc-face${last ? ' top' : ''}`}
style={{ transform: `rotate(${rot}deg) translate(${rot * 0.6}px, 0)`, ...(last && from ? { '--fx': `${Math.round(from.x)}px`, '--fy': `${Math.round(from.y)}px` } : {}) } as CSSProperties}
>
<Face card={c} mode={v.mode} />
</span>
);
})}
</div>
<div className="oc-info">
<AttackCount n={v.pendingAttack} uno={v.mode === 'uno-style'} />
<div className="row">
<span className="oc-dir" data-dir={v.direction} aria-label={v.direction === 1 ? '진행 방향: 시계 방향' : '진행 방향: 반대 방향'}>
<b key={fx.spin} className={fx.spin ? 'oc-spin' : undefined} aria-hidden>
↻
</b>
{v.direction === 1 ? '시계 방향' : '반대 방향'}
</span>
{v.extraTurn && <span className="oc-chip">K: 한 번 더</span>}
</div>
{v.declaredSuit && (
<span className="oc-chip" style={{ background: '#fffef9', color: SUIT_INK[v.declaredSuit] }}>
지정 무늬 {SUIT_SYMBOL[v.declaredSuit]} {SUIT_KO[v.declaredSuit]}
</span>
)}
{v.mode === 'uno-style' && (
<span className="oc-chip">
{v.currentColor ? (
<>
<span className="oc-swatch" style={{ background: COLOR_HEX[v.currentColor] }} aria-hidden />
지금 색: {COLOR_KO[v.currentColor]}
{v.declaredColor ? ' (지정)' : ''}
</>
) : (
'아무 색이나 낼 수 있어요'
)}
</span>
)}
{v.reference && <span className="oc-chip">조커 밑 기준: {faceName(v.reference)}</span>}
{v.wild4 && (
<span className="oc-chip">
{nick(players, v.wild4.target)}님이 의심할지 고르는 중
</span>
)}
</div>
{fx.flash && <div key={fx.flash.key} className="oc-flash" style={{ '--c': fx.flash.color } as CSSProperties} aria-hidden />}
<div className="oc-banners" aria-hidden>
{fx.banners.map((b) => (
<div key={b.key} className={`oc-banner anim-banner ${b.kind}`} style={b.color ? ({ '--suit': b.color } as CSSProperties) : undefined}>
<b>{b.text}</b>
{b.sub && <span>{b.sub}</span>}
</div>
))}
</div>
</div>
);
}
// ---------------------------------------------------------------- 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<T extends HTMLElement>(): [React.RefObject<T | null>, number, number] {
const ref = useRef<T>(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<string, PublicUser>; arrived: Record<string, number> }) {
const my = v.my!;
const [sortBy, setSortBy] = useState<'suit' | 'rank'>('suit');
const [sel, setSel] = useState<string[]>([]);
const [hints, setHints] = useState(true);
const [pick, setPick] = useState<PickState | null>(null);
const [note, setNote] = useState('');
const [ref, width, playH] = useWidth<HTMLDivElement>();
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<string, unknown> = {}) => {
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<HTMLDivElement>) => {
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
const btns = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>('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 (
<div className="oc-hand-wrap">
<div className="oc-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 === 'suit'} onClick={() => setSortBy('suit')}>
{v.mode === 'classic' ? '무늬별' : '색깔별'}
</button>
<button type="button" aria-pressed={sortBy === 'rank'} onClick={() => setSortBy('rank')}>
숫자별
</button>
</div>
<label className="row small" style={{ gap: 4, cursor: 'pointer' }}>
<input type="checkbox" checked={hints} onChange={(e) => setHints(e.target.checked)} style={{ width: 20, height: 20 }} />
힌트
</label>
</div>
</div>
<div
ref={ref}
className={`oc-hand${phone ? ' wrap' : ''}`}
role="group"
aria-label="내 카드. 좌우 방향키로 고르고 Enter로 들어 올리거나 내요"
onKeyDown={onKey}
style={{ '--cw': `${cw}px`, '--ov': `${ov}px` } as CSSProperties}
>
{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 (
<button
key={c.id}
type="button"
className={`oc-card${arrived[c.id] !== undefined ? ' oc-in' : ''}`}
style={arrived[c.id] !== undefined ? ({ '--anim-delay': `${arrived[c.id]}ms` } as CSSProperties) : undefined}
data-legal={myTurn ? isLegal : undefined}
data-id={c.id}
aria-pressed={picked}
draggable={legal.has(c.id) && !pending}
onDragStart={(e) => e.dataTransfer.setData('text/plain', c.id)}
onClick={() => tap(c)}
aria-label={`${ariaName(c)}${my.drawnCardId === c.id ? ', 방금 먹은 카드' : ''}${myTurn ? (legal.has(c.id) ? ', 낼 수 있음' : ', 낼 수 없음') : ''}${picked ? ', 골랐음. 한 번 더 누르면 내요' : ''}`}
title={reason || undefined}
>
<Face card={c} mode={v.mode} />
</button>
);
})}
{n === 0 && <span className="muted">손에 카드가 없어요.</span>}
</div>
{(note || hintText || counters.length > 0) && (
<p className="small" style={{ margin: 0 }} aria-live="polite">
{note || hintText}
{!note && counters.length > 0 && ` 막을 수 있는 카드: ${counters.map(faceName).join(', ')}`}
{!note && v.pendingAttack > 0 && myTurn && counters.length === 0 && ' 막을 카드가 없어요. 카드를 먹어 주세요.'}
</p>
)}
<ActionBar
v={v}
act={act}
pending={pending}
players={players}
canPlay={sel.length > 0 && legal.has(sel[0]!)}
playLabel={sel.length > 1 ? `${sel.length}장 내기` : '내기'}
onPlay={() => playIds(sel)}
leavesOne={leavesOne}
/>
{pick && (
<Sheet onClose={() => setPick(null)} label={pick.kind === 'suit' ? '무늬 고르기' : '색 고르기'}>
<h2>{pick.kind === 'suit' ? '다음 무늬를 골라 주세요' : '다음 색을 골라 주세요'}</h2>
<div className="oc-pick">
{pick.kind === 'suit'
? SUITS.map((s) => (
<button key={s} type="button" style={{ color: SUIT_INK[s], background: '#fffef9' }} onClick={() => send(pick.ids, { chooseSuit: s })}>
{SUIT_SYMBOL[s]} {SUIT_KO[s]}
</button>
))
: COLORS.map((c) => (
<button key={c} type="button" style={{ background: COLOR_HEX[c], color: COLOR_INK[c], borderColor: COLOR_HEX[c] }} onClick={() => send(pick.ids, { chooseColor: c })}>
{COLOR_KO[c]} <span className="small">({patternName(c)})</span>
</button>
))}
</div>
<button type="button" className="btn btn-secondary btn-block" onClick={() => setPick(null)}>
취소
</button>
</Sheet>
)}
</div>
);
}
function ActionBar(props: {
v: OneCardView;
act: (a: unknown) => void;
pending: boolean;
players: Record<string, PublicUser>;
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 (
<div className="oc-actions">
{myTurn && (
<button type="button" className="btn btn-primary" disabled={!canPlay || pending} onClick={onPlay}>
{playLabel}
</button>
)}
{my.canDraw && (
<button type="button" className={`btn ${v.pendingAttack > 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>
)}
{myTurn && leavesOne && (
<span className="small" style={{ flex: '1 1 100%' }}>
내고 나면 1장이 남아요. 낸 다음 [원카드!]를 따로 눌러요.
</span>
)}
<OneCardButton v={v} act={act} pending={pending} players={players} />
</div>
);
}
/**
* 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<string, PublicUser> }) {
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 (
<button
type="button"
className={`oc-onebtn${can && mine ? ' urgent' : ''}${my.canDeclare && wait > 0 ? ' wait' : ''}`}
disabled={!can}
onClick={() => {
haptic(40);
act({ type: 'declareOneCard' });
}}
aria-label={label}
>
{my.canDeclare && wait > 0 ? (
<>
잡기
<br />
{secs}초
</>
) : (
'원카드!'
)}
</button>
);
}
/** 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<string, PublicUser> }) {
const wait = useCatchWait(v);
const who = v.oneCardWindow ? nick(players, v.oneCardWindow.player) : '';
return (
<button type="button" className="btn btn-secondary" disabled={pending || wait > 0} onClick={() => act({ type: 'declareOneCard' })}>
{wait > 0 ? `${Math.ceil(wait / 1000)}초 뒤에 ${who}님 잡기` : `원카드! (${who}님 잡기)`}
</button>
);
}
// ---------------------------------------------------------------- prompts
function Wild4Panel({ v, players, act, pending }: { v: OneCardView; 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="oc-panel warn" role="group" aria-label="색 바꾸기+4 의심하기">
<strong>{by}님이 색 바꾸기+4를 냈어요.</strong>
<span className="small">
의심하면 {by}님 카드를 나만 볼 수 있어요. 낼 수 없었는데 냈다면 {by}님이 {v.pendingAttack}장을 먹고, 아니면 내가 {v.pendingAttack + 2}장을 먹어요.
{v.options.unoStacking ? ' 색 바꾸기+4가 있으면 받아칠 수도 있어요.' : ''}
</span>
<div className="row">
<button type="button" className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'challengeWild4' })}>
의심하기
</button>
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'acceptWild4' })}>
받아들이기({v.pendingAttack}장 먹기)
</button>
</div>
</div>
);
}
function RevealPanel({ v, players }: { v: OneCardView; players: Record<string, PublicUser> }) {
if (!v.reveal) return null;
const by = nick(players, v.reveal.by);
return (
<div className="oc-panel" aria-live="polite">
<strong>{v.reveal.illegal ? `의심 성공! ${by}님은 지금 색 카드가 있었어요.` : `${by}님은 규칙대로 냈어요. 의심이 틀렸어요.`}</strong>
<span className="small muted">{by}님의 카드(나만 볼 수 있어요)</span>
<div className="oc-mini">
{v.reveal.cards.map((c, i) => (
<span key={i} title={faceName(c)}>
<Face card={c} mode={v.mode} />
</span>
))}
</div>
</div>
);
}
function RoundPanel({ v, players, act, pending }: { v: OneCardView; 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="oc-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(' · ')}{' '}
(목표 {v.options.unoTargetScore}점)
</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': {
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<OneCardView>) {
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<HTMLUListElement>(others.length);
const canDraw = !!v.my?.canDraw && !pending;
const meSeat = v.seats.find((s) => s.id === me);
const rootRef = useRef<HTMLDivElement>(null);
const layerRef = useRef<HTMLDivElement>(null);
const fx = useOneCardFx({ view: v, me, nick: (id) => nick(players, id) }, rootRef, layerRef);
return (
<div className="oc" ref={rootRef}>
<style>{CSS + FX_CSS}</style>
<ul className="oc-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} />
))}
</ul>
<TableArea
v={v}
players={players}
canDraw={canDraw}
fx={fx}
onDraw={() => 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] });
}
}}
/>
<Wild4Panel v={v} players={players} act={act} pending={pending} />
<AfterMotion when={!!v.reveal}>
<RevealPanel v={v} players={players} />
</AfterMotion>
<AfterMotion when={v.phase === 'roundEnd'}>
<RoundPanel v={v} players={players} act={act} pending={pending} />
</AfterMotion>
{v.my && meSeat && meSeat.status === 'playing' && v.phase !== 'roundEnd' && v.phase !== 'finished' && <MyHand v={v} act={act} pending={pending} players={players} arrived={fx.arrived} />}
{meSeat && meSeat.status !== 'playing' && v.phase !== 'finished' && v.phase !== 'roundEnd' && (
<div className="oc-panel">
<strong>
{meSeat.status === 'out' ? '카드를 모두 냈어요! 다른 사람의 게임을 지켜봐요.' : meSeat.status === 'bankrupt' ? '파산했어요. 남은 게임을 지켜봐요.' : '게임에서 나갔어요.'}
</strong>
{meSeat.status === 'out' && v.my?.canDeclare && <CatchButton v={v} act={act} pending={pending} players={players} />}
</div>
)}
<p className="sr-only" aria-live="polite">
{announce}
</p>
<div className="oc-fxlayer" ref={layerRef} aria-hidden />
</div>
);
}
// ---------------------------------------------------------------- side
function rulesLine(v: Pick<OneCardView, 'mode' | 'options' | 'penalty' | 'bankruptLimit'>): 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<OneCardView>) {
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 (
<>
<style>{CSS}</style>
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<strong>
{MODE_KO[v.mode]}
{scoreMode ? ` · ${v.round}판` : ''}
{v.phase === 'finished' ? ' · 게임 끝' : ''}
</strong>
{waitingId && v.phase !== 'finished' && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={isMyTurn(v, me)} size={36} />}
</div>
<span className="small muted">{rulesLine(v)}</span>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
{v.seats.map((s, i) => {
const [status, score] = (seatShown[i] ?? `${s.status}:${s.score}`).split(':') as [SeatView['status'], string];
return (
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: status === 'bankrupt' || status === '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 ? ' (나)' : ''}
{status === 'out' ? ' · 다 냄' : status === 'bankrupt' ? ' · 파산' : status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
</span>
{scoreMode && <span className="small">{score}점</span>}
<span className="oc-count" aria-hidden>
<i />
{s.cards}
</span>
</li>
);
})}
</ol>
</div>
{showResult && 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.status === 'bankrupt' ? '파산' : p.status === 'left' ? '나감' : `남은 카드 ${p.cardsLeft}장`}
{v.mode === 'uno-style' ? ` · ${p.points}점` : p.cardsLeft > 0 ? ` (${p.points}점)` : ''}
</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="oc-log">
{v.log.filter((e) => e.seq <= shownSeq).reverse().map((e) => (
<li key={`${e.seq}-${e.t}-${'p' in e ? e.p : ''}`} className="small">
{logText(e, players)}
</li>
))}
</ol>
</details>
)}
<details className="card" style={{ padding: 12 }}>
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>특수 카드</summary>
<SpecialTable mode={v.mode} o={v.options} />
</details>
</>
);
}
// ---------------------------------------------------------------- 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, PublicUser>): 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<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) {
return (
<div className="stack" style={{ gap: 6 }}>
<strong>{label}</strong>
{children}
{help && <span className="small muted">{help}</span>}
</div>
);
}
function NumSelect({ value, min, max, onChange, label }: { value: number; min: number; max: number; onChange: (n: number) => void; label: string }) {
return (
<select className="input" aria-label={label} value={value} onChange={(e) => onChange(Number(e.target.value))} style={{ maxWidth: 160 }}>
{Array.from({ length: max - min + 1 }, (_, i) => min + i).map((n) => (
<option key={n} value={n}>
{n}장
</option>
))}
</select>
);
}
const onOff: [boolean, string][] = [
[true, '켜기'],
[false, '끄기'],
];
function Options({ value: o, onChange }: OptionsProps<OneCardOptions>) {
const [more, setMore] = useState(false);
const set = (patch: Partial<OneCardOptions>) => onChange({ ...o, ...patch });
const classic = o.mode === 'classic';
return (
<div className="stack" style={{ gap: 16 }}>
<Field label="게임 모드" help={classic ? '트럼프 카드 54장으로 해요. 2~9명.' : '4가지 색 숫자·기능 카드 108장으로 해요. 2~10명.'}>
<Seg label="게임 모드" value={o.mode} options={[['classic', '원카드(트럼프)'], ['uno-style', '색깔 카드']]} onChange={(mode) => set({ mode })} />
</Field>
<Field label="처음 받는 카드">
<Seg label="처음 받는 카드" value={o.handSize} options={[[5, '5장'], [6, '6장'], [7, '7장']]} onChange={(handSize) => set({ handSize })} />
</Field>
<Field label="끝나는 때">
<Seg label="끝나는 때" value={o.endCondition} options={[['first-out', '1등이 나오면'], ['last-standing', '꼴찌가 정해질 때까지']]} onChange={(endCondition) => set({ endCondition })} />
</Field>
<Field label="한 턴 제한 시간">
<Seg
label="한 턴 제한 시간"
value={o.turnSeconds === null ? 'none' : String(o.turnSeconds)}
options={[['10', '10초'], ['15', '15초'], ['20', '20초'], ['30', '30초'], ['60', '60초'], ['none', '무제한']]}
onChange={(k) => set({ turnSeconds: k === 'none' ? null : (Number(k) as 10 | 15 | 20 | 30 | 60) })}
/>
</Field>
{!classic && (
<Field label="색 바꾸기+4 내는 조건">
<Seg
label="색 바꾸기+4 내는 조건"
value={o.unoWild4Rule}
options={[['strict', '지금 색이 없을 때만'], ['challenge', '아무 때나(의심하기)'], ['free', '제한 없음']]}
onChange={(unoWild4Rule) => set({ unoWild4Rule })}
/>
</Field>
)}
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
</button>
{more && classic && (
<>
<Field label="공격 카드 장수">
<div className="row">
<label className="row small">2 <NumSelect label="2 공격 장수" value={o.attack2} min={1} max={3} onChange={(n) => set({ attack2: n as 1 | 2 | 3 })} /></label>
<label className="row small">A <NumSelect label="A 공격 장수" value={o.attackA} min={2} max={5} onChange={(n) => set({ attackA: n as 2 | 3 | 4 | 5 })} /></label>
<label className="row small">♠A <NumSelect label="스페이드 A 공격 장수" value={o.attackSpadeA} min={3} max={10} onChange={(attackSpadeA) => set({ attackSpadeA })} /></label>
<label className="row small">흑백 조커 <NumSelect label="흑백 조커 공격 장수" value={o.attackBlackJoker} min={5} max={10} onChange={(attackBlackJoker) => set({ attackBlackJoker })} /></label>
<label className="row small">컬러 조커 <NumSelect label="컬러 조커 공격 장수" value={o.attackColorJoker} min={5} max={13} onChange={(attackColorJoker) => set({ attackColorJoker })} /></label>
</div>
</Field>
<Field label="3으로 막기">
<Seg label="3으로 막기" value={o.threeDefense} options={[['same-suit', '같은 무늬 3으로 2·A 막기'], ['off', '안 씀']]} onChange={(threeDefense) => set({ threeDefense })} />
</Field>
<Field label="K 효과">
<Seg label="K 효과" value={o.kEffect} options={[['extra-turn', '한 번 더'], ['skip-two', '두 명 건너뛰기'], ['none', '효과 없음']]} onChange={(kEffect) => set({ kEffect })} />
</Field>
<Field label="2명일 때 Q">
<Seg label="2명일 때 Q" value={o.qInTwoPlayer} options={[['no-effect', '효과 없음'], ['as-skip', 'J처럼 한 번 더']]} onChange={(qInTwoPlayer) => set({ qInTwoPlayer })} />
</Field>
<Field label="마지막 카드로 낼 수 없는 카드">
<Seg
label="마지막 카드로 낼 수 없는 카드"
value={o.lastCardRule}
options={[['none', '제한 없음'], ['joker', '조커'], ['attack', '공격 카드'], ['special', '특수 카드 모두']]}
onChange={(lastCardRule) => set({ lastCardRule })}
/>
</Field>
<Field label="조커 다음에 낼 카드">
<Seg label="조커 다음에 낼 카드" value={o.afterJoker} options={[['previous', '조커 밑 카드 기준'], ['any', '아무 카드']]} onChange={(afterJoker) => set({ afterJoker })} />
</Field>
<Field label="같은 숫자 여러 장 한꺼번에 내기">
<Seg label="같은 숫자 여러 장 한꺼번에 내기" value={o.multiPlay} options={onOff} onChange={(multiPlay) => set({ multiPlay })} />
</Field>
<Field label="덱 수">
<Seg label="덱 수" value={o.deckCount} options={[['auto', '자동(6명부터 2벌)'], [1, '1벌'], [2, '2벌']]} onChange={(deckCount) => set({ deckCount })} />
</Field>
</>
)}
{more && !classic && (
<>
<Field label="+2·+4 받아치기">
<Seg label="+2·+4 받아치기" value={o.unoStacking} options={onOff} onChange={(unoStacking) => set({ unoStacking })} />
</Field>
<Field label="목표 점수(여러 판)">
<Seg label="목표 점수" value={o.unoTargetScore} options={[[0, '없음(한 판)'], [200, '200점'], [500, '500점']]} onChange={(unoTargetScore) => set({ unoTargetScore })} />
</Field>
</>
)}
{more && (
<>
<Field label="원카드를 못 외치고 잡히면">
<Seg label="원카드 벌칙" value={o.oneCardPenalty} options={[['auto', classic ? '1장(기본)' : '2장(기본)'], [1, '1장'], [2, '2장'], [3, '3장']]} onChange={(oneCardPenalty) => set({ oneCardPenalty })} />
</Field>
<Field label="원카드 잡기 전 보호 시간" help="1장 남은 사람만 [원카드!]를 누를 수 있는 시간이에요. 지나면 다른 사람이 잡을 수 있어요.">
<Seg label="원카드 보호 시간" value={o.oneCardGrace} options={[[1, '1초'], [2, '2초(기본)'], [3, '3초']]} onChange={(oneCardGrace) => set({ oneCardGrace })} />
</Field>
<Field label="원카드를 외치면 다른 사람이 1장씩 먹기">
<Seg label="원카드 보너스" value={o.oneCardBonus} options={onOff} onChange={(oneCardBonus) => set({ oneCardBonus })} />
</Field>
<Field label="1장 남으면 자동으로 원카드 외치기" help="초보·어린이용이에요. 켜면 아무도 잡을 수 없어요.">
<Seg label="자동 원카드" value={o.autoDeclare} options={onOff} onChange={(autoDeclare) => set({ autoDeclare })} />
</Field>
<Field label="파산 장수">
<Seg
label="파산 장수"
value={o.bankruptLimit}
options={[['auto', classic ? '20장(기본)' : '없음(기본)'], [15, '15장'], [18, '18장'], [20, '20장'], [25, '25장'], ['none', '파산 없음']]}
onChange={(bankruptLimit) => set({ bankruptLimit })}
/>
</Field>
<Field label="낼 카드가 있어도 1장 먹고 넘기기">
<Seg label="일부러 먹기" value={o.voluntaryDraw} options={[[true, '돼요'], [false, '안 돼요']]} onChange={(voluntaryDraw) => set({ voluntaryDraw })} />
</Field>
<Field label="먹은 카드를 바로 내기">
<Seg label="먹은 카드 바로 내기" value={o.playAfterDraw} options={[['auto', classic ? '안 됨(기본)' : '됨(기본)'], ['on', '돼요'], ['off', '안 돼요']]} onChange={(playAfterDraw) => set({ playAfterDraw })} />
</Field>
</>
)}
</div>
);
}
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) => <Face card={c} mode={mode} />;
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 (
<table className="oc-rules small" style={{ borderCollapse: 'collapse', width: '100%', marginTop: 8 }}>
<tbody>
{rows.map(([pic, name, desc]) => (
<tr key={name + desc}>
<td style={{ width: 44 }}>{pic}</td>
<th scope="row" style={{ whiteSpace: 'nowrap' }}>
{name}
</th>
<td>{desc}</td>
</tr>
))}
</tbody>
</table>
);
}
function Rules({ options }: { options?: OneCardOptions }) {
const o: Partial<OneCardOptions> = 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 (
<div className="stack">
<p>
손에 든 카드를 가장 먼저 모두 내면 이겨요. 바닥 카드와 {classic ? '무늬나 숫자' : '색이나 숫자·기호'}가 같은 카드를 한 장 내요. 낼 카드가 없거나 내기 싫으면 더미에서 1장을 먹고 차례를
넘겨요.
</p>
{classic ? (
<p>
<strong>공격</strong>: 2·A·조커를 내면 다음 사람이 그만큼 먹어요. 받은 사람은 받아칠 카드를 내서 장수를 더해 넘기거나, 모인 장수만큼 먹어요. 7을 내면 다음 무늬를 정하고, 그다음 사람은 그
무늬나 7만 낼 수 있어요.
</p>
) : (
<p>
<strong>색 바꾸기+4</strong>:{' '}
{full.unoWild4Rule === 'strict'
? '지금 색 카드가 손에 없을 때만 낼 수 있어요.'
: full.unoWild4Rule === 'challenge'
? '아무 때나 낼 수 있지만, 다음 사람이 의심하기를 할 수 있어요. 지금 색 카드가 있었는데 냈다면 낸 사람이 4장, 아니면 의심한 사람이 6장을 먹어요.'
: '아무 때나 낼 수 있어요.'}
</p>
)}
<SpecialTable mode={full.mode} o={full} />
<p>
<strong>원카드</strong>:{' '}
{full.autoDeclare
? '카드를 내서 1장이 남으면 저절로 원카드를 외쳐요.'
: `카드를 내서 1장이 남으면, 낸 다음 동그란 [원카드!] 버튼을 따로 눌러 외쳐요(카드를 내면서 함께 외칠 수는 없어요). 처음 ${full.oneCardGrace}초는 나만 누를 수 있고, 그 뒤에는 다른 사람이 먼저 눌러 잡을 수 있어요. 잡히면 ${full.oneCardPenalty === 'auto' ? (classic ? 1 : 2) : full.oneCardPenalty}장을 먹어요.`}
{full.oneCardBonus ? ' 먼저 외치면 다른 사람이 모두 1장씩 먹어요.' : ''}
</p>
{classic && (
<p>
<strong>마지막 카드</strong>:{' '}
{full.lastCardRule === 'none'
? '어떤 카드로든 끝낼 수 있어요.'
: full.lastCardRule === 'joker'
? '조커로는 끝낼 수 없어요.'
: full.lastCardRule === 'attack'
? '공격 카드(2·A·조커)로는 끝낼 수 없어요.'
: '특수 카드로는 끝낼 수 없어요.'}
</p>
)}
<p>
{full.turnSeconds === null
? '한 턴 시간 제한이 없어요(자리를 비운 사람만 잠깐 기다린 뒤 자동으로 먹어요). '
: `${full.turnSeconds}초 안에 고르지 않으면 카드를 내지 않고 자동으로 먹어요(공격받는 중이면 모인 장수만큼). `}
{full.bankruptLimit === 'none' || (full.bankruptLimit === 'auto' && !classic)
? ''
: `손에 ${full.bankruptLimit === 'auto' ? 20 : full.bankruptLimit}장 이상 쌓이면 파산해서 탈락해요.`}
</p>
{!classic && full.unoTargetScore > 0 && <p>여러 판을 해요. 이긴 사람은 다른 사람 손에 남은 카드 점수(숫자 그대로, 기능 카드 20점, 색 바꾸기 50점)를 얻고, {full.unoTargetScore}점에 먼저 닿으면 이겨요.</p>}
{classic && <p className="small muted">{PLAYING_CARD_CREDIT}</p>}
</div>
);
}
const ui: GameUI<OneCardView, OneCardOptions> = {
Board: OneCardBoard,
Side: OneCardSide,
statusText,
isMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;