Files
joke-app/apps/web/src/games/old-maid/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

1145 lines
59 KiB
TypeScript

/** 도둑잡기 화면 (docs/games/old-maid.md §9). Cards are the shared trump card SVGs. */
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
import type { LogEntry, OldMaidOptions, OldMaidView } from '@bg/games/old-maid';
import type { PublicUser } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { TurnTimer } from '../../components/TurnTimer';
import { PLAYING_CARD_CREDIT, PlayingCard, cardAria } from '../../components/cards/PlayingCard';
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
import { toast } from '../../store/toast';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useChange, useNewEntries } from '../card-fx';
import { fanCard, fanLayout, type FanLayout } from './fan';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxAnim, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
// Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod.
const JOKER = 'X1';
const SHUFFLES_PER_TURN = 3;
/** 도둑잡기 sounds on top of the shared palette (synthesized, no files). */
const omSfx = {
/** Two cards snapped down together + a bright chime: a pair thrown away. */
pair: () => {
noise(60, 0.16, 0, 'bandpass', 1700, 0.9);
noise(60, 0.16, 90, 'bandpass', 1500, 0.9);
tone(988, 90, 'triangle', 0.1, 120);
tone(1319, 160, 'triangle', 0.09, 190);
},
/** Someone emptied their hand. */
out: () => [784, 988, 1175, 1568].forEach((f, i) => tone(f, 110, 'triangle', 0.08, i * 70)),
/** I just got the joker: a sly, sinking "uh-oh" (only on the screen of whoever got it). */
jokerGot: () => {
tone(466, 150, 'sawtooth', 0.04, 0, { slideTo: 415 });
tone(370, 260, 'sawtooth', 0.045, 150, { slideTo: 311 });
tone(185, 300, 'sine', 0.1, 150);
},
/** My joker was taken: a sneaky "hehe" (only on the screen of whoever gave it away). */
jokerGone: () => {
[1047, 1175, 1047, 1397].forEach((f, i) => tone(f, 70, 'square', 0.035, i * 85));
tone(1568, 200, 'triangle', 0.06, 340, { slideTo: 2093 });
},
};
/** Where I clicked the card I drew (its button is gone once the view arrives), so the new card flies in from there. */
let myDrawRect: DOMRect | null = null;
/** The fan as it was last painted ([x, y, w, h] of every card, relative to the table), so someone else's draw lifts that card. */
let fanSnap: { target: string; rects: (readonly [number, number, number, number])[] } | null = null;
const handCardEl = (c: string) => document.querySelector(`.om-hand [data-card="${cssEsc(c)}"]`);
const pairKey = (p: [string, string]) => `${p[0]}-${p[1]}`;
const LIFT_MS = 640;
/** Where card `index` of `from`'s fan was last painted (see `fanSnap`), in today's page coordinates. */
function fanCardRect(from: string, index: number): DOMRect | null {
const r = fanSnap?.target === from ? fanSnap.rects[index] : undefined;
const t = fxEl('om-table')?.getBoundingClientRect();
if (!r || !t || typeof DOMRect !== 'function') return null;
return new DOMRect(t.left + r[0], t.top + r[1], r[2], r[3]);
}
/** A face-down copy of the drawn card rises out of the fan, then flies to `to`. False when nothing was shown (reduced motion …). */
function liftFly(from: DOMRect, to: Element | null | undefined, delay: number): boolean {
const b = to?.getBoundingClientRect();
if (!b || (b.width === 0 && b.height === 0) || reducedMotion() || typeof document === 'undefined') return false;
const g = document.createElement('div');
if (typeof g.animate !== 'function') return false;
g.className = 'om-ghost';
g.setAttribute('aria-hidden', 'true');
Object.assign(g.style, { left: `${from.left}px`, top: `${from.top}px`, width: `${from.width}px`, height: `${from.height}px` });
document.body.appendChild(g);
const dx = b.left + b.width / 2 - (from.left + from.width / 2);
const dy = b.top + b.height / 2 - (from.top + from.height / 2);
// Onto a card in my hand: shrink to its size. Onto a seat: a small card.
const s = b.width <= 120 ? Math.max(0.4, Math.min(1.2, b.width / from.width)) : 0.6;
const anim = fxAnim(g.animate(
[
{ transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 },
{ transform: 'translate(0px, -28px) scale(1.08) rotate(-4deg)', opacity: 1, offset: 0.3 },
{ transform: `translate(${dx}px, ${dy}px) scale(${s}) rotate(6deg)`, opacity: 1, offset: 0.88 },
{ transform: `translate(${dx}px, ${dy}px) scale(${s}) rotate(0deg)`, opacity: 0 },
],
{ duration: LIFT_MS, delay, easing: 'cubic-bezier(.35,.6,.3,1)', fill: 'both' },
));
const done = () => g.remove();
anim.onfinish = done;
anim.oncancel = done;
setTimeout(done, fxMs(LIFT_MS + delay) + 1500);
return true;
}
/** My new card stays hidden while its face-down copy flies in, then pops up face-up. */
function reveal(el: Element, delay: number): void {
const h = el as HTMLElement;
if (typeof h.animate !== 'function') return;
fxAnim(h.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 120, delay, fill: 'backwards' }));
fxAnim(h.animate([{ transform: 'scale(.8)' }, { transform: 'scale(1.1)', offset: 0.6 }, { transform: 'scale(1)' }], { duration: 280, delay, easing: 'ease-out', composite: 'add' }));
}
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 who = (players: Record<string, PublicUser>, id: string, me: string | null) => (id === me ? '나' : `${nick(players, id)}님`);
/** "내가" / "친구님이": who drew. */
const drawerSubj = (players: Record<string, PublicUser>, id: string, me: string | null) => (id === me ? '내가' : `${nick(players, id)}님이`);
/** "내" / "친구님의": whose cards. */
const whose = (players: Record<string, PublicUser>, id: string, me: string | null) => (id === me ? '내' : `${nick(players, id)}님의`);
/** "♥7", "조커". */
function cardName(c: string): string {
if (c.startsWith('X')) return '조커';
const r = c[0]!;
return `${{ S: '♠', H: '♥', D: '◆', C: '♣' }[c[1]!] ?? ''}${r === 'T' ? '10' : r}`;
}
function logText(e: LogEntry, players: Record<string, PublicUser>, me: string | null): string {
switch (e.t) {
case 'draw': {
const base = `${drawerSubj(players, e.drawer, me)} ${whose(players, e.from, me)} ${e.index + 1}번째 카드를 뽑았어요`;
const pair = e.pair ? ` → ${cardName(e.pair[0])}·${cardName(e.pair[1])} 짝을 버렸어요` : '';
return `${base}${pair}${e.auto ? ' (시간 초과)' : ''}`;
}
case 'out':
return `${who(players, e.player, me)}${e.player === me ? '는' : '이'} 손패를 다 털었어요! ${e.place}등`;
case 'shuffle':
return `${who(players, e.player, me)}${e.player === me ? '는' : '이'} 손패를 섞었어요`;
case 'left':
return `${nick(players, e.player)}님이 나가서 카드를 ${e.gave.map((g) => `${who(players, g.to, me)}에게 ${g.count}장`).join(', ') || '아무에게도 안'} 나눠 줬어요${e.pairs.length ? ` (짝 ${e.pairs.length}쌍 버림)` : ''}`;
}
}
// ---------------------------------------------------------------- styles
const CSS = `
.om-board { width: 100%; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; flex: 1 1 auto; min-height: 0; }
.om-board > * { flex: none; }
.om-board > .om-table { flex: 1 0 auto; }
.om-seats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 260px)); justify-content: center; gap: 10px; padding-top: 6px; }
.om-seat { position: relative; background: var(--surface); border-radius: var(--radius-lg); padding: 8px 10px; box-shadow: var(--shadow); border: 3px solid transparent; display: flex; flex-direction: column; gap: 5px; min-width: 0; }
.om-seat.turn { border-color: var(--focus); }
.om-seat.target { border-color: var(--primary); border-style: dashed; }
.om-seat.done { opacity: .72; }
.om-seat.thief { border-color: var(--danger); opacity: 1; }
.om-head { display: flex; align-items: center; gap: 7px; min-height: 30px; min-width: 0; }
.om-name { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; }
.om-badges { display: flex; gap: 4px; flex-wrap: wrap; min-height: 22px; }
.om-badge { display: inline-block; border-radius: 999px; padding: 1px 8px; font-weight: 800; font-size: .78rem; background: var(--surface-2); color: var(--text); white-space: nowrap; }
.om-badge.turn { background: var(--focus); color: #1c1e21; animation: om-beat 1.6s ease-in-out infinite; }
.om-badge.target { background: var(--primary-soft); color: var(--text); }
.om-badge.win { background: var(--success-soft); color: var(--success); }
.om-badge.lose { background: var(--danger-soft); color: var(--danger); }
.om-meta { font-size: .85rem; color: var(--text-sub); display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.om-meta strong { color: var(--text); font-variant-numeric: tabular-nums; }
.om-mini { position: relative; display: inline-block; flex: none; height: 24px; }
.om-mini i { position: absolute; bottom: 1px; width: 13px; height: 19px; border-radius: 3px; background: #1e3a8a; border: 1.5px solid #fff;
box-shadow: 0 0 0 1px #1e3a8a, 0 1px 2px rgba(0,0,0,.35); transform: rotate(var(--r)); transform-origin: 50% 140%; }
.om-mini i::after { content: ''; position: absolute; inset: 3px 2px; border: 1px solid #93c5fd; border-radius: 1px; }
.om-mini.empty { width: 15px; }
.om-mini.empty i { background: none; border-style: dashed; border-color: var(--border); box-shadow: none; }
.om-mini.empty i::after { display: none; }
.om-bubble { position: absolute; right: 8px; top: -12px; background: var(--text); color: var(--surface); border-radius: 12px; padding: 2px 10px; font-weight: 800; font-size: .8rem; box-shadow: var(--shadow); animation: om-pop .25s ease-out; z-index: 2; }
.om-table { position: relative; color: #fff; border-radius: 22px; padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 10px; align-items: center; justify-content: center; min-height: 200px;
background: radial-gradient(ellipse 75% 60% at 50% 36%, rgba(255,255,255,.15), rgba(255,255,255,0) 70%), var(--felt);
border: 6px solid var(--wood); box-shadow: inset 0 0 0 2px rgba(255,255,255,.07), inset 0 0 48px rgba(0,0,0,.32), var(--shadow); }
.om-table .small { color: #fff; opacity: .92; text-shadow: 0 1px 2px rgba(0,0,0,.35); }
.om-title { font-weight: 900; font-size: 1.02rem; display: flex; align-items: center; gap: 6px 8px; flex-wrap: wrap; justify-content: center; text-shadow: 0 1px 2px rgba(0,0,0,.45); }
.om-who { display: inline-flex; align-items: center; gap: 6px; min-width: 0; max-width: 100%; background: rgba(0,0,0,.24); border-radius: 999px; padding: 3px 12px 3px 4px; }
.om-who.me { box-shadow: inset 0 0 0 2px rgba(253,224,71,.65); }
.om-who .lbl { display: inline-flex; min-width: 0; white-space: nowrap; }
.om-who .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; max-width: 12em; }
.om-who b { color: #fde047; white-space: nowrap; }
.om-arrow { display: inline-flex; color: #fde047; filter: drop-shadow(0 1px 1px rgba(0,0,0,.4)); animation: om-nudge 1.1s ease-in-out infinite; }
.om-fan { --cw: 70px; --sw: var(--cw); width: 100%; display: flex; justify-content: center; align-items: flex-start; padding: 26px 0 16px; }
.om-fan.wrap { flex-wrap: wrap; gap: 6px; padding-top: 18px; }
.om-card { position: relative; flex: none; width: var(--cw); height: calc(var(--cw) * 1.4); display: inline-block; }
.om-strip { position: relative; flex: none; width: var(--sw); height: calc(var(--cw) * 1.4); transform: translateY(calc(var(--y, 0px) + var(--lift, 0px))) rotate(var(--r, 0deg));
transform-origin: calc(var(--cw) / 2) 115%; transition: transform .16s ease; }
.om-strip.last, .wrap .om-strip { width: var(--cw); }
.om-strip > .om-face { position: absolute; left: 0; top: 0; width: var(--cw); height: 100%; border-radius: 9px; filter: drop-shadow(-2px 2px 3px rgba(0,0,0,.3)); }
.om-back { padding: 0; border: 0; background: none; border-radius: 9px; cursor: default; color: inherit; }
button.om-back { cursor: pointer; }
.om-back:disabled { cursor: default; }
button.om-back:focus-visible { outline: none; --lift: -10px; }
button.om-back:focus-visible > .om-face { outline: 3px solid var(--focus); outline-offset: 2px; }
@media (hover: hover) {
button.om-back:hover:not(:disabled) { --lift: -12px; }
button.om-back:hover:not(:disabled) > .om-face { filter: drop-shadow(0 0 7px rgba(253,224,71,.85)); }
.om-hand .om-card.om-strip:hover { --lift: -12px; }
}
button.om-back[aria-pressed='true'], button.om-back[aria-pressed='true']:hover:not(:disabled) { --lift: -22px; }
button.om-back[aria-pressed='true'] > .om-face { box-shadow: 0 0 0 3px #fde047, 0 0 18px 4px rgba(253,224,71,.75); }
.om-back .om-no { position: absolute; left: 50%; bottom: 5px; transform: translateX(-50%); background: rgba(0,0,0,.6); color: #fff; font-size: .72rem; font-weight: 800; border-radius: 6px; padding: 0 4px; pointer-events: none; z-index: 1; font-variant-numeric: tabular-nums; }
.om-fan.riffle .om-face { animation: om-riffle .62s cubic-bezier(.3,.7,.3,1) both; animation-delay: calc(var(--i, 0) * 14ms); }
.om-face { display: block; width: 100%; height: 100%; }
.om-face svg, .om-face > span { width: 100% !important; height: 100% !important; display: block; }
.om-ghost { position: fixed; z-index: 60; pointer-events: none; box-sizing: border-box; border-radius: 7px; background: #1e3a8a; border: 2px solid #fff;
box-shadow: 0 6px 16px rgba(0,0,0,.4), inset 0 0 0 4px #1e3a8a, inset 0 0 0 6px #93c5fd; will-change: transform, opacity; }
.om-ghost::after { content: ''; position: absolute; left: 50%; top: 50%; width: 34%; height: 24%; background: #3b82f6; transform: translate(-50%, -50%) rotate(45deg); border-radius: 2px; }
.om-last { display: flex; align-items: center; gap: 12px; background: rgba(0,0,0,.24); border: 1px solid rgba(255,255,255,.1); border-radius: 14px; padding: 8px 14px; width: 100%; max-width: 620px; justify-content: center; }
.om-thief-joker { animation: om-pop .45s ease-out; }
.om-last .cards { display: flex; flex: none; padding: 2px 4px; animation: om-pop .3s ease-out; }
.om-last .cards .om-card { --cw: 40px; transform-origin: 50% 100%; filter: drop-shadow(-1px 2px 2px rgba(0,0,0,.3)); }
.om-last .cards .om-card:first-child:not(:last-child) { transform: rotate(-7deg); }
.om-last .cards .om-card + .om-card { margin-left: -12px; transform: rotate(7deg); }
.om-last .txt { line-height: 1.45; min-width: 0; }
.om-pile { display: flex; flex-wrap: wrap; gap: 6px 14px; justify-content: center; align-items: center; font-size: .85rem; }
.om-pile .lbl { background: rgba(0,0,0,.26); border-radius: 999px; padding: 2px 12px; font-weight: 800; white-space: nowrap; }
.om-pile .pairs { display: flex; flex-wrap: wrap; gap: 4px 10px; justify-content: center; }
.om-pile .pair { display: inline-flex; padding: 2px 3px 0; }
.om-pile .om-card { --cw: 28px; transform-origin: 50% 100%; filter: drop-shadow(0 1px 1px rgba(0,0,0,.3)); }
.om-pile .pair .om-card:first-child { transform: rotate(-9deg); }
.om-pile .pair .om-card + .om-card { margin-left: -12px; transform: rotate(8deg); }
.om-me { position: relative; background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 10px 12px; border: 3px solid var(--primary); display: flex; flex-direction: column; gap: 8px; }
.om-me.turn { border-color: var(--focus); }
.om-me.target { border-style: dashed; }
.om-me .om-bubble { right: auto; left: 16px; top: -14px; }
.om-hand { --cw: 72px; --sw: var(--cw); width: 100%; display: flex; justify-content: center; align-items: flex-start; padding: 18px 0 12px; }
.om-hand.wrap { flex-wrap: wrap; gap: 6px; justify-content: flex-start; padding-top: 4px; }
.om-hand .om-card.joker > .om-face { box-shadow: 0 0 0 3px var(--danger); border-radius: 9px; }
.om-hand .om-card.fresh > .om-face { animation: om-pop .45s ease-out; box-shadow: 0 0 0 3px #f59e0b, 0 0 14px 2px rgba(245,158,11,.7); border-radius: 9px; }
.om-mine { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: space-between; }
.om-shuffle { min-height: 44px; }
.om-note { font-size: .85rem; color: var(--text-sub); }
.om-log { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; font-size: .88rem; }
@keyframes om-pop { 0% { transform: scale(.6); opacity: 0; } 100% { transform: none; opacity: 1; } }
@keyframes om-nudge { 0%, 100% { transform: translateX(-2px); } 50% { transform: translateX(4px); } }
@keyframes om-beat { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.07); } }
@keyframes om-riffle { 0%, 100% { transform: none; } 35% { transform: translate(var(--sx, 0px), -10px) rotate(calc(var(--r, 0deg) * -1)); } 68% { transform: translate(calc(var(--sx, 0px) * -.35), -3px); } }
@media (max-width: 719px) {
.om-board { max-height: none; overflow: visible; }
.om-seats { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
.om-seat { padding: 6px 8px; }
.om-table { min-height: 0; padding: 10px 8px 12px; border-width: 5px; border-radius: 18px; }
.om-title { font-size: .95rem; }
.om-who .nm { max-width: 7.5em; }
.om-last { padding: 8px 10px; gap: 10px; }
.om-last .cards .om-card { --cw: 36px; }
}
@media (prefers-reduced-motion: reduce) {
.om-fan.riffle .om-face, .om-bubble, .om-hand .om-card.fresh > .om-face, .om-arrow, .om-badge.turn, .om-last .cards, .om-thief-joker { animation: none; }
.om-strip { transition: none; }
}
`;
// ---------------------------------------------------------------- pieces
/** Width of an element, kept up to date (a callback ref, so it follows the element when it is re-created). */
/** Width of the node + the play area height on PC (`--play-h` of .game-main, 0 when the page scrolls instead). */
function useWidth<T extends HTMLElement>(): [(node: T | null) => void, number, { current: T | null }, number] {
const [w, setW] = useState(0);
const [h, setH] = useState(0);
const el = useRef<T | null>(null);
const ro = useRef<ResizeObserver | null>(null);
const ref = useCallback((node: T | null) => {
ro.current?.disconnect();
ro.current = null;
el.current = node;
if (!node) return;
const measure = () => {
setW(node.clientWidth);
setH(parseFloat(getComputedStyle(node).getPropertyValue('--play-h')) || 0);
};
measure();
if (typeof ResizeObserver === 'function') {
ro.current = new ResizeObserver(measure);
ro.current.observe(node);
const main = node.closest('.game-main');
if (main) ro.current.observe(main);
}
}, []);
return [ref, w, el, h];
}
/**
* How much bigger than the base size the two card rows (table fan + my hand) can be on a big PC play area: both rows
* share the height left after the seats, titles, notes and buttons (~520px + a row of seats per extra seat line).
*/
function cardGrow(v: OldMaidView, width: number, playH: number): number {
const seatRows = Math.ceil(Math.max(1, v.order.length - 1) / Math.max(1, Math.floor((width + 50) / 270)));
return Math.min(2, Math.max(1, Math.min(width / 900, (playH - 520 - (seatRows - 1) * 110) / 200)));
}
const rowStyle = (l: FanLayout): CSSProperties => ({ '--cw': `${l.cw}px`, '--sw': `${l.step}px` }) as CSSProperties;
/** Tilt / drop of card `i` of `n` in a fan row (+ extra CSS variables). */
function stripStyle(i: number, n: number, l: FanLayout, extra: Record<string, string | number> = {}): CSSProperties {
const { r, y } = fanCard(i, n, l);
return { '--r': `${r}deg`, '--y': `${y}px`, ...extra } as CSSProperties;
}
function Card({ card, className, style }: { card: string | null; className?: string; style?: CSSProperties }) {
return (
<span className={`om-card${className ? ` ${className}` : ''}`} data-card={card ?? undefined} style={style} aria-hidden>
<span className="om-face">
<PlayingCard card={card} size="lg" style={{ width: '100%', height: '100%', filter: 'none' }} />
</span>
</span>
);
}
/** A seat's hand: a small fanned stack of card backs, wider and more spread with more cards. */
function MiniFan({ n }: { n: number }) {
if (n <= 0) {
return (
<span className="om-mini empty" aria-hidden>
<i style={{ left: 0, '--r': '0deg' } as CSSProperties} />
</span>
);
}
const k = Math.min(n, 10);
const half = Math.min(12, (k - 1) * 1.6);
return (
<span className="om-mini" style={{ width: 13 + (k - 1) * 4 + 8 }} aria-hidden>
{Array.from({ length: k }, (_, i) => (
<i key={i} style={{ left: 4 + i * 4, '--r': `${k > 1 ? Math.round(((2 * i) / (k - 1) - 1) * half) : 0}deg` } as CSSProperties} />
))}
</span>
);
}
function seatLabel(v: OldMaidView, id: string, me: string | null, players: Record<string, PublicUser>): string {
const st = v.status[id];
const parts = [`${nick(players, id)}님${id === me ? '(나)' : ''}`];
if (st === 'out') parts.push(`다 털었어요, ${v.places[id]}등`);
else if (st === 'left') parts.push('나갔어요');
else parts.push(`카드 ${v.handCounts[id]}장`);
parts.push(`버린 짝 ${v.pairCounts[id]}쌍`);
if (v.turn === id) parts.push(v.target ? `${whose(players, v.target, me)} 카드를 뽑는 차례` : '뽑는 차례');
if (v.target === id && v.turn) parts.push(`${who(players, v.turn, me)}에게 카드를 뽑히는 중`);
if (v.final?.thief === id) parts.push('도둑');
if (v.away[id]) parts.push('자리 비움');
return parts.join(', ');
}
/** `r`: the view as of the last time the table stood still (counts, places, the thief), `v`: the live view (whose turn). */
function Seat({ id, v, r, me, players, deadline, bubble }: { id: string; v: OldMaidView; r: OldMaidView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; bubble: string | null }) {
const u = userOf(players, id);
const st = r.status[id];
const thief = r.final?.thief === id;
const cls = ['om-seat', v.turn === id ? 'turn anim-glow' : '', v.target === id ? 'target' : '', st !== 'playing' && !thief ? 'done' : '', thief ? 'thief' : ''].filter(Boolean).join(' ');
return (
<section className={cls} data-fx-seat={id} aria-label={seatLabel(r, id, me, players)}>
{bubble && (
<span className="om-bubble" aria-hidden>
{bubble}
</span>
)}
<div className="om-head">
<Avatar user={u} size={26} />
<span className="om-name">{u.nickname}</span>
{v.turn === id && <TurnTimer deadline={deadline} totalMs={v.turnMs} mine={false} size={30} />}
</div>
<div className="om-badges" aria-hidden>
{v.turn === id && <span className="om-badge turn">{v.target === me ? '내 카드 뽑는 중' : '뽑는 중'}</span>}
{v.target === id && <span className="om-badge target">{v.turn === me ? '내가 여기서 뽑아요' : '뽑히는 중'}</span>}
{st === 'out' && <span className="om-badge win">🎉 {r.places[id]}등</span>}
{st === 'left' && <span className="om-badge">나감</span>}
{thief && <span className="om-badge lose">🃏 도둑</span>}
{v.away[id] && <span className="om-badge">자리 비움</span>}
</div>
<div className="om-meta" aria-hidden>
{st === 'playing' || thief ? (
<>
<MiniFan n={r.handCounts[id] ?? 0} />
<span>
<strong>{r.handCounts[id]}</strong>장
</span>
</>
) : (
<span>{st === 'out' ? '다 털었어요' : '나갔어요'}</span>
)}
<span>· 짝 {r.pairCounts[id]}</span>
</div>
</section>
);
}
/** "[🙂 친구님] → [🙂 내 카드 3장]": the arrow always points from whoever draws to the hand being drawn from. */
function DrawTitle({ v, me, players }: { v: OldMaidView; me: string | null; players: Record<string, PublicUser> }) {
const drawer = v.turn!;
const target = v.target;
const count = target ? (v.handCounts[target] ?? 0) : 0;
const sentence = target ? `${drawerSubj(players, drawer, me)} ${whose(players, target, me)} 카드 ${count}장 중에서 한 장을 뽑아요` : `${drawerSubj(players, drawer, me)} 뽑을 차례예요`;
return (
<div className="om-title">
<span className="sr-only">{sentence}</span>
<span className={`om-who${drawer === me ? ' me' : ''}`} aria-hidden>
<Avatar user={userOf(players, drawer)} size={24} />
{drawer === me ? (
<span>내가</span>
) : (
<span className="lbl">
<span className="nm">{nick(players, drawer)}</span>님
</span>
)}
</span>
{target && (
<>
<span className="om-arrow" aria-hidden>
<svg width="28" height="16" viewBox="0 0 28 16">
<path d="M2 8h21M17 2l6 6-6 6" fill="none" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</span>
<span className={`om-who${target === me ? ' me' : ''}`} aria-hidden>
<Avatar user={userOf(players, target)} size={24} />
{target === me ? (
<span>내 카드</span>
) : (
<span className="lbl">
<span className="nm">{nick(players, target)}</span>님의 카드
</span>
)}
<b>{count}장</b>
</span>
</>
)}
</div>
);
}
const FAN_PC = { cw: 70, prefer: 54 };
const FAN_PHONE = { cw: 50, prefer: 39, wrapCw: 44 };
/** The face-down hand of the player being drawn from, held as a fan. Interactive only for the drawer. */
function Fan({ v, me, players, act, pending, tapConfirm, riffle }: { v: OldMaidView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; riffle: boolean }) {
const target = v.target!;
const mine = !!v.my?.canDraw && v.my.from === target;
const count = mine ? v.my!.count : (v.handCounts[target] ?? 0);
const [sel, setSel] = useState<number | null>(null);
const [ref, width, box, playH] = useWidth<HTMLDivElement>();
// A new turn, or the owner shuffled / the fan changed: start over.
useEffect(() => setSel(null), [v.turnNo, target, count, v.shuffles[target]]);
// Where every card sits now (relative to the table), so a draw by someone else lifts that very card (useOldMaidFx).
useEffect(() => {
const table = fxEl('om-table');
if (!table || !box.current) return;
const t = table.getBoundingClientRect();
fanSnap = {
target,
rects: Array.from(box.current.querySelectorAll('.om-back > .om-face'), (el) => {
const r = el.getBoundingClientRect();
return [r.left - t.left, r.top - t.top, r.width, r.height] as const;
}),
};
});
const g = cardGrow(v, width, playH);
const l = fanLayout(count, width, width > 0 && width < 520 ? FAN_PHONE : { cw: Math.round(FAN_PC.cw * g), prefer: Math.round(FAN_PC.prefer * g), wrapCw: Math.round((count > 12 ? 50 : 60) * g) });
const draw = (index: number) => {
if (pending) return;
myDrawRect = box.current?.querySelectorAll('button.om-back')[index]?.querySelector('.om-face')?.getBoundingClientRect() ?? null;
act({ type: 'draw', from: target, index });
setSel(null);
};
const tap = (i: number) => {
if (!mine) return;
if (sel === i || !tapConfirm) draw(i);
else {
setSel(i);
sfx.select();
}
};
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'Escape') {
setSel(null);
return;
}
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
const btns = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>('button.om-back'));
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();
};
const owner = who(players, target, me);
return (
<div
ref={ref}
className={`om-fan${l.wrap ? ' wrap' : ''}${riffle ? ' riffle' : ''}`}
style={rowStyle(l)}
role="group"
aria-label={mine ? `${owner}의 뒤집힌 카드 ${count}장. 좌우 방향키로 고르고 Enter로 뽑아요` : `${owner}의 뒤집힌 카드 ${count}장`}
onKeyDown={onKey}
>
{Array.from({ length: count }, (_, i) => {
const { t } = fanCard(i, count, l);
// Shuffling: the halves slide towards the middle and back, every other card a bit off, one after another.
const sx = (l.wrap ? 0 : Math.round(-t * Math.min(60, l.step * 1.5))) + (i % 2 ? 7 : -7);
const style = stripStyle(i, count, l, { '--i': i, '--sx': `${sx}px` });
const cls = `om-back om-strip${i === count - 1 ? ' last' : ''}`;
return mine ? (
<button
key={i}
type="button"
className={cls}
style={style}
aria-pressed={sel === i}
disabled={pending}
aria-label={`${i + 1}번째 카드${sel === i ? '. 한 번 더 누르면 뽑아요' : ''}`}
onClick={() => tap(i)}
>
<span className="om-face" aria-hidden>
<PlayingCard card={null} size="lg" style={{ width: '100%', height: '100%', filter: 'none' }} />
</span>
<span className="om-no" aria-hidden>
{i + 1}
</span>
</button>
) : (
<span key={i} className={cls} style={style} aria-hidden>
<span className="om-face">
<PlayingCard card={null} size="lg" style={{ width: '100%', height: '100%', filter: 'none' }} />
</span>
</span>
);
})}
</div>
);
}
function LastDraw({ v, me, players }: { v: OldMaidView; me: string | null; players: Record<string, PublicUser> }) {
// A new draw (the card drawn, the pair thrown away) is told only once its card has landed.
const shownNo = useAfterMotionValue(v.lastDraw?.no ?? 0);
const kept = useRef(v.lastDraw);
if ((v.lastDraw?.no ?? 0) === shownNo) kept.current = v.lastDraw;
const d = kept.current;
if (!d) return null;
const mineDraw = d.drawer === me;
const text = `${drawerSubj(players, d.drawer, me)} ${whose(players, d.from, me)} ${d.index + 1}번째 카드를 뽑았어요${d.auto ? '(시간 초과)' : ''}`;
let tail: string;
if (d.pair) tail = `${cardName(d.pair[0])}·${cardName(d.pair[1])} 짝을 버렸어요`;
else if (mineDraw && d.card) tail = d.card === JOKER ? '앗, 조커를 뽑았어요!' : `뽑은 카드 ${cardName(d.card)} · 짝이 없어서 손에 넣었어요`;
else tail = '짝이 없어서 손에 넣었어요';
return (
<div key={d.no} className="om-last" role="status" aria-label={`${text}. ${tail}`}>
{(d.pair || (mineDraw && d.card)) && (
<span className="cards" aria-hidden>
{d.pair ? d.pair.map((c) => <Card key={c} card={c} />) : <Card card={d.card} />}
</span>
)}
<span className="small txt" aria-hidden>
{text}
<br />
<strong>{tail}</strong>
</span>
</div>
);
}
function Pile({ v }: { v: OldMaidView }) {
const pairs = v.log.flatMap((e) => (e.t === 'draw' && e.pair ? [e.pair] : e.t === 'left' ? e.pairs : [])).slice(-6);
const total = Object.values(v.pairCounts).reduce((a, b) => a + b, 0);
return (
<div className="om-pile" data-fx="om-pile" aria-label={`버린 짝 모두 ${total}쌍${pairs.length ? `, 최근: ${pairs.map((p) => `${cardName(p[0])}·${cardName(p[1])}`).join(', ')}` : ''}`} role="group">
<span className="lbl">버린 짝 {total}쌍 / 26쌍</span>
{pairs.length > 0 && (
<span className="pairs">
{pairs.map((p, i) => (
<span key={i} className="pair" data-pair={pairKey(p)} aria-hidden>
<Card card={p[0]} />
<Card card={p[1]} />
</span>
))}
</span>
)}
</div>
);
}
function Table(props: { v: OldMaidView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; riffle: boolean; revealed: boolean }) {
const { v, me, players } = props;
if (v.phase === 'finished' && !props.revealed) {
// The last card is still flying (or the thief banner is up): the thief is unmasked after that.
return (
<div className="om-table" role="group" aria-label="테이블" data-fx="om-table">
<LastDraw v={v} me={me} players={players} />
<Pile v={v} />
</div>
);
}
if (v.phase === 'finished') {
const f = v.final!;
return (
<div className="om-table" role="group" aria-label="테이블" data-fx="om-table">
<strong className="om-title">게임이 끝났어요</strong>
{f.thief ? (
<>
<Card card={JOKER} className="om-thief-joker" style={{ '--cw': '64px' } as CSSProperties} />
<span style={{ textAlign: 'center', fontWeight: 800 }}>🃏 도둑: {who(players, f.thief, me)}</span>
</>
) : (
<span style={{ textAlign: 'center' }}>한 사람이 나가서 도둑 없이 끝났어요.</span>
)}
<span className="small" style={{ textAlign: 'center' }}>
{f.summary}
</span>
<LastDraw v={v} me={me} players={players} />
</div>
);
}
const drawer = v.turn!;
const target = v.target;
return (
<div className="om-table" role="group" aria-label="테이블" data-fx="om-table">
<DrawTitle v={v} me={me} players={players} />
{target && <Fan {...props} />}
{v.my?.canDraw ? (
<span className="small" style={{ textAlign: 'center' }}>
{props.tapConfirm ? '뽑을 카드를 눌러 고르고, 한 번 더 누르면 뽑아요.' : '뽑을 카드를 누르면 바로 뽑아요.'} 숫자는 왼쪽부터의 자리예요.
</span>
) : (
<span className="small" style={{ textAlign: 'center' }}>
{target === me
? `${drawerSubj(players, drawer, me)} 내 카드를 고르는 중이에요. 아래 [🔀 섞기]로 순서를 바꿀 수 있어요.`
: `${drawerSubj(players, drawer, me)} ${target ? `${whose(players, target, me)} 카드를 ` : ''}고르는 중이에요.`}
</span>
)}
<LastDraw v={v} me={me} players={players} />
<Pile v={v} />
</div>
);
}
const HAND_PC = { cw: 72, prefer: 46 };
const HAND_PHONE = { cw: 50, prefer: 34 };
function MyArea({ v, r, me, players, act, pending, deadline, fresh, bubble }: { v: OldMaidView; r: OldMaidView; me: string; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) {
const hand = v.myHand ?? [];
const st = v.status[me];
const cls = ['om-me', v.turn === me ? 'turn anim-glow' : '', v.target === me ? 'target' : ''].filter(Boolean).join(' ');
const [ref, width, box, playH] = useWidth<HTMLDivElement>();
const narrow = width > 0 && width < 520;
const g = narrow ? 1 : cardGrow(v, width, playH);
const base = narrow ? HAND_PHONE : HAND_PC;
const l = fanLayout(hand.length, width, { cw: Math.round(base.cw * g), prefer: Math.round(base.prefer * g), wrapCw: Math.round((narrow ? (hand.length > 12 ? 44 : 50) : hand.length > 12 ? 52 : 64) * g) });
// Shuffled (same cards, new order): every card slides with a little hop from its old place to its new one.
const order = hand.join(',');
const pos = useRef<{ order: string; at: Map<string, [number, number]> }>({ order: '', at: new Map() });
useLayoutEffect(() => {
const el = box.current;
const prev = pos.current;
const at = new Map<string, [number, number]>();
const cards = el ? Array.from(el.querySelectorAll<HTMLElement>('.om-card')) : [];
if (el) {
const b = el.getBoundingClientRect();
for (const c of cards) {
const r = c.getBoundingClientRect();
at.set(c.dataset.card ?? '', [r.left - b.left, r.top - b.top]);
}
}
pos.current = { order, at };
if (prev.order === order || prev.at.size !== at.size || at.size < 2 || reducedMotion() || ![...at.keys()].every((k) => prev.at.has(k))) return;
let n = 0;
for (const c of cards) {
const a = prev.at.get(c.dataset.card ?? '');
const b = at.get(c.dataset.card ?? '');
if (!a || !b) continue;
const dx = a[0] - b[0];
const dy = a[1] - b[1];
if (Math.abs(dx) + Math.abs(dy) < 2 || typeof c.animate !== 'function') continue;
fxAnim(c.animate(
[{ transform: `translate(${dx}px, ${dy}px)` }, { transform: `translate(${dx / 2}px, ${dy / 2 - 18}px)`, offset: 0.45 }, { transform: 'translate(0px, 0px)' }],
{ duration: 480, delay: n++ * 14, easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'backwards', composite: 'add' },
));
}
}, [order, width, l.wrap]);
return (
<section className={cls} data-fx-seat={me} aria-label="내 자리">
{bubble && (
<span className="om-bubble" aria-hidden>
{bubble}
</span>
)}
<div className="om-head">
<Avatar user={userOf(players, me)} size={26} />
<span className="om-name">{nick(players, me)} (나)</span>
{v.turn === me && v.phase === 'playing' && (
<span className="om-badge turn" aria-hidden>
뽑을 차례
</span>
)}
{v.target === me && (
<span className="om-badge target" aria-hidden>
뽑히는 중
</span>
)}
{v.away[me] && <span className="om-badge">자리 비움</span>}
{r.status[me] === 'out' && <span className="om-badge win">🎉 {r.places[me]}등</span>}
{r.final?.thief === me && <span className="om-badge lose">🃏 도둑</span>}
{v.turn === me && <TurnTimer deadline={deadline} totalMs={v.turnMs} mine size={30} />}
</div>
<div className="om-mine">
<strong>
내 손패 {hand.length}장 · 버린 짝 {v.pairCounts[me]}쌍
</strong>
{v.phase === 'playing' && st === 'playing' && (
<button type="button" className="btn btn-secondary om-shuffle" disabled={!v.my?.canShuffle || pending} onClick={() => act({ type: 'shuffle' })}>
🔀 섞기{v.my ? ` (${v.my.shufflesLeft}/${SHUFFLES_PER_TURN})` : ''}
</button>
)}
</div>
{hand.length > 0 ? (
<div ref={ref} className={`om-hand${l.wrap ? ' wrap' : ''}`} style={rowStyle(l)} data-fx="om-hand" role="list" aria-label={`내 손패, 왼쪽부터: ${hand.map(cardAria).join(', ')}`}>
{hand.map((c, i) => (
<span key={c} role="listitem" aria-label={cardAria(c)} style={{ display: 'contents' }}>
<Card
card={c}
className={['om-strip', i === hand.length - 1 ? 'last' : '', c === JOKER ? 'joker' : '', c === fresh ? 'fresh' : ''].filter(Boolean).join(' ')}
style={stripStyle(i, hand.length, l)}
/>
</span>
))}
</div>
) : (
<span className="om-note">{st === 'out' ? '손패를 다 털었어요! 끝날 때까지 구경해요.' : '손에 카드가 없어요.'}</span>
)}
{st === 'playing' && v.phase === 'playing' && (
<span className="om-note">다른 사람에게는 이 순서 그대로 뒷면으로 보여요. 조커를 어디에 둘지 섞어서 숨겨 보세요.</span>
)}
</section>
);
}
// ---------------------------------------------------------------- board
function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm }: BoardProps<OldMaidView>) {
const amPlayer = !!me && v.order.includes(me);
const [announce, setAnnounce] = useState('');
const [bubbles, setBubbles] = useState<Record<string, string>>({});
const [riffle, setRiffle] = useState(false);
const [fresh, setFresh] = useState<string | null>(null);
const prev = useRef({ logCount: v.logCount, hand: v.myHand ?? [], turn: v.turn });
const [banner, showBanner] = useBanner();
useOldMaidFx(v, me, players, showBanner);
// "조커를 뽑았어요!" tells what the card is: only once it has landed in my hand.
const [note, setNote] = useState<{ text: string; buzz: number | number[] } | null>(null);
const noteReady = useMotionSettled(!!note);
useEffect(() => {
if (!noteReady || !note) return;
toast(note.text);
haptic(note.buzz);
setNote(null);
}, [noteReady]); // eslint-disable-line react-hooks/exhaustive-deps
// Places, counts and the thief change on screen once the cards have landed; the end table after the thief banner.
const shown = useAfterMotionValue(v);
const revealed = useMotionSettled(v.phase === 'finished');
const popBubbles = (bub: Record<string, string>) => {
setBubbles((b) => ({ ...b, ...bub }));
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), fxMs(2500));
};
const [bubQ, setBubQ] = useState<Record<string, string> | null>(null);
const bubReady = useMotionSettled(!!bubQ);
useEffect(() => {
if (!bubReady || !bubQ) return;
popBubbles(bubQ);
setBubQ(null);
}, [bubReady]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
const p = prev.current;
// New public log entries since last time (the log keeps only the last 30).
const n = Math.max(0, Math.min(v.log.length, v.logCount - p.logCount));
const added = n ? v.log.slice(-n) : [];
const msgs: string[] = [];
const bub: Record<string, string> = {};
let shuffled = false;
for (const e of added) {
msgs.push(logText(e, players, me));
if (e.t === 'shuffle') {
bub[e.player] = '🔀 섞었어요';
if (e.player === v.target) shuffled = true;
} else if (e.t === 'draw' && e.pair) bub[e.drawer] = '짝!';
else if (e.t === 'out') bub[e.player] = '🎉 다 털었어요';
}
const hand = v.myHand ?? [];
const ld = v.lastDraw;
if (amPlayer && ld && added.some((e) => e.t === 'draw')) {
if (ld.drawer === me && ld.card === JOKER) setNote({ text: '앗, 조커를 뽑았어요! 다른 사람이 가져가게 섞어 보세요.', buzz: [40, 30, 40] });
else if (ld.from === me && p.hand.includes(JOKER) && !hand.includes(JOKER)) setNote({ text: '조커를 넘겼어요! 😆', buzz: 40 });
setFresh(ld.drawer === me && !ld.pair ? ld.card : null);
}
if (amPlayer && v.turn === me && p.turn !== me && v.phase === 'playing') {
sounds.myTurn();
haptic(40);
msgs.push('내 차례예요.');
}
if (msgs.length) setAnnounce(msgs.join(' '));
if (Object.keys(bub).length) {
// "짝!" / "다 털었어요" once the drawn card has landed; "섞었어요" right away (it goes with the riffle).
if (added.some((e) => e.t !== 'shuffle')) setBubQ((q) => ({ ...q, ...bub }));
else popBubbles(bub);
}
prev.current = { logCount: v.logCount, hand, turn: v.turn };
if (shuffled) {
setRiffle(true);
const t = setTimeout(() => setRiffle(false), fxMs(1000));
return () => clearTimeout(t);
}
return undefined;
}, [v.seq]); // eslint-disable-line react-hooks/exhaustive-deps
const seats = amPlayer ? v.order.slice(v.order.indexOf(me!) + 1).concat(v.order.slice(0, v.order.indexOf(me!))) : v.order;
return (
<div className="om-board" role="region" aria-label="도둑잡기 판">
<style>{CSS}</style>
<div className="om-seats">
{seats.map((p) => (
<Seat key={p} id={p} v={v} r={shown} me={me} players={players} deadline={deadline} bubble={bubbles[p] ?? null} />
))}
</div>
<Table v={v} me={me} players={players} act={act} pending={pending} tapConfirm={tapConfirm} riffle={riffle} revealed={revealed} />
{amPlayer && <MyArea v={v} r={shown} me={me!} players={players} act={act} pending={pending} deadline={deadline} fresh={fresh} bubble={bubbles[me!] ?? null} />}
<p className="sr-only" aria-live="polite">
{announce}
</p>
{banner}
</div>
);
}
/**
* Sounds + motion for every change of the table (new public log entries), mine or anyone else's. Only uses what this
* viewer's view shows: the joker sounds play only for whoever saw the joker come or go in their own hand.
*/
function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const amPlayer = !!me && v.order.includes(me);
const hand = v.myHand ?? [];
const prevHand = useRef(hand);
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
// Banners ("1등!", "도둑!") wait until the card that caused them has landed; the screen counts as moving meanwhile,
// so the room's result window opens only after the banner.
const flightEnd = useRef(0);
const bannerTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const [bannerWait, setBannerWait] = useState(false);
useMotionHold(bannerWait);
useEffect(() => () => clearTimeout(bannerTimer.current), []);
const bannerAfterFlight = (...args: Parameters<typeof showBanner>) => {
clearTimeout(bannerTimer.current);
const wait = flightEnd.current - performance.now();
if (wait <= 0) {
setBannerWait(false);
return showBanner(...args);
}
setBannerWait(true);
bannerTimer.current = setTimeout(() => {
setBannerWait(false);
showBanner(...args);
}, wait);
};
/** My seat is my own area; the hand inside it is a better spot for cards leaving / arriving. */
const spot = (p: string) => (p === me ? (fxEl('om-hand') ?? seatEl(p)) : seatEl(p));
const entries = v.log.map((e, i) => ({ e, n: v.logCount - v.log.length + i }));
useNewEntries(entries, (x) => x.n, (fresh) => {
let t = 0;
let end = 0; // when the last flying card lands (written ms)
const ld = v.lastDraw;
const pile = (pairs: [string, string][], from: Element | null, delay: number) => {
for (const p of pairs) flyFrom(document.querySelector(`.om-pile [data-pair="${cssEsc(pairKey(p))}"]`), from, { delay, ms: 420, rotate: 14 });
};
for (const { e } of fresh) {
const at = t;
switch (e.t) {
case 'draw': {
const newMine = e.drawer === me && !e.pair && ld?.no === e.no && ld.drawer === me && ld.card ? handCardEl(ld.card) : null;
// The drawn card itself rises out of the fan and flies to whoever drew it (my new card shows up when it lands).
const from = e.drawer === me && myDrawRect ? myDrawRect : fanCardRect(e.from, e.index);
const lifted = !!from && liftFly(from, newMine?.querySelector('.om-face') ?? spot(e.drawer), at);
if (lifted && newMine) reveal(newMine, at + LIFT_MS - 120);
else if (!lifted && newMine) flyFrom(newMine, myDrawRect ?? seatEl(e.from), { ms: 420, rotate: 12, delay: at });
else if (!lifted) flyGhost(spot(e.from), spot(e.drawer), { delay: at, ms: 420 });
if (e.drawer === me) myDrawRect = null;
fanSnap = null;
const land = lifted ? LIFT_MS - 140 : 300;
end = Math.max(end, at + (lifted ? LIFT_MS : 420));
later(at, () => {
if (e.auto) sfx.tick();
sfx.draw();
});
if (e.pair) {
pile([e.pair], spot(e.drawer), at + land);
later(at + land + 30, omSfx.pair);
end = Math.max(end, at + land + 420);
t += land + 120;
} else t += 160;
break;
}
case 'out':
later(at, () => {
omSfx.out();
bump(seatEl(e.player), 'pop');
});
flightEnd.current = performance.now() + fxMs(end);
bannerAfterFlight(`${e.place}등!`, 'green', e.player === me ? '손패를 다 털었어요' : `${nick(players, e.player)}님 다 털었어요`);
t += 150;
break;
case 'shuffle':
later(at, () => {
sfx.shuffle();
// My own hand slides card by card (MyArea), the fan being drawn from riffles (Fan); other seats wiggle.
if (e.player !== me) bump(seatEl(e.player), 'shake');
});
t += 120;
break;
case 'left': {
let n = 0;
for (const g of e.gave) {
flyGhost(seatEl(e.player), spot(g.to), { count: g.count, gap: 60, delay: at });
n += g.count;
}
if (n) later(at, () => sfx.deal(Math.min(n, 8), 60));
if (e.pairs.length) {
pile(e.pairs, seatEl(e.player), at + 350);
later(at + 380, omSfx.pair);
end = Math.max(end, at + 350 + 420);
}
end = Math.max(end, at + 480 + 60 * Math.max(0, n - 1));
t += 400;
break;
}
}
}
// The joker came into / left my own hand: only this screen knows, so only this screen hears it.
if (amPlayer) {
const had = prevHand.current.includes(JOKER);
const has = hand.includes(JOKER);
if (!had && has) {
later(t + 150, () => {
omSfx.jokerGot();
bump(handCardEl(JOKER), 'shake');
});
} else if (had && !has && v.phase === 'playing') later(t + 150, omSfx.jokerGone);
}
flightEnd.current = performance.now() + fxMs(end);
});
useLayoutEffect(() => {
prevHand.current = hand;
});
// The end: the thief is unmasked (the win / lose sound itself comes from the room screen).
useChange(v.phase, (now) => {
const thief = v.final?.thief;
if (now !== 'finished' || !thief) return;
bannerAfterFlight('🃏 도둑!', 'dark', thief === me ? '내가 조커를 들고 있었어요' : `${nick(players, thief)}님`);
// (The joker on the end table pops by itself when it shows, after the banner.)
setTimeout(() => bump(seatEl(thief), 'shake'), Math.max(0, flightEnd.current - performance.now()) + fxMs(200));
});
const started = useRef(false);
useLayoutEffect(() => {
if (started.current) return;
started.current = true;
// Mounted right at the start (nobody has drawn or shuffled yet): show the deal once.
if (v.phase !== 'playing' || v.logCount !== 0 || v.turnNo !== 1) return;
sfx.shuffle();
setTimeout(() => sfx.deal(8, 60), fxMs(300));
// Next frame: the card rows lay themselves out once their width is known (useWidth), so measure after that.
requestAnimationFrame(() => {
const table = fxEl('om-table');
document.querySelectorAll('.om-hand .om-card').forEach((el, i) => flyFrom(el, table, { delay: 280 + i * 40, rotate: 10 }));
for (const p of v.order) if (p !== me) flyGhost(table, seatEl(p), { count: 3, gap: 90, delay: 280 });
});
}, []); // eslint-disable-line react-hooks/exhaustive-deps
}
// ---------------------------------------------------------------- side
function OldMaidSide({ view, me, players, deadline }: BoardProps<OldMaidView>) {
// The side panel (places, the thief, the log) follows the board once its cards have landed.
const v = useAfterMotionValue(view);
const running = v.phase === 'playing';
const log = v.log.filter((e) => e.t !== 'shuffle').slice(-8).reverse();
return (
<>
<style>{CSS}</style>
<div className="card stack" style={{ gap: 8, padding: 12 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<strong>{running ? `${nick(players, v.turn!)}님 차례` : '게임 끝'}</strong>
{running && <TurnTimer deadline={deadline} totalMs={v.turnMs} mine={v.turn === me} size={36} />}
</div>
<span className="small muted">{optionsSummary(v.options)}</span>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 6 }} aria-label="참가자(앉은 순서, 다음 사람에게서 뽑아요)">
{v.order.map((p) => (
<li key={p} className="row" style={{ gap: 6, flexWrap: 'nowrap', alignItems: 'center' }} aria-label={seatLabel(v, p, me, players)}>
<Avatar user={userOf(players, p)} size={24} />
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: p === me ? 800 : 600 }} aria-hidden>
{nick(players, p)}
{v.turn === p ? ' · 차례' : ''}
{v.final?.thief === p ? ' · 🃏 도둑' : ''}
</span>
<span className="small muted" style={{ whiteSpace: 'nowrap' }} aria-hidden>
{v.status[p] === 'out' ? `${v.places[p]}등` : v.status[p] === 'left' ? '나감' : `${v.handCounts[p]}장`}
</span>
</li>
))}
</ol>
</div>
{v.final && (
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<strong>결과</strong>
<span>{v.final.thief ? `🃏 도둑은 ${who(players, v.final.thief, me)}${v.final.thief === me ? '예요' : '이에요'}.` : '한 사람이 나가서 끝났어요.'}</span>
<ol className="om-log">
{v.final.ranking.map((g, i) => (
<li key={i}>
<strong>{v.final!.ranking.slice(0, i).reduce((n, x) => n + x.length, 1)}등</strong> {g.map((p) => `${nick(players, p)}${p === v.final!.thief ? ' (도둑)' : v.status[p] === 'left' ? ' (나감)' : ''}`).join(', ')}
</li>
))}
</ol>
</div>
)}
{log.length > 0 && (
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<strong>최근 기록</strong>
<ol className="om-log" aria-label="최근 기록, 새 것부터">
{log.map((e, i) => (
<li key={i}>{logText(e, players, me)}</li>
))}
</ol>
</div>
)}
<details className="card" style={{ padding: 12 }} open={running}>
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>도움말</summary>
<ul className="small" style={{ margin: '8px 0 0', paddingLeft: 18, display: 'grid', gap: 4 }}>
<li>내 차례에는 다음 사람(왼쪽)의 뒷면 카드 중 한 장을 뽑아요.</li>
<li>같은 숫자 두 장은 저절로 짝으로 버려져요(무늬는 상관없어요).</li>
<li>손패를 먼저 다 털수록 높은 등수예요.</li>
<li>마지막까지 조커를 든 사람이 도둑(꼴찌)이에요.</li>
<li>[🔀 섞기]로 내 손패 순서를 섞을 수 있어요(차례마다 3번까지).</li>
</ul>
</details>
</>
);
}
// ---------------------------------------------------------------- status
function isMyTurn(v: OldMaidView, me: string | null): boolean {
return !!me && v.phase === 'playing' && v.turn === me;
}
function statusText(v: OldMaidView, me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'finished') return v.final?.summary ?? '게임이 끝났어요';
const t = v.turn!;
const target = v.target;
if (isMyTurn(v, me)) return `내 차례예요. ${target ? `${nick(players, target)}님 카드에서 한 장 뽑아요` : '기다려 주세요'}`;
if (target && target === me) return `${nick(players, t)}님이 내 카드를 고르는 중이에요`;
return `${nick(players, t)}님이 ${target ? `${nick(players, target)}님 카드를 ` : ''}고르는 중이에요`;
}
// ---------------------------------------------------------------- options
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
function Field({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="stack" style={{ gap: 6 }}>
<strong>{label}</strong>
{children}
</div>
);
}
function Options({ value: o, onChange }: OptionsProps<OldMaidOptions>) {
return (
<div className="stack" style={{ gap: 16 }}>
<Field label="한 번 뽑는 제한 시간">
<Seg
label="한 번 뽑는 제한 시간"
value={o.turnSeconds}
options={[
[10, '10초'],
[20, '20초'],
[30, '30초'],
[60, '60초'],
[null, '무제한'],
]}
onChange={(turnSeconds) => onChange({ ...o, turnSeconds })}
/>
</Field>
</div>
);
}
function optionsSummary(o: OldMaidOptions): string {
return `트럼프 52장 + 조커 1장 · ${o.turnSeconds === null ? '시간 무제한' : `제한 ${o.turnSeconds}초`}`;
}
function Rules({ options }: { options?: OldMaidOptions }) {
const row: CSSProperties = { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' };
return (
<div className="stack">
<p>
옆 사람 손패에서 한 장씩 몰래 뽑아 같은 숫자 짝을 버리다가, <strong>마지막에 조커를 들고 있는 사람이 도둑(꼴찌)</strong>이 되는 카드놀이예요. 2~8명이 할 수 있어요.
</p>
<div style={row} role="img" aria-label="하트 7과 스페이드 7은 짝이라 버리고, 조커는 짝이 없어요">
<PlayingCard card="7H" size="sm" />
<PlayingCard card="7S" size="sm" />
<span aria-hidden>→ 짝! 버려요 ·</span>
<PlayingCard card={JOKER} size="sm" />
<span aria-hidden>짝 없음</span>
</div>
<p>
<strong>준비</strong>: 트럼프 52장에 조커 1장을 넣은 53장을 섞어 모두에게 한 장씩 고르게 나눠요(한 장 차이는 괜찮아요). 먼저 나누어 받는 사람은 무작위로 정하고, 그 사람이 먼저 뽑아요. 나눈 뒤 각자 손에서 같은 숫자 두 장을 짝으로 모두
버려요(무늬는 상관없어요). 이건 저절로 돼요.
</p>
<p>
<strong>뽑기</strong>: 내 차례에는 다음 사람(왼쪽)이 뒷면으로 내민 카드 중 한 장을 골라 뽑아요. 뽑은 카드로 짝이 생기면 바로 버리고, 짝이 없으면 내 손에 넣어요(내 손패 아무 자리에 섞여 들어가요). 그다음 차례는 내가 뽑아 온 사람이에요.
</p>
<p>
<strong>섞기</strong>: 언제든 [🔀 섞기]로 내 손패 순서를 섞을 수 있어요(차례마다 {SHUFFLES_PER_TURN}번까지). 다른 사람에게는 내 손패가 순서 그대로 뒷면으로 보이니, 조커를 숨길 때 써 보세요.
</p>
<p>
<strong>끝</strong>: 손패를 다 턴 사람은 빠지고, 먼저 턴 순서대로 1등, 2등…이에요. 짝이 다 버려지면 조커 한 장만 남고, 그걸 든 사람이 도둑이에요.
</p>
<p className="muted">
{options?.turnSeconds === null
? '시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 무작위로 한 장을 대신 뽑아 주고, 그런 일이 세 번 연속이면 그 사람은 5초 안에 뽑아야 해요.'
: `${options?.turnSeconds ?? 20}초 안에 고르지 않으면 무작위로 한 장을 뽑아요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요.`}{' '}
카드를 든 채 게임을 나가면 그 사람 카드는 섞어서 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고(짝이
생기면 버려요), 나간 사람은 맨 아래 등수가 돼요. 둘만 남았을 때 한 사람이 나가면 도둑 없이 끝나요.
</p>
<p className="small muted">{PLAYING_CARD_CREDIT}</p>
</div>
);
}
const ui: GameUI<OldMaidView, OldMaidOptions> = {
Board: OldMaidBoard,
Side: OldMaidSide,
statusText,
isMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;