카드 게임 시간 무제한(우노·뱅!·달무티·고스톱·도둑잡기·포커·바퀴벌레 포커·99), 공통 카드 움직임(card-fx), 우노·달무티·도둑잡기·포커 소리·애니메이션

- 무제한(null): 차례 시계·타임아웃 없음, 자리 비움만 짧은 시계, 연결 끊김은 방 유예 뒤 자동 행동 그대로
- 포커는 리바이 고르는 시간도 무제한 가능, 고스톱은 고·스톱 선택 시간도 무제한 가능, 뱅!은 반응 시간·캐릭터 고르기도
- card-fx: 날아가는 카드·칩(ghost), 제자리 날아오기, 배너, view 변화 감지 훅(처음 렌더·다시 보기는 건너뜀)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 13:04:11 +09:00
parent f12cf12b84
commit ac37a6a6d8
44 changed files with 1438 additions and 198 deletions

View File

@@ -77,7 +77,7 @@ export function helpNow(v: BangView, me: string | null, players: Record<string,
if (use.length >= p.needed) {
const label = use.map((c) => NAME[c.kind as 'bang' | 'missed'] ?? '빗나감!').join(' + ');
lines.push(`[${label} 내기]를 누르면 막아요. 막지 않으려면 [맞기 (생명 −1)]를 눌러요.`);
if (v.options.autoDefend) lines.push('시간 안에 고르지 않으면 막을 카드를 자동으로 내요.');
if (v.options.autoDefend) lines.push(v.options.reactionSeconds === null ? '반응 시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 막을 카드를 자동으로 내요.' : '시간 안에 고르지 않으면 막을 카드를 자동으로 내요.');
} else lines.push(`막을 카드가 ${p.options.length > 0 ? '모자라요' : '없어요'}. [맞기 (생명 −1)]를 눌러요.`);
if (p.canBarrel) lines.push('[술통 판정하기]를 누르면 카드를 한 장 뒤집어 ♥가 나올 때 피해요.');
lines.push(life);

View File

@@ -1034,7 +1034,7 @@ function BangSide({ view: v, me, players }: BoardProps<BangView>) {
{v.winner ? ' · 게임 끝' : ''}
</strong>
<span className="small muted">
카드 더미 {v.deckCount}장 · 버린 카드 {v.discardCount}장 · 반응 {v.options.reactionSeconds}초 · 턴 {v.options.turnSeconds}초
카드 더미 {v.deckCount}장 · 버린 카드 {v.discardCount}장 · {secText('반응', v.options.reactionSeconds)} · {secText('턴', v.options.turnSeconds)}
</span>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
{v.players.map((p) => (
@@ -1132,7 +1132,7 @@ function statusText(v: BangView, me: string | null, players: Record<string, Publ
// ---------------------------------------------------------------- options
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
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]) => (
@@ -1168,10 +1168,10 @@ function Options({ value: o, onChange }: OptionsProps<BangOptions>) {
<Seg label="캐릭터 정하기" value={o.characterDraft} options={[['random', '무작위 1장'], ['choose2', '2장 중 고르기']]} onChange={(characterDraft) => set({ characterDraft })} />
</Field>
<Field label="내 턴 제한 시간">
<Seg label="내 턴 제한 시간" value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [120, '120초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Seg label="내 턴 제한 시간" value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [120, '120초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
<Field label="반응 제한 시간" help="빗나감!·맥주·결투·잡화점을 고르는 시간이에요.">
<Seg label="반응 제한 시간" value={o.reactionSeconds} options={[[8, '8초'], [15, '15초'], [25, '25초']]} onChange={(reactionSeconds) => set({ reactionSeconds })} />
<Field label="반응 제한 시간" help="빗나감!·맥주·결투·잡화점을 고르는 시간이에요. 무제한이어도 연결이 끊긴 채 오래 돌아오지 않으면 자동으로 골라요.">
<Seg label="반응 제한 시간" value={o.reactionSeconds} options={[[8, '8초'], [15, '15초'], [25, '25초'], [null, '무제한']]} onChange={(reactionSeconds) => set({ reactionSeconds })} />
</Field>
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
@@ -1208,8 +1208,10 @@ function Options({ value: o, onChange }: OptionsProps<BangOptions>) {
);
}
const secText = (what: string, sec: number | null) => (sec === null ? `${what} 시간 무제한` : `${what} ${sec}초`);
function optionsSummary(o: BangOptions): string {
const parts = [o.characterDraft === 'choose2' ? '캐릭터 고르기' : '캐릭터 무작위', `턴 ${o.turnSeconds}초`, `반응 ${o.reactionSeconds}초`];
const parts = [o.characterDraft === 'choose2' ? '캐릭터 고르기' : '캐릭터 무작위', secText('턴', o.turnSeconds), secText('반응', o.reactionSeconds)];
if (!o.autoDefend) parts.push('자동 방어 끔');
if (o.drawBeforeDeath || o.beerAtFullHealth || o.selfTargetCatBalou || o.deputyCount7) parts.push('하우스 룰');
return parts.join(' · ');
@@ -1239,7 +1241,7 @@ function CardTable() {
);
}
function Rules() {
function Rules({ options }: { options?: BangOptions }) {
return (
<div className="stack">
<p>
@@ -1256,7 +1258,10 @@ function Rules() {
<p>
생명이 0이 되면 맥주로 살아날 수 있어요(2명 남으면 안 돼요). 무법자를 쓰러뜨리면 카드 3장을 받고, 보안관이 부관을 쓰러뜨리면 카드를 모두 버려요. 쓰러진 사람의 역할은 공개돼요.
</p>
<p className="small muted">반응 시간이 지나면 막을 카드가 있을 때 자동으로 내요(설정에서 끌 수 있어요). 내 역할은 역할 카드를 꾹 누르고 있을 때만 보여요.</p>
<p className="small muted">
{options?.reactionSeconds === null ? '이 방은 반응 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '반응 시간이 지나면'} 막을 카드가 있을 때 자동으로 내요(설정에서 끌 수
있어요).{options?.turnSeconds === null ? ' 내 턴도 시간 제한이 없고, 연결이 끊긴 채 오래 돌아오지 않으면 턴을 자동으로 마쳐요.' : ''} 내 역할은 역할 카드를 꾹 누르고 있을 때만 보여요.
</p>
<CardTable />
<table className="bg-rules small" style={{ borderCollapse: 'collapse', width: '100%' }}>
<tbody>

View File

@@ -0,0 +1,228 @@
/**
* Motion + sound helpers shared by the card games (포커·고스톱·달무티·99·도둑잡기·우노·바퀴벌레 포커·뱅!, 2026-10-13).
*
* - Everything reacts to *view changes*, so the other players' moves animate and sound too, and skips the first
* render: joining, reloading or a replay jump (the replay page remounts the board) never replays old moves.
* - Web Animations only (no layout change, `composite: 'add'` keeps the element's own transform), short (≤ 0.6 s),
* and flying copies ("ghosts") never take clicks, so nothing waits for an animation.
* - Respects `prefers-reduced-motion` (Web Animations are not covered by the global CSS rule, so it is checked here).
* - Sounds stay in `lib/feedback` (`sfx`, `tone`, `noise`); game-specific ones live in each game folder.
*/
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
export const reducedMotion = (): boolean => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
type Where = Element | DOMRect | null | undefined;
function rectOf(w: Where): DOMRect | null {
if (!w) return null;
const r = w instanceof Element ? w.getBoundingClientRect() : w;
return r.width === 0 && r.height === 0 ? null : r;
}
const center = (r: DOMRect) => ({ x: r.left + r.width / 2, y: r.top + r.height / 2 });
/** `CSS.escape` (games usually shadow `CSS` with their own style string). */
export const cssEsc = (v: string): string => CSS.escape(v);
/** First element matching `[data-fx="<name>"]` (pile, deck, pot, hand …) or a seat `[data-fx-seat="<player id>"]`. */
export const fxEl = (name: string): Element | null => document.querySelector(`[data-fx="${CSS.escape(name)}"]`);
export const seatEl = (player: string): Element | null => document.querySelector(`[data-fx-seat="${CSS.escape(player)}"]`);
export interface FlyOpts {
ms?: number;
delay?: number;
/** Start scale (default 0.6). */
scale?: number;
/** Start rotation in degrees (default -10). */
rotate?: number;
}
/** Makes `el` (already at its final place) fly in from `from` (an element or rect). */
export function flyFrom(el: Element | null | undefined, from: Where, o: FlyOpts = {}): void {
const a = rectOf(from);
const b = rectOf(el);
if (!el || !a || !b || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
const p = center(a);
const q = center(b);
const dx = p.x - q.x;
const dy = p.y - q.y;
if (Math.abs(dx) + Math.abs(dy) < 4) return;
(el as HTMLElement).animate(
[
{ transform: `translate(${dx}px, ${dy}px) scale(${o.scale ?? 0.6}) rotate(${o.rotate ?? -10}deg)`, opacity: 0.35 },
{ transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 },
],
{ duration: o.ms ?? 380, delay: o.delay ?? 0, easing: 'cubic-bezier(.2,.8,.3,1)', fill: 'backwards', composite: 'add' },
);
}
export type GhostKind = 'card' | 'hwatu' | 'chip' | 'coin';
export interface GhostOpts {
kind?: GhostKind;
/** How many copies (staggered by `gap` ms), e.g. dealing 3 cards or a stack of chips. */
count?: number;
gap?: number;
ms?: number;
delay?: number;
/** Optional text on the ghost (a chip amount, a card name). */
label?: string;
/** Extra class for a game-specific look (game CSS must target `.fx-ghost.<class>`). */
className?: string;
}
const GHOST_SIZE: Record<GhostKind, [number, number]> = { card: [40, 56], hwatu: [34, 54], chip: [22, 22], coin: [22, 22] };
/**
* A temporary copy flying from one place to another (card dealt to a seat, chips to the pot, pot to the winner …).
* Fixed-position, pointer-events none, removed when done.
*/
export function flyGhost(from: Where, to: Where, o: GhostOpts = {}): void {
const a = rectOf(from);
const b = rectOf(to);
if (!a || !b || reducedMotion() || typeof document === 'undefined') return;
ensureCss();
const kind = o.kind ?? 'card';
const [w, h] = GHOST_SIZE[kind];
const p = center(a);
const q = center(b);
const n = Math.max(1, Math.min(o.count ?? 1, 12));
for (let i = 0; i < n; i++) {
const g = document.createElement('div');
g.className = `fx-ghost fx-ghost-${kind}${o.className ? ` ${o.className}` : ''}`;
g.setAttribute('aria-hidden', 'true');
if (o.label) g.textContent = o.label;
g.style.left = `${p.x - w / 2}px`;
g.style.top = `${p.y - h / 2}px`;
document.body.appendChild(g);
const jitter = n > 1 ? (i - (n - 1) / 2) * 6 : 0;
const anim = g.animate(
[
{ transform: 'translate(0px, 0px) scale(.85) rotate(-8deg)', opacity: 0 },
{ opacity: 1, offset: 0.15 },
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(1) rotate(0deg)`, opacity: 1, offset: 0.85 },
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(.9) rotate(0deg)`, opacity: 0 },
],
{ duration: o.ms ?? 480, delay: (o.delay ?? 0) + i * (o.gap ?? 70), easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'both' },
);
const done = () => g.remove();
anim.onfinish = done;
anim.oncancel = done;
// Safety net (a background tab may never finish the animation).
setTimeout(done, (o.ms ?? 480) + (o.delay ?? 0) + i * (o.gap ?? 70) + 1500);
}
}
/** Quick attention wiggle / pop on an element that is already there (a seat that drew, a counter that changed). */
export function bump(el: Element | null | undefined, kind: 'pop' | 'shake' = 'pop'): void {
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
const frames =
kind === 'pop'
? [{ transform: 'scale(1)' }, { transform: 'scale(1.12)', offset: 0.4 }, { transform: 'scale(1)' }]
: [
{ transform: 'translateX(0px)' },
{ transform: 'translateX(-6px) rotate(-2deg)', offset: 0.25 },
{ transform: 'translateX(6px) rotate(2deg)', offset: 0.5 },
{ transform: 'translateX(-4px) rotate(-1deg)', offset: 0.75 },
{ transform: 'translateX(0px)' },
];
(el as HTMLElement).animate(frames, { duration: kind === 'pop' ? 320 : 420, easing: 'ease-out', composite: 'add' });
}
// ---------------------------------------------------------------- hooks
/**
* Calls `onNew` (in a layout effect, before paint, so new elements can still be animated from elsewhere) with the
* entries of `list` whose `key` was not there on the previous render. Never on the first render. A jump of more
* than `max` new entries at once (resync, reconnect) is skipped silently.
*/
export function useNewEntries<T>(list: readonly T[] | null | undefined, key: (t: T) => string | number, onNew: (fresh: T[]) => void, max = 12): void {
const seen = useRef<Set<string | number> | null>(null);
const cb = useRef(onNew);
cb.current = onNew;
useLayoutEffect(() => {
const items = list ?? [];
const keys = items.map(key);
const prev = seen.current;
seen.current = new Set(keys);
if (!prev) return;
const fresh = items.filter((_, i) => !prev.has(keys[i]!));
if (fresh.length && fresh.length <= max) cb.current(fresh);
});
}
/** Calls `onChange(now, before)` in a layout effect when `value` (compared with `Object.is`) changes; not on the first render. */
export function useChange<T>(value: T, onChange: (now: T, before: T) => void): void {
const prev = useRef<{ v: T } | null>(null);
const cb = useRef(onChange);
cb.current = onChange;
useLayoutEffect(() => {
const before = prev.current;
prev.current = { v: value };
if (before && !Object.is(before.v, value)) cb.current(value, before.v);
}, [value]);
}
export type BannerTone = 'gold' | 'red' | 'blue' | 'green' | 'dark';
/**
* Big short banner over the screen (우노!, 뻑!, 고!, 혁명!, 뱅! …). `show` replaces the current one.
* Render `node` once inside the board.
*/
export function useBanner(): [ReactNode, (text: string, tone?: BannerTone, sub?: string) => void] {
const [b, setB] = useState<{ id: number; text: string; tone: BannerTone; sub?: string } | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const show = (text: string, tone: BannerTone = 'gold', sub?: string) => {
ensureCss();
if (timer.current) clearTimeout(timer.current);
setB((old) => ({ id: (old?.id ?? 0) + 1, text, tone, sub }));
timer.current = setTimeout(() => setB(null), 1700);
};
useLayoutEffect(() => () => {
if (timer.current) clearTimeout(timer.current);
}, []);
const node = b ? (
<div className="fx-banner-wrap" aria-hidden>
<div key={b.id} className={`fx-banner anim-banner fx-${b.tone}`}>
{b.text}
{b.sub && <small>{b.sub}</small>}
</div>
</div>
) : null;
return [node, show];
}
// ---------------------------------------------------------------- CSS
const FX_CSS = `
.fx-ghost { position: fixed; z-index: 60; pointer-events: none; box-sizing: border-box; will-change: transform, opacity; }
.fx-ghost-card { width: 40px; height: 56px; border-radius: 6px; background: #1e3a8a; border: 2px solid #fff;
box-shadow: 0 3px 8px rgba(0,0,0,.35), inset 0 0 0 4px #1e3a8a, inset 0 0 0 6px #93c5fd; }
.fx-ghost-hwatu { width: 34px; height: 54px; border-radius: 4px; background: #b91c1c; border: 2px solid #1f2937;
box-shadow: 0 3px 8px rgba(0,0,0,.35), inset 0 0 0 3px #7f1d1d; }
.fx-ghost-chip, .fx-ghost-coin { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
font: 800 10px/1 system-ui, sans-serif; color: #fff; white-space: nowrap; }
.fx-ghost-chip { background: #dc2626; border: 3px dashed #fff; box-shadow: 0 2px 5px rgba(0,0,0,.4), 0 0 0 1px #7f1d1d; }
.fx-ghost-coin { background: #f59e0b; border: 2px solid #fde68a; box-shadow: 0 2px 5px rgba(0,0,0,.4), 0 0 0 1px #92400e; color: #451a03; }
.fx-banner-wrap { position: fixed; inset: 0; z-index: 70; display: flex; align-items: center; justify-content: center; pointer-events: none; }
.fx-banner { pointer-events: none; font-size: clamp(2.2rem, 9vw, 4.6rem); font-weight: 900; letter-spacing: .02em; line-height: 1.05; text-align: center;
padding: .18em .6em; border-radius: 22px; color: #fff; border: 5px solid #fff; box-shadow: 0 10px 30px rgba(0,0,0,.4);
text-shadow: 0 3px 0 rgba(0,0,0,.3); display: flex; flex-direction: column; align-items: center; max-width: 92vw; }
.fx-banner small { font-size: .32em; font-weight: 800; text-shadow: none; opacity: .95; margin-top: .2em; }
.fx-gold { background: linear-gradient(180deg, #f59e0b, #d97706); }
.fx-red { background: linear-gradient(180deg, #ef4444, #b91c1c); }
.fx-blue { background: linear-gradient(180deg, #3b82f6, #1d4ed8); }
.fx-green { background: linear-gradient(180deg, #22c55e, #15803d); }
.fx-dark { background: linear-gradient(180deg, #374151, #111827); }
`;
let cssDone = false;
function ensureCss(): void {
if (cssDone || typeof document === 'undefined') return;
cssDone = true;
const s = document.createElement('style');
s.dataset.fx = 'card-fx';
s.textContent = FX_CSS;
document.head.appendChild(s);
}

View File

@@ -956,7 +956,7 @@ function statusText(v: CockroachView, me: string | null, players: Record<string,
// ---------------------------------------------------------------- options
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
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]) => (
@@ -986,7 +986,7 @@ function Options({ value: o, onChange }: OptionsProps<CockroachOptions>) {
<Seg label="같은 벌레 몇 장이면 패배" value={o.loseCount} options={[['auto', '자동(2명 5장, 3~6명 4장)'], [3, '3장(짧게)'], [4, '4장'], [5, '5장']]} onChange={(loseCount) => set({ loseCount })} />
</Field>
<Field label="건네기·판정 제한 시간">
<Seg label="건네기·판정 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Seg label="건네기·판정 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
<Field label="이번 라운드 주장 기록">
<Seg label="이번 라운드 주장 기록" value={o.claimHistory} options={[[true, '보이기'], [false, '숨기기']]} onChange={(claimHistory) => set({ claimHistory })} />
@@ -1015,7 +1015,7 @@ function optionsSummary(o: CockroachOptions, players?: number): string {
const lose = o.loseCount === 'auto' ? (players ? `${players === 2 ? 5 : 4}장` : '자동(2명 5장, 그 외 4장)') : `${o.loseCount}장`;
return [
`같은 벌레 ${lose}이면 패배`,
`제한 ${o.turnSeconds}초`,
o.turnSeconds === null ? '시간 무제한' : `제한 ${o.turnSeconds}초`,
...(o.claimHistory ? [] : ['주장 기록 숨김']),
...(o.quickChat ? [] : ['빠른 말 끔']),
...(o.eightKindsRule ? ['8종 모으면 패배'] : []),
@@ -1058,7 +1058,7 @@ function Rules({ options }: { options?: CockroachOptions }) {
<p>카드를 앞마당에 놓은 사람이 다음 라운드를 시작해요. 그때 손에 카드가 한 장도 없으면 바로 져요.</p>
{o?.eightKindsRule && <p>하우스 룰: 앞마당에 8종을 모두 한 장 이상 모아도 져요.</p>}
<p className="muted">
시간 안에 고르지 않으면 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
것으로 끝나요.
</p>
</div>

View File

@@ -1,10 +1,11 @@
/** 달무티 화면 (docs/games/dalmuti.md §9). */
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
import type { Choice, DCard, DalmutiOptions, DalmutiView, LogEntry, PlayView, SeatView, Title } from '@bg/games/dalmuti';
import type { PublicUser } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { TurnTimer } from '../../components/TurnTimer';
import { haptic, sounds } from '../../lib/feedback';
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries } from '../card-fx';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
@@ -51,6 +52,52 @@ const rankText = (rank: number) => (rank === JESTER ? '광대(13)' : String(rank
const setText = (p: { rank: number; count: number }) => `${rankText(p.rank)} × ${p.count}장`;
const facesText = (cards: number[]) => cards.map((n) => (n === JESTER ? '광대' : String(n))).join(', ');
/** 달무티 sounds on top of the shared palette (synthesized, no files). */
const dmSfx = {
/** A set lands on the pile: one slap per card. */
set: (n: number) => {
for (let i = 0; i < Math.min(n, 6); i++) noise(60, 0.15, i * 55, 'bandpass', 1500 + i * 120, 0.9);
tone(220, 70, 'sine', 0.09, Math.min(n - 1, 5) * 55);
},
/** Soft double knock on the table (pass). */
knock: () => {
tone(190, 70, 'sine', 0.14);
noise(35, 0.06, 0, 'lowpass', 700);
tone(165, 70, 'sine', 0.12, 120);
noise(35, 0.05, 120, 'lowpass', 700);
},
/** 혁명 / 대혁명: drum roll, falling growl, then a big chord (higher and longer for 대혁명). */
revolution: (great: boolean) => {
for (let i = 0; i < 7; i++) noise(90, 0.1 + i * 0.012, i * 55, 'lowpass', 320);
tone(130, 520, 'sawtooth', 0.06, 0, { slideTo: great ? 55 : 80 });
[392, 494, 587, 784].forEach((f, i) => tone(f, 420, 'square', 0.045, 420 + i * 35));
if (great) [523, 659, 784, 1046].forEach((f, i) => tone(f, 520, 'square', 0.045, 820 + i * 35));
},
/** Tax card slides over (with a little coin ring). */
tax: () => {
noise(140, 0.1, 0, 'bandpass', 1200, 0.6);
tone(660, 80, 'triangle', 0.07, 120);
tone(990, 130, 'triangle', 0.06, 190);
},
/** Card given back: slide + a lower note. */
give: () => {
noise(140, 0.1, 0, 'bandpass', 1000, 0.6);
tone(520, 110, 'triangle', 0.06, 120);
},
};
/** Where my last played set was (its button may be gone once the view arrives), so the pile cards fly from there. */
let myPlayRect: DOMRect | null = null;
const rememberPlay = (rank: number) => {
myPlayRect = document.querySelector(`.dm-group[data-n="${cssEsc(String(rank))}"]`)?.getBoundingClientRect() ?? null;
};
/** Brief dim of a seat (pass). */
function dim(el: Element | null): void {
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
(el as HTMLElement).animate([{ opacity: 1 }, { opacity: 0.4, offset: 0.35 }, { opacity: 1 }], { duration: 650, easing: 'ease-out' });
}
const CSS = `
.dm { width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 10px; align-self: center; }
.dm-tip { display: flex; align-items: center; gap: 8px; background: var(--primary-soft); color: var(--text); border-radius: 12px; padding: 6px 6px 6px 12px; font-weight: 700; font-size: .95rem; }
@@ -60,6 +107,7 @@ const CSS = `
.dm-seat { position: relative; flex: 0 1 124px; min-width: 104px; 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: 2px; font-size: .88rem; animation: dm-in .35s ease both; }
.dm-seat.turn { border-color: var(--focus); }
.dm-seat.anim-glow { animation: anim-glow 1.4s ease-in-out infinite; }
.dm-seat.me { background: var(--primary-soft); }
.dm-seat.out { opacity: .7; }
.dm-seat .nm { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
@@ -80,7 +128,6 @@ const CSS = `
.dm-prev .dm-card .nm { display: none; }
.dm-set { display: flex; }
.dm-set > .dm-card + .dm-card { margin-left: calc(var(--w) * -0.55); }
.dm-set.top { animation: dm-fly .3s ease-out; }
.dm-card { --w: 60px; position: relative; flex: none; width: var(--w); height: calc(var(--w) * 1.4); border-radius: calc(var(--w) * .13); background: #fffdf7; color: #1f2937;
border: 2px solid var(--c, #444); box-shadow: 0 2px 4px rgba(0,0,0,.28); display: flex; flex-direction: column; align-items: center; overflow: hidden; font-family: inherit; }
.dm-card .band { width: 100%; background: var(--c, #444); color: #fff; font-weight: 900; font-size: calc(var(--w) * .2); line-height: 1.35; text-align: left; padding-left: 4px; }
@@ -129,10 +176,9 @@ const CSS = `
.dm-flip { animation: dm-flip .7s ease both; }
@keyframes dm-in { from { transform: translateY(-8px); opacity: 0; } to { transform: none; opacity: 1; } }
@keyframes dm-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } }
@keyframes dm-fly { from { transform: translateY(40px) scale(.85); opacity: .2; } to { transform: none; opacity: 1; } }
@keyframes dm-flip { from { transform: rotateY(180deg); } to { transform: none; } }
@media (prefers-reduced-motion: reduce) {
.dm *, .dm-seat, .dm-set.top, .dm-rev, .dm-bubble, .dm-draw, .dm-flip { animation: none !important; transition: none !important; }
.dm *, .dm-seat, .dm-rev, .dm-bubble, .dm-draw, .dm-flip { animation: none !important; transition: none !important; }
}
@media (max-width: 719px) {
.dm { gap: 8px; }
@@ -195,7 +241,8 @@ function Seats({ v, players, me, deadline }: { v: DalmutiView; players: Record<s
return (
<li
key={s.id}
className={`dm-seat${s.isTurn && v.phase === 'playing' ? ' turn' : ''}${s.id === me ? ' me' : ''}${s.place ? ' out' : ''}`}
className={`dm-seat${s.isTurn && v.phase === 'playing' ? ' turn anim-glow' : ''}${s.id === me ? ' me' : ''}${s.place ? ' out' : ''}`}
data-fx-seat={s.id}
style={{ animationDelay: `${i * 40}ms` }}
aria-label={seatLabel(s, v, players, me)}
>
@@ -251,7 +298,7 @@ function TableArea({ v, players, me }: { v: DalmutiView; players: Record<string,
const leaderName = t.leader === me ? '내가' : `${nick(players, t.leader)}님이`;
const curName = v.current === me ? '내' : `${nick(players, v.current ?? '')}님`;
return (
<div className="dm-table" role="region" aria-label="바닥">
<div className="dm-table" data-fx="dm-center" role="region" aria-label="바닥">
{top ? (
<>
<div className="dm-now" aria-live="polite">
@@ -339,6 +386,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
setSel(null);
return;
}
sfx.select();
if (top) setSel({ rank: g.n, count: top.count, mix: ch.needsJester });
else setSel({ rank: g.n, count: ch.have, mix: false });
};
@@ -360,6 +408,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
};
const send = () => {
if (!ids || !legal) return;
rememberPlay(sel!.rank);
act({ type: 'play', cardIds: ids });
setSel(null);
};
@@ -374,7 +423,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
</strong>
{mine && <span className="small muted">{top ? `${setText(top)}보다 낮은 숫자를 골라요` : '낼 숫자를 골라요'}</span>}
</div>
<div className="dm-hand" role="group" aria-label="내 카드(숫자별). 좌우 방향키로 고르고 Enter로 선택해요" onKeyDown={(e) => onArrowKeys(e, 'button.dm-group')}>
<div className="dm-hand" data-fx="dm-hand" role="group" aria-label="내 카드(숫자별). 좌우 방향키로 고르고 Enter로 선택해요" onKeyDown={(e) => onArrowKeys(e, 'button.dm-group')}>
{groups.map((g) => {
const c = choice(g.n);
const picked = sel?.rank === g.n;
@@ -508,7 +557,7 @@ function RevolutionPanel({ v, players, me, act, pending }: { v: DalmutiView; pla
const my = v.my;
const done = v.seats.filter((s) => s.confirmed).length;
return (
<div className="dm-panel">
<div className="dm-panel" data-fx="dm-center">
<h3>
{v.round}라운드 준비 · 손패 확인 ({done}/{v.seats.length})
</h3>
@@ -553,11 +602,12 @@ function TaxPanel({ v, players, me, act, pending }: { v: DalmutiView; players: R
const subject = (id: string) => (id === me ? '내가' : `${nick(players, id)}님이`);
const toggle = (id: string) => {
if (!owe) return;
sfx.select();
if (picked.includes(id)) setPicked(picked.filter((x) => x !== id));
else setPicked(picked.length >= owe.count ? [...picked.slice(1), id] : [...picked, id]);
};
return (
<div className={`dm-panel${owe ? ' hot' : ''}`}>
<div className={`dm-panel${owe ? ' hot' : ''}`} data-fx="dm-center">
<h3>세금 카드 교환</h3>
<RoundRecap v={v} players={players} me={me} />
<ul style={{ margin: 0, paddingLeft: 20 }} aria-label="세금 내역">
@@ -685,6 +735,8 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
const mine = isMyTurn(v, me);
const prevMine = useRef(false);
const lastLog = v.log[v.log.length - 1];
const [banner, showBanner] = useBanner();
useDalmutiFx(v, me, players, showBanner);
useEffect(() => {
if (mine && !prevMine.current) {
haptic(40);
@@ -715,10 +767,101 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
<p className="sr-only" aria-live="polite">
{announce}
</p>
{banner}
</div>
);
}
const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : 'from' in e ? e.from : ''}`;
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`);
// A new round (or the very first deal): cards go from the middle to everyone.
const deal = (delay = 0) => {
const c = fxEl('dm-center');
later(delay, sfx.shuffle);
later(delay + 300, () => sfx.deal(6, 60));
document.querySelectorAll('.dm-hand .dm-group, .dm-hand .dm-one').forEach((el, i) => flyFrom(el, c, { delay: delay + 280 + i * 45, rotate: 10 }));
for (const s of v.seats) if (s.id !== me) flyGhost(c, seatEl(s.id), { count: 3, gap: 90, delay: delay + 280 });
};
useNewEntries(v.log, logKey, (fresh) => {
const lastPlay = [...fresh].reverse().find((e) => e.t === 'play');
let t = 0;
for (const e of fresh) {
const at = t;
switch (e.t) {
case 'play': {
if (e === lastPlay) {
const from = e.p === me ? (myPlayRect ?? fxEl('dm-hand')) : seatEl(e.p);
document.querySelectorAll('.dm-set.top .dm-card').forEach((el, i) => flyFrom(el, from, { delay: at + i * 60, ms: 340, rotate: -12 }));
}
if (e.p === me) myPlayRect = null;
later(at, () => dmSfx.set(e.count));
t += 150;
break;
}
case 'pass':
later(at, dmSfx.knock);
dim(seatEl(e.p));
t += 120;
break;
case 'trick':
// Everyone passed: the pile is swept to whoever leads next.
flyGhost(fxEl('dm-center'), seatEl(e.p), { count: 3, gap: 60, delay: at, ms: 420 });
later(at, sfx.whoosh);
later(at + 380, () => bump(seatEl(e.p)));
t += 200;
break;
case 'out':
showBanner(`${e.place}등!`, e.place === 1 ? 'gold' : 'green', e.p === me ? '손패를 다 냈어요' : `${nick(players, e.p)}님`);
later(at + 80, e.place === 1 ? sfx.fanfare : sfx.good);
bump(seatEl(e.p));
t += 250;
break;
case 'revolution': {
const great = e.kind === 'great';
showBanner(great ? '대혁명!' : '혁명!', great ? 'dark' : 'red', great ? `${who(e.p)} · 신분이 뒤집혀요` : `${who(e.p)} · 세금 없음`);
later(at, () => dmSfx.revolution(great));
t += 300;
break;
}
case 'tax':
case 'return':
flyGhost(seatEl(e.from), seatEl(e.to), { count: e.n, gap: 90, delay: at, ms: 520 });
later(at, e.t === 'tax' ? dmSfx.tax : dmSfx.give);
t += 350;
break;
case 'round':
// The next round's cards are dealt (not after the last round).
if (v.phase !== 'finished') {
deal(at + 500);
t += 1300;
}
break;
case 'timeout':
later(at, sfx.tick);
break;
default:
break;
}
}
});
const started = useRef(false);
useLayoutEffect(() => {
if (started.current) return;
started.current = true;
// Mounted right at the start of the game (nobody has done anything yet): show the deal once.
const fresh =
v.round === 1 &&
(v.phase === 'revolutionCheck'
? v.log.length === 0 && !v.seats.some((s) => s.confirmed)
: v.phase === 'taxReturn' && !v.options.revolution && v.log.every((e) => e.t === 'tax') && v.taxPending.every((p) => !p.done));
if (fresh) deal();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
}
// ---------------------------------------------------------------- side
function rulesLine(o: DalmutiOptions): string {
@@ -729,7 +872,7 @@ function rulesLine(o: DalmutiOptions): string {
o.jesterTaxable ? '세금에 광대 포함' : '세금에 광대 빼기',
o.passLocksOut ? '패스하면 트릭에서 빠짐' : '패스해도 다시 낼 수 있음',
o.removeHighCards ? '9~12 빼기' : '',
`${o.turnSeconds}초`,
o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`,
]
.filter(Boolean)
.join(' · ');
@@ -853,7 +996,7 @@ function statusText(v: DalmutiView, me: string | null, players: Record<string, P
// ---------------------------------------------------------------- options
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
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]) => (
@@ -895,7 +1038,7 @@ function Options({ value: o, onChange }: OptionsProps<DalmutiOptions>) {
<Seg label="혁명 규칙" value={o.revolution} options={onOff} onChange={(revolution) => set({ revolution })} />
</Field>
<Field label="한 턴 제한 시간">
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [45, '45초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [45, '45초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
@@ -926,7 +1069,7 @@ function optionsSummary(o: DalmutiOptions): string {
if (o.jesterTaxable) parts.push('세금에 광대');
if (o.passLocksOut) parts.push('패스하면 빠짐');
if (o.removeHighCards) parts.push('9~12 빼기');
parts.push(`${o.turnSeconds}초`);
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
return parts.join(' · ');
}
@@ -990,7 +1133,10 @@ function Rules({ options }: { options?: DalmutiOptions }) {
라운드에서 1등은 (사람 수 − 1)점, 마지막 순위는 0점을 받아요. {o?.scoring === 'last-round' ? '이 방은 마지막 라운드 순위가 최종 순위예요.' : '총점이 높은 사람이 이기고, 같으면 마지막 라운드 순위로 정해요.'}{' '}
점수는 이 방 안에서만 쓰는 표시용이에요.
</p>
<p>시간 안에 고르지 않으면 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는 패스해요.</p>
<p>
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는
패스해요.
</p>
<CardTable removeHigh={o?.removeHighCards} />
</div>
);

View File

@@ -18,6 +18,9 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
};
const seat = me ? v.seats.find((s) => s.id === me) : undefined;
const seatOf = (id: string | null) => v.seats.find((s) => s.id === id);
/** What happens when the decision clock runs out (무제한: only after a dropped connection). */
const late = (what: string) =>
v.rules.decisionSeconds === null ? `시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 ${what}` : `시간이 지나면 ${what}`;
if (v.phase === 'finished') {
const lines = [`게임이 끝났어요. ${v.result?.summary ?? ''}`.trim()];
@@ -57,7 +60,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
const gain = n * v.rules.gwangPrice * (v.rules.gwangPayer === 'nonDealerPlayers' ? 2 : 3);
lines.push('광팔기 차례예요. 4~5명이면 이번 판은 3명만 쳐요(선은 꼭 쳐요).');
lines.push(
`[치기]를 누르면 이번 판에 참가해요. ${n > 0 ? `[죽기 · 광 ${n}장 팔기]를 누르면 ${gain}점을 받고 이번 판은 쉬어요.` : '[죽기]를 누르면 팔 패가 없어 그냥 쉬어요.'} 시간이 지나면 죽기로 정해져요.`,
`[치기]를 누르면 이번 판에 참가해요. ${n > 0 ? `[죽기 · 광 ${n}장 팔기]를 누르면 ${gain}점을 받고 이번 판은 쉬어요.` : '[죽기]를 누르면 팔 패가 없어 그냥 쉬어요.'} ${late('죽기로 정해져요.')}`,
);
} else if (seat) {
const mine = s?.decisions.find((d) => d.player === me);
@@ -76,7 +79,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
const each = v.rules.chongtongPoints * v.nagariMult;
lines.push(`총통이에요! 손에 같은 월 4장${months.length ? `(${months.map((m) => `${m}월`).join(', ')})` : ''}이 있어요.`);
lines.push(`[총통 선언]을 누르면 이번 판을 바로 이기고 상대마다 ${each}점, 모두 ${each * others}점을 받아요. [그냥 치기]를 누르면 판을 계속하고, 그 월로 흔들기나 폭탄을 할 수 있어요.`);
lines.push('시간이 지나면 총통 선언으로 정해져요.');
lines.push(late('총통 선언으로 정해져요.'));
} else {
lines.push(`${nm(who)}이 총통(손에 같은 월 4장)을 선언할지 고르는 중이에요. 선언하면 ${nm(who)}이 이번 판을 바로 이겨요.`);
}
@@ -122,7 +125,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
const who = pf?.player ?? v.turn;
if (seat && who === me && pf) {
lines.push(`뒤집은 ${pf.flipped.name}과(와) 같은 월 패가 바닥에 2장(${pf.options.map((c) => c.name).join(', ')}) 있어요. 창에서 가져올 패를 눌러 골라요.`);
lines.push('시간이 지나면 더 좋은 패를 저절로 가져와요.');
lines.push(late('더 좋은 패를 저절로 가져와요.'));
} else {
lines.push(`${nm(who)}이 뒤집은 패${pf ? `(${pf.flipped.name})` : ''}로 가져올 바닥 패를 고르는 중이에요.`);
}
@@ -139,7 +142,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
lines.push(`${g.score}점이 났어요! [고] 또는 [스톱]을 골라요.${g.goCount > 0 ? ` 지금까지 ${g.goCount}고 했어요.` : ''}`);
lines.push(`[스톱]: 판을 끝내고 ${g.stopNow.total}점을 받아요${notes}.${baks.length ? ` ${baks.join(', ')}이 붙어요.` : ''}`);
lines.push(`[고]: ${g.goNext.goCount}고로 판을 계속해요. +${g.goNext.plus}점${g.goNext.factor > 1 ? `, 점수 x${g.goNext.factor}` : ''}.${risk}`);
lines.push('시간이 지나면 스톱으로 정해져요.');
lines.push(late('스톱으로 정해져요.'));
} else {
lines.push(`${nm(who)}이 ${g ? `${g.score}점을 내서 ` : ''}고 또는 스톱을 고르는 중이에요. 스톱하면 이번 판이 끝나요.`);
const mine = g?.stopNow.perLoser.find((x) => x.player === me);
@@ -152,7 +155,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
const who = g?.player ?? v.turn;
if (seat && who === me && g) {
lines.push('판이 끝나기 전에 내가 가진 9월 열끗(국진)을 어떻게 셀지 골라요.');
lines.push(`[열끗으로]: 내 점수 ${g.yeolScore}점. [쌍피로](피 2장 값): 내 점수 ${g.piScore}점. 시간이 지나면 나에게 유리한 쪽으로 정해져요.`);
lines.push(`[열끗으로]: 내 점수 ${g.yeolScore}점. [쌍피로](피 2장 값): 내 점수 ${g.piScore}점. ${late('나에게 유리한 쪽으로 정해져요.')}`);
} else {
lines.push(`스톱이 나왔어요. ${nm(who)}이 9월 열끗(국진)을 열끗으로 셀지 쌍피로 셀지 정하는 중이에요. 정하면 이번 판 점수를 계산해요.`);
}

View File

@@ -51,7 +51,7 @@ function totalMsOf(v: GostopView): number {
if (v.phase === 'roundResult') return 10_000;
const who = v.step === 'sell' ? v.sell?.current : v.turn;
if (who && v.seats.find((s) => s.id === who)?.autoPilot) return 2_000;
return (v.step === 'play' ? v.rules.turnSeconds : v.rules.decisionSeconds) * 1000;
return ((v.step === 'play' ? v.rules.turnSeconds : v.rules.decisionSeconds) ?? 0) * 1000;
}
/** Whoever the table is waiting for (null on result screens). */
@@ -672,7 +672,7 @@ function Decisions({ view: v, me, players, act, pending }: BoardProps<GostopView
return (
<Sheet onClose={nop} label="국진 정하기">
<h2>9월 열끗(국진)을 어떻게 쓸까요?</h2>
<p className="muted">열끗 1장 또는 쌍피(피 2장 값)로 셀 수 있어요. 시간이 지나면 나에게 유리한 쪽으로 정해져요.</p>
<p className="muted">열끗 1장 또는 쌍피(피 2장 값)로 셀 수 있어요.{v.rules.decisionSeconds === null ? '' : ' 시간이 지나면 나에게 유리한 쪽으로 정해져요.'}</p>
<div className="gs-big">
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'gukjin', as: 'yeol' })}>
열끗으로<small>내 점수 {g.yeolScore}점</small>
@@ -1033,12 +1033,14 @@ function Rules({ options }: { options?: GostopOptions }) {
</div>
<strong>족보</strong>
<JokboTable rules={{ ogwangPoints: o?.ogwangPoints ?? 15, biGwangThree: o?.biGwangThree ?? 2 }} />
<p className="small muted">시간 안에 내지 않으면 바닥과 맞는 패 중 가장 좋은 패를 대신 내고, 고·스톱은 스톱으로 정해요. 두 번 연속 시간을 넘기면 2초 만에 자동으로 진행돼요.</p>
<p className="small muted">
{o?.turnSeconds === null ? '이 방은 차례 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 내지 않으면'} 바닥과 맞는 패 중 가장 좋은 패를 대신 내고, 고·스톱은 스톱으로 정해요. 두 번 연속 시간을 넘기면 2초 만에 자동으로 진행돼요.
</p>
</div>
);
}
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
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]) => (
@@ -1080,7 +1082,7 @@ function Options({ value: o, onChange }: OptionsProps<GostopOptions>) {
<Seg label="고·스톱 기준 점수" value={o.winScore} options={[['auto', '자동(맞고 7·고스톱 3)'], [3, '3점'], [5, '5점'], [7, '7점']]} onChange={(winScore) => set({ winScore })} />
</Field>
<Field label="한 턴 제한 시간">
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[5, '5초'], [10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[5, '5초'], [10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
@@ -1091,7 +1093,7 @@ function Options({ value: o, onChange }: OptionsProps<GostopOptions>) {
<Seg label="보너스패" value={o.bonusCards} options={[['auto', '자동(맞고만)'], ['none', '없음'], ['2+1', '2피 2장 + 3피 1장'], ['3+1', '2피 3장 + 3피 1장']]} onChange={(bonusCards) => set({ bonusCards })} />
</Field>
<Field label="고·스톱·선택 제한 시간">
<Seg label="고·스톱·선택 제한 시간" value={o.decisionSeconds} options={[[5, '5초'], [10, '10초'], [15, '15초'], [20, '20초'], [30, '30초']]} onChange={(decisionSeconds) => set({ decisionSeconds })} />
<Seg label="고·스톱·선택 제한 시간" value={o.decisionSeconds} options={[[5, '5초'], [10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [null, '무제한']]} onChange={(decisionSeconds) => set({ decisionSeconds })} />
</Field>
<Field label="피박 기준(진 사람 피 값)">
<Seg label="피박 기준" value={o.piBakLimit} options={[['auto', '자동(맞고 7·고스톱 5)'], [5, '5 이하'], [6, '6 이하'], [7, '7 이하']]} onChange={(piBakLimit) => set({ piBakLimit })} />
@@ -1155,7 +1157,7 @@ function optionsSummary(o: GostopOptions): string {
return [
`${o.rounds}판`,
o.winScore === 'auto' ? '맞고 7점·고스톱 3점' : `${o.winScore}점 나기`,
`${o.turnSeconds}초`,
o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`,
o.bonusCards === 'none' ? '보너스패 없음' : o.bonusCards === 'auto' ? '' : `보너스 ${o.bonusCards}`,
o.gwangPalgi ? '' : '광팔기 없음',
]

View File

@@ -686,7 +686,7 @@ function statusText(v: NinetyNineView, me: string | null, players: Record<string
// ---------------------------------------------------------------- options
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
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]) => (
@@ -735,7 +735,7 @@ function Options({ value: o, onChange }: OptionsProps<NNOptions>) {
/>
</Field>
<Field label="한 턴 제한 시간">
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
{kr && (
<button type="button" className="btn btn-secondary" onClick={() => set({ jokerRange: '0-99', handSize: 'auto' })}>
@@ -790,7 +790,7 @@ function optionsSummary(o: NNOptions): string {
if (o.mode === 'kr-product' && o.startTotal === 'zero') parts.push('0부터 시작');
if (!o.refill) parts.push('보충 없음');
if (o.mode === 'kr-product' && o.jokerRange === '0-99') parts.push('조커 0~99');
parts.push(`${o.turnSeconds}초`);
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
return parts.join(' · ');
}
@@ -872,7 +872,7 @@ function Rules({ options }: { options?: NNOptions }) {
</p>
<SpecialTable o={o} />
<p className="small muted">
시간 안에 내지 않으면 합계가 가장 작아지는 카드를 자동으로 내요. 어린이와 할 때는 조커 0~99를 추천해요. 목숨(하트)은 이 판에서만 쓰는 표시예요.
{o.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 내지 않으면'} 합계가 가장 작아지는 카드를 자동으로 내요. 어린이와 할 때는 조커 0~99를 추천해요. 목숨(하트)은 이 판에서만 쓰는 표시예요.
</p>
</div>
);

View File

@@ -1,13 +1,14 @@
/** 도둑잡기 화면 (docs/games/old-maid.md §9). Cards are the shared trump card SVGs. */
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
import { 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 { PlayingCard, cardAria } from '../../components/cards/PlayingCard';
import { haptic, sounds } from '../../lib/feedback';
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, seatEl, useBanner, useChange, useNewEntries } from '../card-fx';
import { helpNow } from './help';
import { quickStart } from './quick';
@@ -15,6 +16,35 @@ import { quickStart } from './quick';
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;
const handCardEl = (c: string) => document.querySelector(`.om-hand [data-card="${cssEsc(c)}"]`);
const pairKey = (p: [string, string]) => `${p[0]}-${p[1]}`;
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)}님`);
@@ -122,7 +152,7 @@ button.om-back:hover:not(:disabled) { transform: translateY(-5px); }
function Card({ card, className }: { card: string | null; className?: string }) {
return (
<span className={`om-card${className ? ` ${className}` : ''}`} aria-hidden>
<span className={`om-card${className ? ` ${className}` : ''}`} data-card={card ?? undefined} aria-hidden>
<span className="om-face">
<PlayingCard card={card} size="lg" style={{ width: '100%', height: '100%', filter: 'none' }} />
</span>
@@ -158,9 +188,9 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaid
const u = userOf(players, id);
const st = v.status[id];
const thief = v.final?.thief === id;
const cls = ['om-seat', v.turn === id ? 'turn' : '', v.target === id ? 'target' : '', st !== 'playing' && !thief ? 'done' : '', thief ? 'thief' : ''].filter(Boolean).join(' ');
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} aria-label={seatLabel(v, id, me, players)}>
<section className={cls} data-fx-seat={id} aria-label={seatLabel(v, id, me, players)}>
{bubble && (
<span className="om-bubble" aria-hidden>
{bubble}
@@ -204,13 +234,17 @@ function Fan({ v, me, players, act, pending, tapConfirm, shake }: { v: OldMaidVi
useEffect(() => setSel(null), [v.turnNo, target, count, v.shuffles[target]]);
const draw = (index: number) => {
if (pending) return;
myDrawRect = document.querySelectorAll('.om-fan button.om-back')[index]?.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);
else {
setSel(i);
sfx.select();
}
};
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'Escape') {
@@ -291,10 +325,10 @@ 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" aria-label={`버린 짝 모두 ${total}쌍${pairs.length ? `, 최근: ${pairs.map((p) => `${cardName(p[0])}·${cardName(p[1])}`).join(', ')}` : ''}`} role="group">
<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>버린 짝 {total}쌍 / 26쌍</span>
{pairs.map((p, i) => (
<span key={i} className="pair" aria-hidden>
<span key={i} className="pair" data-pair={pairKey(p)} aria-hidden>
<Card card={p[0]} />
<Card card={p[1]} />
</span>
@@ -308,11 +342,11 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record<strin
if (v.phase === 'finished') {
const f = v.final!;
return (
<div className="om-table" role="group" aria-label="테이블">
<div className="om-table" role="group" aria-label="테이블" data-fx="om-table">
<strong className="om-title">게임이 끝났어요</strong>
{f.thief ? (
<>
<Card card={JOKER} />
<Card card={JOKER} className="om-thief-joker" />
<span style={{ textAlign: 'center', fontWeight: 800 }}>🃏 도둑: {who(players, f.thief, me)}</span>
</>
) : (
@@ -328,7 +362,7 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record<strin
const drawer = v.turn!;
const target = v.target;
return (
<div className="om-table" role="group" aria-label="테이블">
<div className="om-table" role="group" aria-label="테이블" data-fx="om-table">
<div className="om-title">
<span>{who(players, drawer, me)}</span>
<span className="arrow" aria-hidden>
@@ -355,9 +389,9 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record<strin
function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v: 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' : '', v.target === me ? 'target' : ''].filter(Boolean).join(' ');
const cls = ['om-me', v.turn === me ? 'turn anim-glow' : '', v.target === me ? 'target' : ''].filter(Boolean).join(' ');
return (
<section className={cls} aria-label="내 자리">
<section className={cls} data-fx-seat={me} aria-label="내 자리">
{bubble && (
<span className="om-bubble" aria-hidden>
{bubble}
@@ -382,7 +416,7 @@ function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v:
)}
</div>
{hand.length > 0 ? (
<div className={`om-hand${hand.length > 12 ? ' many' : ''}`} role="list" aria-label={`내 손패, 왼쪽부터: ${hand.map(cardAria).join(', ')}`}>
<div className={`om-hand${hand.length > 12 ? ' many' : ''}`} data-fx="om-hand" role="list" aria-label={`내 손패, 왼쪽부터: ${hand.map(cardAria).join(', ')}`}>
{hand.map((c) => (
<span key={c} role="listitem" aria-label={cardAria(c)} style={{ display: 'contents' }}>
<Card card={c} className={[c === JOKER ? 'joker' : '', c === fresh ? 'fresh' : ''].filter(Boolean).join(' ')} />
@@ -408,6 +442,8 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
const [shake, setShake] = 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);
useEffect(() => {
const p = prev.current;
@@ -470,10 +506,119 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
<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, ms) : f());
/** 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;
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;
if (newMine) flyFrom(newMine, myDrawRect ?? seatEl(e.from), { ms: 420, rotate: 12, delay: at });
else flyGhost(e.drawer === me && myDrawRect ? myDrawRect : spot(e.from), spot(e.drawer), { delay: at, ms: 420 });
if (e.drawer === me) myDrawRect = null;
later(at, () => {
if (e.auto) sfx.tick();
sfx.draw();
});
if (e.pair) {
pile([e.pair], spot(e.drawer), at + 300);
later(at + 330, omSfx.pair);
later(at + 330, () => bump(document.querySelector('.om-last .cards'), 'pop'));
t += 420;
} else t += 160;
break;
}
case 'out':
later(at, () => {
omSfx.out();
bump(seatEl(e.player), 'pop');
});
showBanner(`${e.place}등!`, 'green', e.player === me ? '손패를 다 털었어요' : `${nick(players, e.player)}님 다 털었어요`);
t += 150;
break;
case 'shuffle':
later(at, () => {
sfx.shuffle();
bump(e.player === me ? fxEl('om-hand') : 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);
}
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);
}
});
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;
showBanner('🃏 도둑!', 'dark', thief === me ? '내가 조커를 들고 있었어요' : `${nick(players, thief)}님`);
setTimeout(() => {
bump(seatEl(thief), 'shake');
bump(fxEl('om-table')?.querySelector('.om-thief-joker'), 'pop');
}, 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;
const table = fxEl('om-table');
sfx.shuffle();
setTimeout(() => sfx.deal(8, 60), 300);
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: v, me, players, deadline }: BoardProps<OldMaidView>) {
@@ -558,7 +703,7 @@ function statusText(v: OldMaidView, me: string | null, players: Record<string, P
// ---------------------------------------------------------------- options
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
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]) => (
@@ -591,6 +736,7 @@ function Options({ value: o, onChange }: OptionsProps<OldMaidOptions>) {
[20, '20초'],
[30, '30초'],
[60, '60초'],
[null, '무제한'],
]}
onChange={(turnSeconds) => onChange({ ...o, turnSeconds })}
/>
@@ -600,7 +746,7 @@ function Options({ value: o, onChange }: OptionsProps<OldMaidOptions>) {
}
function optionsSummary(o: OldMaidOptions): string {
return `트럼프 52장 + 조커 1장 · 제한 ${o.turnSeconds}초`;
return `트럼프 52장 + 조커 1장 · ${o.turnSeconds === null ? '시간 무제한' : `제한 ${o.turnSeconds}초`}`;
}
function Rules({ options }: { options?: OldMaidOptions }) {
@@ -631,7 +777,10 @@ function Rules({ options }: { options?: OldMaidOptions }) {
<strong>끝</strong>: 손패를 다 턴 사람은 빠지고, 먼저 턴 순서대로 1등, 2등…이에요. 짝이 다 버려지면 조커 한 장만 남고, 그걸 든 사람이 도둑이에요.
</p>
<p className="muted">
{options?.turnSeconds ?? 20}초 안에 고르지 않으면 무작위로 한 장을 뽑아요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 카드를 든 채 게임을 나가면 그 사람 카드는 섞어서 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고(짝이
{options?.turnSeconds === null
? '시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 무작위로 한 장을 대신 뽑아 주고, 그런 일이 세 번 연속이면 그 사람은 5초 안에 뽑아야 해요.'
: `${options?.turnSeconds ?? 20}초 안에 고르지 않으면 무작위로 한 장을 뽑아요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요.`}{' '}
카드를 든 채 게임을 나가면 그 사람 카드는 섞어서 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고(짝이
생기면 버려요), 나간 사람은 맨 아래 등수가 돼요. 둘만 남았을 때 한 사람이 나가면 도둑 없이 끝나요.
</p>
</div>

View File

@@ -1,12 +1,13 @@
/** 포커 화면 (docs/games/poker.md §9). Chips are room-only play points. */
import { useEffect, useRef, useState } from 'react';
import type { BetActionType, LegalBetView, PokerMode, PokerOptions, PokerView, SeatView, Side, ViewCard } from '@bg/games/poker';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import type { BetActionType, LegalBetView, LogEntry, PokerMode, PokerOptions, PokerView, SeatView, Side, ViewCard } from '@bg/games/poker';
import type { PublicUser } from '@bg/shared/lite';
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
import { TurnTimer } from '../../components/TurnTimer';
import { PlayingCard } from '../../components/cards/PlayingCard';
import { Chips, PlayChipNotice, formatChips } from '../../components/cards/Chips';
import { haptic, sounds } from '../../lib/feedback';
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useChange } from '../card-fx';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
@@ -119,7 +120,7 @@ function SeatCards({ seat, v, me }: { seat: SeatView; v: PokerView; me: string |
if (!cards.length) return null;
const best = new Set(sd?.best ?? []);
return (
<div style={{ display: 'flex', flexWrap: 'nowrap', justifyContent: 'center' }}>
<div style={{ display: 'flex', flexWrap: 'nowrap', justifyContent: 'center' }} data-fx="seat-cards">
{cards.map((x, i) => (
<PlayingCard
key={x.key}
@@ -148,8 +149,9 @@ function SeatBox({ seat, v, players, me, deadline, x, y }: { seat: SeatView; v:
if (seat.boss) marks.push(['보스', '#fb923c', '보스(먼저 베팅)']);
return (
<div
className={`pk-seat${waiting ? ' turn' : ''}${seat.id === me ? ' me' : ''}${won ? ' win' : ''}${out ? ' out' : ''}`}
className={`pk-seat${waiting ? ' turn anim-glow' : ''}${seat.id === me ? ' me' : ''}${won ? ' win' : ''}${out ? ' out' : ''}`}
style={{ '--x': `${x}%`, '--y': `${y}%` } as React.CSSProperties}
data-fx-seat={seat.id}
aria-label={`${u.nickname} ${formatChips(seat.stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`}
>
<div className="row" style={{ gap: 5, flexWrap: 'nowrap' }}>
@@ -195,15 +197,15 @@ function CenterInfo({ v, players }: { v: PokerView; players: Record<string, Publ
const limit = v.options.endCondition === 'hands' ? `/${v.options.handLimit}` : '';
const penalty = v.penalties.reduce((a, p) => a + p.amount, 0);
return (
<div className="pk-center">
<div className="pk-center" data-fx="poker-center">
{v.streetName && <div className="pk-badge" style={{ background: '#fde047', color: '#422006', fontSize: '0.95rem', padding: '2px 12px' }}>{v.streetName}</div>}
{isCommunity(v.mode) && (
<div className="pk-board" aria-label="공용 카드">
<div className="pk-board" aria-label="공용 카드" data-fx="poker-board">
{Array.from({ length: 5 }, (_, i) => (v.board[i] ? <PlayingCard key={v.board[i]} card={v.board[i]!} size="md" /> : <span key={`e${i}`} className="pk-slot" aria-hidden />))}
</div>
)}
<div style={{ fontSize: '0.95rem', opacity: 0.9 }}>모인 칩</div>
<div style={{ fontSize: '2.2rem', fontWeight: 900, fontVariantNumeric: 'tabular-nums' }} aria-live="polite">
<div style={{ fontSize: '2.2rem', fontWeight: 900, fontVariantNumeric: 'tabular-nums' }} aria-live="polite" data-fx="poker-pot">
{formatChips(v.pot)}
</div>
{v.pots.length > 1 && (
@@ -239,6 +241,8 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
const prevWaiting = useRef(false);
const mine = isMyTurn(v, me);
const showKey = `${v.handNo}-${v.handPhase}`;
const [banner, showBanner] = useBanner();
usePokerFx(v, me, players, showBanner);
useEffect(() => {
if (mine && !prevWaiting.current) {
@@ -270,10 +274,259 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
<p className="sr-only" aria-live="polite">
{announce}
</p>
{banner}
</div>
);
}
// ---------------------------------------------------------------- sounds + motion (2026-10-13)
/** 포커 sounds on top of the shared palette (synthesized, no files). */
const pokerSfx = {
/** 체크: two knuckle knocks on the felt. */
knock: (delay = 0) => {
for (const d of [0, 120]) {
tone(190, 60, 'sine', 0.22, delay + d, { slideTo: 120 });
noise(35, 0.1, delay + d, 'lowpass', 700);
}
},
/** 다이/폴드: cards slid away to the muck. */
fold: (delay = 0) => {
noise(220, 0.09, delay, 'bandpass', 800, 0.6);
tone(330, 160, 'triangle', 0.05, delay + 40, { slideTo: 200 });
},
/** 올인: a big push of chips with a low swell. */
allIn: (delay = 0) => {
for (let i = 0; i < 7; i++) sfx.chip(delay + i * 45);
tone(140, 360, 'sawtooth', 0.05, delay, { slideTo: 280 });
tone(70, 300, 'sine', 0.14, delay);
},
/** 하이·로우·스윙 선언 공개. */
declare: (delay = 0) => tone(660, 120, 'triangle', 0.1, delay, { slideTo: 990 }),
};
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
/** Card turned over in place (WAAPI so React's own style/transform stays). */
function flipIn(el: Element | null | undefined, delay = 0): void {
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
(el as HTMLElement).animate(
[
{ transform: 'perspective(600px) rotateY(90deg)' },
{ transform: 'perspective(600px) rotateY(-12deg)', offset: 0.6 },
{ transform: 'perspective(600px) rotateY(0deg)' },
],
{ duration: 420, delay, easing: 'ease', fill: 'backwards', composite: 'add' },
);
}
/** The card elements of a seat on the table (forehead, hole, choice, up — same order as SeatCards). */
const seatCardEls = (id: string): Element[] => [...(seatEl(id)?.querySelector('[data-fx="seat-cards"]')?.children ?? [])];
const myCardEl = (slot: string) => document.querySelector(`[data-fx="poker-mine"] [data-slot="${cssEsc(slot)}"]`);
const cardCount = (s: SeatView) => (s.forehead !== undefined ? 1 : 0) + s.hole.length + s.choiceCount + s.up.length;
/** My visible card slots (ids where I can see them) — a new id means a card just came to me. */
function mySlots(v: PokerView, me: string | null): string[] {
const seat = v.seats.find((s) => s.id === me);
if (!seat) return [];
const out: string[] = [];
seat.hole.forEach((c, i) => out.push(c ?? `h${i}`));
seat.up.forEach((c, i) => out.push(c ?? `u${i}`));
if (v.my.choice) out.push(...v.my.choice);
return out;
}
const sameEntry = (a: LogEntry, b: LogEntry) => a.hand === b.hand && a.by === b.by && a.msg === b.msg;
/** Entries appended to the (sliding, last-30) log since `prev`; null when the two don't line up (resync/jump). */
function newLogEntries(prev: readonly LogEntry[], next: readonly LogEntry[]): LogEntry[] | null {
for (let d = 0; d <= next.length; d++) {
const keep = next.length - d;
if (keep > prev.length) continue;
if (keep === 0) return prev.length === 0 ? [...next] : null;
let ok = true;
for (let i = 0; i < keep && ok; i++) ok = sameEntry(next[i]!, prev[prev.length - keep + i]!);
if (ok) return next.slice(keep);
}
return null;
}
const BET_RE = /^(삥|콜|따당|쿼터|하프|풀|레이즈|벳|올인) (\d+) 칩/;
const DRAW_RE = /(\d)장 바꿈|박스\((\d)장\)/;
/**
* Sounds + motion for every change of the table, mine or anyone else's (log entries and view diffs since the last
* view). Nothing on the first render (join, reload, replay jump).
*/
function usePokerFx(v: PokerView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const prev = useRef<PokerView | null>(null);
const chipN = (amount: number) => Math.max(1, Math.min(6, Math.round(Math.log2(1 + amount / Math.max(1, v.baseUnit)))));
const center = () => fxEl('poker-center');
const pot = () => fxEl('poker-pot');
/** New hand (or the very first one on mount): antes/blinds to the pot, then cards from the middle to everyone. */
const deal = (p: PokerView | null) => {
sfx.shuffle();
const inHand = v.seats.filter((s) => s.inHand && s.status !== 'left');
inHand.forEach((s, i) => {
if (s.handBet > 0) flyGhost(seatEl(s.id), pot(), { kind: 'chip', count: Math.min(3, chipN(s.handBet)), delay: i * 50 });
});
if (v.pot > 0) later(150, () => sfx.chips(3));
const per = Math.max(0, ...inHand.map(cardCount));
later(320, () => sfx.deal(Math.min(8, per * Math.max(1, inHand.length)), 55));
inHand.forEach((s, i) => {
if (s.id !== me) flyGhost(center(), seatEl(s.id), { count: Math.min(4, cardCount(s)), gap: 90, delay: 320 + i * 60 });
});
const known = new Set(p ? mySlots(p, me) : []);
mySlots(v, me)
.filter((k) => !known.has(k))
.forEach((k, i) => flyFrom(myCardEl(k), center(), { delay: 320 + i * 80, rotate: 10 }));
if (v.seats.find((s) => s.id === me)?.forehead !== undefined) flyFrom(myCardEl('f'), center(), { delay: 320, rotate: -10 });
};
useLayoutEffect(() => {
const p = prev.current;
prev.current = v;
if (!p || p === v) return;
const newHand = v.handNo !== p.handNo && v.handNo > 0;
let t = 0;
if (newHand) {
deal(p);
t = 600;
} else if (v.handNo > 0) {
// Cards dealt during the hand (7포커 streets, 인디언 2nd card …) and community cards.
let dealt = 0;
v.seats.forEach((s) => {
const before = p.seats.find((x) => x.id === s.id);
const k = before ? cardCount(s) - cardCount(before) : 0;
if (k > 0 && s.id !== me) flyGhost(center(), seatEl(s.id), { count: Math.min(4, k), gap: 90, delay: dealt * 70 });
if (k > 0) dealt += k;
});
const known = new Set(mySlots(p, me));
const mine = mySlots(v, me).filter((k) => !known.has(k));
mine.forEach((k, i) => flyFrom(myCardEl(k), center(), { delay: i * 80, rotate: 10 }));
if (dealt > 0) sfx.deal(Math.min(8, dealt), 60);
const boardEl = fxEl('poker-board');
for (let i = p.board.length; i < v.board.length; i++) {
const at = (i - p.board.length) * 140;
flipIn(boardEl?.children[i], at);
later(at, sfx.cardFlip);
}
if (v.board.length > p.board.length) t = (v.board.length - p.board.length) * 140;
// Showdown: hidden cards are turned over seat by seat.
if (v.showdown && !p.showdown) {
let n = 0;
for (const e of v.showdown) {
const s = v.seats.find((x) => x.id === e.id);
if (!s || s.id === me) continue;
const els = seatCardEls(s.id);
const off = s.forehead !== undefined ? 1 : 0;
const at = t + n * 160;
for (let i = 0; i < s.hole.length; i++) flipIn(els[off + i], at + i * 40);
later(at, sfx.cardFlip);
n++;
}
t += n * 160 + 100;
}
// 인디언: my own forehead card is shown at the end of the hand.
const myNow = v.seats.find((s) => s.id === me);
const myBefore = p.seats.find((s) => s.id === me);
if (myNow?.forehead && myBefore && !myBefore.forehead) {
flipIn(myCardEl('f'), t);
later(t, sfx.cardFlip);
t += 160;
}
}
const fresh = newLogEntries(p.log, v.log);
if (!fresh || fresh.length > 12) return;
for (const e of fresh) {
const at = t;
const by = e.by;
const msg = e.msg;
if (!by) {
if (msg.includes('오픈 카드를 공개')) {
v.seats.forEach((s, i) => {
if (!s.up.length) return;
const els = seatCardEls(s.id);
flipIn(els[els.length - 1], at + i * 70);
});
later(at, sfx.cardFlip);
later(at + 140, sfx.cardFlip);
t += 200;
} else if (msg.includes('섞')) {
later(at, sfx.shuffle);
} else if (msg.includes('기본 단위가')) {
later(at, sfx.good);
bump(pot());
}
continue;
}
const bet = BET_RE.exec(msg);
if (bet) {
const amount = Number(bet[2]);
const n = chipN(amount);
flyGhost(seatEl(by), pot(), { kind: 'chip', count: n, gap: 60, delay: at });
if (msg.includes('올인')) {
later(at, () => pokerSfx.allIn());
later(at, () => showBanner('올인!', 'red', by === me ? undefined : `${nick(players, by)}님`));
bump(seatEl(by), 'shake');
} else later(at, () => sfx.chips(Math.min(5, n + 1)));
t += 140;
} else if (msg === '체크') {
later(at, () => pokerSfx.knock());
t += 120;
} else if (msg === '다이' || msg === '폴드' || msg.includes('나가서 다이')) {
const s = v.seats.find((x) => x.id === by);
flyGhost(seatEl(by), center(), { count: Math.min(3, s ? Math.max(1, cardCount(s)) : 2), gap: 50, delay: at });
later(at, () => pokerSfx.fold());
t += 130;
} else if (DRAW_RE.test(msg)) {
const m = DRAW_RE.exec(msg)!;
const k = Number(m[1] ?? m[2]);
flyGhost(seatEl(by), center(), { count: k, gap: 60, delay: at });
if (by !== me) flyGhost(center(), seatEl(by), { count: k, gap: 70, delay: at + 300 });
later(at, () => sfx.cardDeal());
later(at + 300, () => sfx.draw(Math.min(4, k)));
t += 150;
} else if (msg.endsWith('패스')) {
later(at, () => pokerSfx.knock());
t += 120;
} else if (msg.startsWith('선언:')) {
later(at, () => pokerSfx.declare());
bump(seatEl(by));
t += 120;
} else if (msg.includes('벌칙')) {
flyGhost(seatEl(by), pot(), { kind: 'chip', count: 4, gap: 50, delay: at });
later(at, sfx.alarm);
bump(seatEl(by), 'shake');
t += 200;
} else if (msg.includes('가져갔어요')) {
flyGhost(pot(), seatEl(by), { kind: 'chip', count: 6, gap: 55, delay: at + 150 });
later(at + 300, sfx.collect);
later(at + 500, () => bump(seatEl(by)));
t += 250;
} else if (msg.includes('다시 받았어요')) {
flyGhost(center(), seatEl(by), { kind: 'coin', count: 5, gap: 60, delay: at });
later(at, sfx.coin);
t += 150;
} else if (msg.includes('자리 비움')) {
later(at, sfx.tick);
}
}
});
// Pot amount pops when it grows (after the chips arrive).
useChange(v.pot, (now, before) => {
if (now > before) later(380, () => bump(pot()));
});
// Mounted right at the start of the game (nothing played yet): show the deal once.
const started = useRef(false);
useLayoutEffect(() => {
if (started.current) return;
started.current = true;
if (v.handNo === 1 && v.handPhase !== 'handEnd' && !v.log.some((e) => e.by !== null)) deal(null);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
}
function resultLine(v: PokerView, players: Record<string, PublicUser>): string {
if (!v.awards) return '';
const won = new Map<string, number>();
@@ -369,21 +622,21 @@ function MyCards({ v, seat }: { v: PokerView; seat: SeatView }) {
const sd = v.showdown?.find((e) => e.id === seat.id);
const best = new Set(sd?.best ?? []);
return (
<div className="pk-mine" aria-label="내 카드">
<div className="pk-mine" aria-label="내 카드" data-fx="poker-mine">
{seat.forehead !== undefined && (
<div className="stack" style={{ gap: 2, alignItems: 'center' }}>
<div className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot="f">
<PlayingCard card={seat.forehead} size="lg" title={seat.forehead ? undefined : '내 이마 카드(나만 못 봐요)'} />
<span className="small muted">이마</span>
</div>
)}
{seat.hole.map((c, i) => (
<div key={`h${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }}>
<div key={`h${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot={c ?? `h${i}`}>
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
{(isSevenMode(v.mode) || v.mode === 'indian') && <span className="small muted">{v.mode === 'indian' ? '손' : '나만 봄'}</span>}
</div>
))}
{seat.up.map((c, i) => (
<div key={`u${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }}>
<div key={`u${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot={c ?? `u${i}`}>
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
<span className="small muted">공개</span>
</div>
@@ -397,6 +650,7 @@ function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unkno
const [discard, setDiscard] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const tap = (c: string) => {
sfx.select();
if (!discard) setDiscard(c);
else if (c === discard) {
setDiscard(null);
@@ -410,9 +664,9 @@ function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unkno
<br />
<span className="small muted">버린 카드는 아무에게도 보이지 않아요. 남는 2장은 나만 봐요.</span>
</p>
<div className="pk-mine">
<div className="pk-mine" data-fx="poker-mine">
{cards.map((c) => (
<span key={c} className={c === discard ? 'pk-x' : undefined}>
<span key={c} className={c === discard ? 'pk-x' : undefined} data-slot={c}>
<PlayingCard card={c} size="lg" selected={c === open} dimmed={c === discard} onClick={() => tap(c)} title={c === discard ? '버릴 카드(다시 누르면 취소)' : c === open ? '보여 줄 카드' : undefined} />
</span>
))}
@@ -457,7 +711,11 @@ function DrawPicker({ v, hole, act, pending }: { v: PokerView; hole: string[]; a
</p>
<div className="pk-mine">
{hole.map((c) => (
<PlayingCard key={c} card={c} size="lg" selected={sel.includes(c)} onClick={() => setSel((s) => (s.includes(c) ? s.filter((x) => x !== c) : [...s, c]))} />
<PlayingCard key={c} card={c} size="lg" selected={sel.includes(c)} onClick={() => {
sfx.select();
setSel((s) => (s.includes(c) ? s.filter((x) => x !== c) : [...s, c]));
}}
/>
))}
</div>
{tooMany && <p className="field-error" style={{ margin: 0, textAlign: 'center' }}>{limit}장까지만 바꿀 수 있어요.</p>}
@@ -812,7 +1070,7 @@ function statusText(v: PokerView, me: string | null, players: Record<string, Pub
// ---------------------------------------------------------------- options
function Seg<T extends string | number>({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
function Seg<T extends string | number | null>({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
return (
<div className="segmented">
{options.map(([k, l]) => (
@@ -868,7 +1126,7 @@ function Options({ value: o, onChange }: OptionsProps<PokerOptions>) {
{o.endCondition === 'hands' && <Seg value={o.handLimit} options={[[10, '10판'], [20, '20판'], [30, '30판'], [50, '50판']]} onChange={(handLimit) => set({ handLimit })} />}
</Field>
<Field label="행동 제한 시간">
<Seg value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Seg value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
{o.mode === 'indian' && (
<Field label="인디언 포커">
@@ -888,6 +1146,11 @@ function Options({ value: o, onChange }: OptionsProps<PokerOptions>) {
<Seg value={o.rebuy} options={[['off', '안 함(탈락)'], ['limited', '횟수 제한'], ['unlimited', '무제한']]} onChange={(rebuy) => set({ rebuy })} />
{o.rebuy === 'limited' && <Seg value={o.rebuyLimit} options={[[1, '1번'], [2, '2번'], [3, '3번']]} onChange={(rebuyLimit) => set({ rebuyLimit })} />}
</Field>
{o.rebuy !== 'off' && (
<Field label="리바이 고르는 시간">
<Seg value={o.rebuySeconds} options={[[10, '10초'], [15, '15초'], [30, '30초'], [null, '무제한']]} onChange={(rebuySeconds) => set({ rebuySeconds })} />
</Field>
)}
<Field label="기본 칩 2배로 올리기">
<Seg value={o.blindUpEvery} options={[[0, '안 올림'], [5, '5판마다'], [10, '10판마다'], [15, '15판마다']]} onChange={(blindUpEvery) => set({ blindUpEvery })} />
</Field>
@@ -933,7 +1196,7 @@ function Options({ value: o, onChange }: OptionsProps<PokerOptions>) {
function optionsSummary(o: PokerOptions): string {
const bet = o.betting === 'auto' ? '' : o.betting === 'korean' ? '한국식' : o.betting === 'noLimit' ? '노리밋' : '팟리밋';
return [MODE_KO[o.mode], bet, `시작 ${o.startingChips.toLocaleString('ko-KR')}칩`, `기본 ${o.baseUnit}칩`, o.endCondition === 'hands' ? `${o.handLimit}판` : '최후의 1인', `${o.turnSeconds}초`]
return [MODE_KO[o.mode], bet, `시작 ${o.startingChips.toLocaleString('ko-KR')}칩`, `기본 ${o.baseUnit}칩`, o.endCondition === 'hands' ? `${o.handLimit}판` : '최후의 1인', o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`]
.filter(Boolean)
.join(' · ');
}
@@ -974,7 +1237,11 @@ function Rules({ options }: { options?: PokerOptions }) {
{o?.rebuy === 'off' ? '탈락하고 구경해요.' : '칩을 다시 받을지 고를 수 있어요. 다시 받은 만큼 최종 점수에서 빠져요.'}{' '}
{o?.endCondition === 'lastStanding' ? '칩을 가진 사람이 한 명 남으면 끝나요.' : '정해진 판 수가 끝나면 (마지막 칩 − 시작 칩 × 다시 받은 횟수)로 순위를 정해요.'}
</p>
<p>시간 안에 고르지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 처리돼요. 두 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 짧아져요.</p>
{o?.turnSeconds === null ? (
<p>시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 자동 처리돼요. 이렇게 두 번 연속 넘어가면 '자리 비움'이 되고 짧은 제한 시간이 생겨요.</p>
) : (
<p>시간 안에 고르지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 처리돼요. 두 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 짧아져요.</p>
)}
</div>
);
}

View File

@@ -4,7 +4,8 @@ import type { CardFace, Color, LogEntry, SeatView, UnoCard, UnoOptions, UnoView
import type { PublicUser } from '@bg/shared/lite';
import { Avatar, Sheet } from '../../components/ui';
import { TurnTimer } from '../../components/TurnTimer';
import { haptic, sounds } from '../../lib/feedback';
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useChange, useNewEntries } from '../card-fx';
import { useSeatRows } from '../../lib/seat-rows';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, patternName } from '../one-card/ColorCard';
@@ -36,6 +37,30 @@ function cardName(c: CardFace): string {
const isWild = (c: CardFace) => c.kind === 'wild' || c.kind === 'wild4';
/** 우노 sounds on top of the shared palette (synthesized, no files). */
const unoSfx = {
skip: () => {
tone(520, 80, 'square', 0.05);
tone(330, 140, 'square', 0.05, 80);
},
reverse: () => {
tone(420, 220, 'triangle', 0.1, 0, { slideTo: 900 });
tone(900, 220, 'triangle', 0.08, 160, { slideTo: 420 });
},
wild: () => [523, 659, 784, 1046].forEach((f, i) => tone(f, 90, 'triangle', 0.08, i * 55)),
/** Heavy "+2 / +4" thump. */
plus: () => {
tone(170, 180, 'sawtooth', 0.07, 0, { slideTo: 80 });
tone(110, 220, 'sine', 0.16);
},
};
/** Where my last played card was (its button is gone once the view arrives), so the pile card flies from there. */
let myPlayRect: DOMRect | null = null;
const rememberPlay = (id: string) => {
myPlayRect = document.querySelector(`.un-card[data-id="${cssEsc(id)}"]`)?.getBoundingClientRect() ?? null;
};
function sortHand(hand: UnoCard[], by: 'color' | 'number'): UnoCard[] {
const col = (c: UnoCard) => ('color' in c ? COLORS.indexOf(c.color) : 9);
const num = (c: UnoCard) => (c.kind === 'num' ? c.value : c.kind === 'skip' ? 10 : c.kind === 'reverse' ? 11 : c.kind === 'draw2' ? 12 : c.kind === 'wild' ? 20 : 21);
@@ -77,7 +102,6 @@ const CSS = `
.un-discard { position: relative; width: calc(var(--pw) * 1.12); height: calc(var(--pw) * 1.12 * 1.4); border-radius: 12px; }
.un-discard::before { content: ''; position: absolute; inset: -9px; border-radius: 18px; border: 5px solid var(--cc, transparent); box-shadow: 0 0 18px var(--cc, transparent); transition: border-color .3s, box-shadow .3s; }
.un-discard > .un-face { position: absolute; inset: 0; }
.un-discard > .un-face.top { animation: un-fly .28s ease-out; }
.un-discard[data-drop='true'] { outline: 3px dashed #fde047; outline-offset: 12px; }
.un-info { display: flex; flex-direction: column; gap: 8px; align-items: flex-start; min-width: 0; text-shadow: 0 1px 2px rgba(0,0,0,.5); }
.un-info .row { gap: 6px; }
@@ -123,7 +147,6 @@ const CSS = `
.un-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 240px; overflow: auto; }
.un-rules td, .un-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); }
.un-rules .un-face { width: 34px; height: 48px; }
@keyframes un-fly { from { transform: translate(-40px, 30px) scale(.8); opacity: .3; } to { transform: none; opacity: 1; } }
@keyframes un-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } }
@keyframes un-shake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-8deg); } 75% { transform: rotate(8deg); } }
@media (min-width: 720px) {
@@ -163,7 +186,7 @@ function seatLabel(s: SeatView, players: Record<string, PublicUser>, me: string
function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; next: boolean }) {
const u = userOf(players, s.id);
return (
<li className={`un-seat${s.isTurn ? ' turn' : next ? ' next' : ''}${s.left ? ' gone' : ''}`} aria-label={seatLabel(s, players, me, v)}>
<li className={`un-seat${s.isTurn ? ' turn anim-glow' : next ? ' next' : ''}${s.left ? ' gone' : ''}`} data-fx-seat={s.id} aria-label={seatLabel(s, players, me, v)}>
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
<Avatar user={u} size={24} />
<span className="nm">{u.nickname}</span>
@@ -199,7 +222,7 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: UnoView; pl
const next = nextOf(v, v.current);
return (
<div className="un-table" role="region" aria-label="카드 판" style={{ '--pw': pw } as CSSProperties}>
<button type="button" className="un-pile" data-can={canDraw} disabled={!canDraw} onClick={onDraw} aria-label={`카드 더미 ${v.drawPileCount}장${canDraw ? `. 눌러서 ${drawText}` : ''}`}>
<button type="button" className="un-pile" data-fx="uno-deck" data-can={canDraw} disabled={!canDraw} onClick={onDraw} aria-label={`카드 더미 ${v.drawPileCount}장${canDraw ? `. 눌러서 ${drawText}` : ''}`}>
<Face card={null} />
<span className="cnt" aria-hidden>
{v.drawPileCount}
@@ -235,7 +258,7 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: UnoView; pl
</div>
<div className="un-info">
{v.color ? (
<span key={v.color} className="un-color" style={{ background: COLOR_HEX[v.color], color: COLOR_INK[v.color] }} aria-live="polite">
<span key={v.color} className="un-color anim-pop" style={{ background: COLOR_HEX[v.color], color: COLOR_INK[v.color] }} aria-live="polite">
<span className="sw" aria-hidden />
지금 색: {COLOR_KO[v.color]}
</span>
@@ -316,7 +339,12 @@ function MyHand({ v, act, pending, players }: { v: UnoView; act: (a: unknown) =>
const myTurn = v.current === v.me && (v.phase === 'turn' || v.phase === 'afterDraw' || (v.phase === 'wild4' && my.playable.length > 0));
const byId = (id: string) => my.hand.find((c) => c.id === id);
useNewEntries(my.hand, (c) => c.id, (fresh) => {
const deck = fxEl('uno-deck');
fresh.forEach((c, i) => flyFrom(document.querySelector(`.un-card[data-id="${cssEsc(c.id)}"]`), deck, { delay: i * 70, rotate: 8 }));
}, 30);
const send = (id: string, extra: Record<string, unknown> = {}) => {
rememberPlay(id);
act({ type: 'play', cardId: id, ...extra, ...(armed && my.hand.length === 2 ? { uno: true } : {}) });
setSel(null);
setPick(null);
@@ -336,6 +364,7 @@ function MyHand({ v, act, pending, players }: { v: UnoView; act: (a: unknown) =>
}
setNote('');
setSel(c.id);
sfx.select();
};
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
@@ -382,6 +411,7 @@ function MyHand({ v, act, pending, players }: { v: UnoView; act: (a: unknown) =>
</div>
<div
ref={ref}
data-fx="uno-hand"
className={`un-hand${phone ? ' wrap' : ''}`}
role="group"
aria-label="내 카드. 좌우 방향키로 고르고 Enter로 들어 올리거나 내요"
@@ -625,6 +655,9 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
if (lastLog && !mine) setAnnounce(logText(lastLog, players));
}, [lastLog?.seq, lastLog?.t]); // eslint-disable-line react-hooks/exhaustive-deps
const [banner, showBanner] = useBanner();
useUnoFx(v, me, players, showBanner);
const myIdx = v.seats.findIndex((s) => s.id === me);
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
const opps = useSeatRows<HTMLUListElement>(others.length);
@@ -646,7 +679,10 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
onDraw={() => act({ type: 'draw' })}
onDropCard={(id) => {
const c = v.my?.hand.find((x) => x.id === id);
if (c && v.my!.playable.includes(id) && !isWild(c)) act({ type: 'play', cardId: id });
if (c && v.my!.playable.includes(id) && !isWild(c)) {
rememberPlay(id);
act({ type: 'play', cardId: id });
}
}}
/>
<StartColorPanel v={v} act={act} pending={pending} />
@@ -662,10 +698,105 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
<p className="sr-only" aria-live="polite">
{announce}
</p>
{banner}
</div>
);
}
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
function useUnoFx(v: UnoView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
useNewEntries(v.log, logKey, (fresh) => {
let t = 0;
for (const e of fresh) {
const at = t;
switch (e.t) {
case 'play': {
const top = document.querySelector('.un-discard .un-face.top');
flyFrom(top, e.p === me ? (myPlayRect ?? fxEl('uno-hand')) : seatEl(e.p), { ms: 340, rotate: -14 });
if (e.p === me) myPlayRect = null;
later(at, () => {
sfx.cardPlay();
if (e.card.kind === 'wild') unoSfx.wild();
if (e.card.kind === 'draw2' || e.card.kind === 'wild4') unoSfx.plus();
});
if (e.card.kind === 'wild4') showBanner('+4', 'dark', e.color ? `${COLOR_KO[e.color]}으로` : undefined);
else if (e.card.kind === 'draw2') showBanner('+2', 'red');
t += 120;
break;
}
case 'draw': {
const n = Math.min(e.n, 8);
if (e.p !== me) flyGhost(fxEl('uno-deck'), seatEl(e.p), { count: n, gap: 80 });
later(at, () => sfx.draw(Math.min(n, 4)));
if (e.why === 'penalty' || e.why === 'challenge' || e.why === 'stack' || e.n >= 4) later(at, () => bump(seatEl(e.p), 'shake'));
t += 120;
break;
}
case 'uno':
showBanner('우노!', 'red', e.p === me ? undefined : `${nick(players, e.p)}님`);
later(at, sfx.fanfare);
bump(seatEl(e.p));
break;
case 'caught':
showBanner('잡았다!', 'gold', `${nick(players, e.p)}님 +${e.n}장`);
later(at, sfx.alarm);
break;
case 'challenge':
showBanner(e.illegal ? '도전 성공!' : '도전 실패', e.illegal ? 'green' : 'dark');
later(at + 150, e.illegal ? sfx.good : sfx.bad);
break;
case 'skip':
later(at + 80, unoSfx.skip);
bump(seatEl(e.p), 'shake');
break;
case 'reverse':
later(at + 80, unoSfx.reverse);
bump(document.querySelector('.un-dir b'));
break;
case 'reshuffle':
later(at, sfx.shuffle);
bump(fxEl('uno-deck'), 'shake');
break;
case 'startColor':
later(at, unoSfx.wild);
break;
case 'round':
if (e.winner) {
const to = seatEl(e.winner) ?? fxEl('uno-hand');
for (const s of v.seats) if (s.id !== e.winner && !s.left) flyGhost(seatEl(s.id), to, { count: 3, gap: 60 });
later(at + 200, sfx.collect);
}
break;
case 'timeout':
later(at, sfx.tick);
break;
default:
break;
}
}
});
// A new round (or the very first deal): cards are dealt from the deck to everyone.
// `myHand`: only on mount — on a later round MyHand's own new-card motion already flies my cards in.
const deal = (myHand: boolean) => {
const deck = fxEl('uno-deck');
sfx.shuffle();
setTimeout(() => sfx.deal(7, 60), 300);
if (myHand) document.querySelectorAll('.un-hand .un-card').forEach((el, i) => flyFrom(el, deck, { delay: 280 + i * 60, rotate: 10 }));
for (const s of v.seats) if (s.id !== me && !s.left) flyGhost(deck, seatEl(s.id), { count: 3, gap: 90, delay: 280 });
};
useChange(v.round, () => deal(false));
const started = useRef(false);
useLayoutEffect(() => {
if (started.current) return;
started.current = true;
// Mounted right at the start of the game (nothing played yet): show the deal once.
if (v.round === 1 && v.discardCount <= 1 && !v.log.some((e) => e.t === 'play')) deal(true);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
}
const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`;
// ---------------------------------------------------------------- side
function rulesLine(o: UnoOptions): string {
@@ -733,7 +864,7 @@ function UnoSide({ view: v, me, players, deadline }: BoardProps<UnoView>) {
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
<ol className="un-log">
{[...v.log].reverse().map((e) => (
<li key={`${e.seq}-${e.t}-${'p' in e ? e.p : ''}`} className="small">
<li key={logKey(e)} className="small">
{logText(e, players)}
</li>
))}
@@ -777,7 +908,7 @@ function statusText(v: UnoView, me: string | null, players: Record<string, Publi
// ---------------------------------------------------------------- options
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
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]) => (
@@ -824,7 +955,7 @@ function Options({ value: o, onChange }: OptionsProps<UnoOptions>) {
<Seg label="낼 수 있을 때까지 뽑기" value={o.drawUntilPlayable} options={onOff} onChange={(drawUntilPlayable) => set({ drawUntilPlayable })} />
</Field>
<Field label="한 턴 제한 시간">
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
</div>
);
@@ -834,7 +965,7 @@ function optionsSummary(o: UnoOptions): string {
const parts = [o.scoring === 'to500' ? '500점 먼저' : '한 판', o.wild4Rule === 'challenge' ? '+4 도전' : '+4 제한'];
if (o.stacking) parts.push('쌓기');
if (o.drawUntilPlayable) parts.push('나올 때까지 뽑기');
parts.push(`${o.turnSeconds}초`);
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
return parts.join(' · ');
}
@@ -897,7 +1028,10 @@ function Rules({ options }: { options?: UnoOptions }) {
<strong>점수</strong>: 이긴 사람은 다른 사람 손에 남은 카드 점수(숫자 그대로, 스킵·리버스·드로우2 20점, 와일드 50점)를 얻어요.
{o.scoring === 'to500' ? ' 여러 판을 해서 500점에 먼저 닿으면 이겨요.' : ' 이 방은 한 판으로 끝나요.'}
</p>
<p>시간 안에 고르지 않으면 낼 수 있는 카드 하나를 자동으로 내요(와일드는 가장 많이 가진 색). 낼 카드가 없으면 1장 뽑아요.</p>
<p>
{o.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 낼 수 있는 카드 하나를 자동으로 내요(와일드는 가장 많이
가진 색). 낼 카드가 없으면 1장 뽑아요.
</p>
</div>
);
}