병합: wt2/g2-cards
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
/** 뱅! 화면 (docs/games/bang.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import type { BangOptions, BangView, Card, CardFace, CardKind, CharacterId, LogEntry, PlayOption, PlayerView, Prompt, Role, Team } from '@bg/games/bang';
|
||||
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, type BannerTone } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -176,14 +177,91 @@ button.bg-card:focus-visible { outline: 3px solid var(--focus); outline-offset:
|
||||
.bg-me { padding: 8px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { button.bg-card { transition: none; } }
|
||||
.fx-ghost.bg-ghost { background: #fffaf0; border: 2px solid #92400e; box-shadow: 0 3px 8px rgba(0,0,0,.35); display: flex; align-items: center; justify-content: center;
|
||||
font: 900 20px/1 system-ui, sans-serif; color: #1f2937; }
|
||||
.fx-ghost.bg-ghost.blue { border-color: #1d4ed8; }
|
||||
.fx-ghost.bg-ghost.chk { font-size: 14px; }
|
||||
.fx-ghost.bg-ghost.chk.r { color: #dc2626; }
|
||||
.fx-ghost.bg-ghost-back { background: repeating-linear-gradient(45deg, #7c2d12 0 5px, #9a3412 5px 10px); border: 2px solid #fdba74; box-shadow: 0 3px 8px rgba(0,0,0,.35); }
|
||||
.fx-ghost.bg-bullet { background: none; border: 0; box-shadow: none; font-size: 22px; }
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- sounds + motion helpers
|
||||
|
||||
/** 뱅! sounds on top of the shared palette (synthesized; `d` = delay in ms). */
|
||||
const shot = (d = 0) => {
|
||||
noise(110, 0.32, d, 'bandpass', 1700, 0.6);
|
||||
noise(40, 0.18, d, 'highpass', 4500);
|
||||
tone(95, 170, 'sine', 0.26, d, { slideTo: 45 });
|
||||
};
|
||||
const bangSfx = {
|
||||
shot,
|
||||
gatling: (d = 0) => {
|
||||
for (let i = 0; i < 7; i++) {
|
||||
noise(60, 0.22, d + i * 85, 'bandpass', 1600 + (i % 3) * 250, 0.7);
|
||||
tone(90, 80, 'sine', 0.15, d + i * 85, { slideTo: 50 });
|
||||
}
|
||||
},
|
||||
/** 빗나감! / 술통: a ricochet whistle. */
|
||||
ricochet: (d = 0) => {
|
||||
noise(30, 0.08, d, 'highpass', 5000);
|
||||
tone(2200, 300, 'sine', 0.07, d + 10, { slideTo: 700 });
|
||||
},
|
||||
hit: (d = 0) => {
|
||||
noise(90, 0.2, d, 'lowpass', 500, 0.8);
|
||||
tone(160, 200, 'sawtooth', 0.07, d, { slideTo: 70 });
|
||||
},
|
||||
/** Glug glug + clink. */
|
||||
beer: (d = 0) => {
|
||||
[0, 110, 220].forEach((x, i) => tone(240 - i * 25, 80, 'sine', 0.14, d + x, { slideTo: 150 }));
|
||||
tone(2600, 140, 'triangle', 0.05, d + 340);
|
||||
tone(3300, 120, 'triangle', 0.04, d + 360);
|
||||
},
|
||||
boom: (d = 0) => {
|
||||
noise(900, 0.42, d, 'lowpass', 380, 0.7);
|
||||
noise(120, 0.22, d, 'bandpass', 1200, 0.5);
|
||||
tone(70, 800, 'sine', 0.3, d, { slideTo: 28 });
|
||||
},
|
||||
/** Jail bars. */
|
||||
clank: (d = 0) => {
|
||||
tone(330, 180, 'square', 0.05, d);
|
||||
tone(495, 220, 'square', 0.04, d + 30);
|
||||
noise(70, 0.14, d, 'bandpass', 4200, 3);
|
||||
},
|
||||
drums: (d = 0) =>
|
||||
[0, 170, 340, 430, 520].forEach((x) => {
|
||||
tone(120, 130, 'sine', 0.26, d + x, { slideTo: 65 });
|
||||
noise(50, 0.08, d + x, 'lowpass', 320);
|
||||
}),
|
||||
duel: (d = 0) => {
|
||||
shot(d);
|
||||
shot(d + 340);
|
||||
},
|
||||
death: (d = 0) => tone(440, 750, 'triangle', 0.12, d, { slideTo: 100 }),
|
||||
};
|
||||
|
||||
/** 판정 card / role badge turning face up (Web Animations, no layout change). */
|
||||
function flip(el: Element | null | undefined, delay = 0): void {
|
||||
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||
(el as HTMLElement).animate([{ transform: 'perspective(500px) rotateX(90deg)', opacity: 0.3 }, { transform: 'perspective(500px) rotateX(0deg)', opacity: 1 }], {
|
||||
duration: 380,
|
||||
delay,
|
||||
easing: 'ease-out',
|
||||
fill: 'backwards',
|
||||
composite: 'add',
|
||||
});
|
||||
}
|
||||
|
||||
const sameFace = (a: CardFace, b: CardFace) => a.kind === b.kind && a.suit === b.suit && a.rank === b.rank;
|
||||
const faceGhost = (f: CardFace) => ({ label: CARD_INFO[f.kind].icon, className: `bg-ghost${BLUE.includes(f.kind) ? ' blue' : ''}` });
|
||||
const BACK_GHOST = { className: 'bg-ghost-back' };
|
||||
|
||||
// ---------------------------------------------------------------- small parts
|
||||
|
||||
function CardArt({ card, small, label }: { card: CardFace; small?: boolean; label?: boolean }) {
|
||||
function CardArt({ card, small, label, fx }: { card: CardFace; small?: boolean; label?: boolean; fx?: string }) {
|
||||
const info = CARD_INFO[card.kind];
|
||||
return (
|
||||
<span className={`bg-card${small ? ' sm' : ''}`} data-blue={BLUE.includes(card.kind)} aria-hidden={!label} {...(label ? { role: 'img', 'aria-label': faceAria(card) } : {})}>
|
||||
<span className={`bg-card${small ? ' sm' : ''}`} data-fx={fx} data-blue={BLUE.includes(card.kind)} aria-hidden={!label} {...(label ? { role: 'img', 'aria-label': faceAria(card) } : {})}>
|
||||
<CardFaceInner card={card} info={info} />
|
||||
</span>
|
||||
);
|
||||
@@ -300,7 +378,7 @@ function Seat({
|
||||
) : p.isTurn && !v.reactions.length && !v.winner ? (
|
||||
<TurnTimer deadline={v.turnDeadline} totalMs={v.deadlineTotalMs} mine={p.id === me} size={26} />
|
||||
) : null;
|
||||
const cls = `bg-seat${p.isTurn ? ' turn' : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}`;
|
||||
const cls = `bg-seat${p.isTurn ? ` turn${v.winner ? '' : ' anim-glow'}` : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}`;
|
||||
const body = (
|
||||
<>
|
||||
<span className="bg-row nw">
|
||||
@@ -347,6 +425,7 @@ function Seat({
|
||||
style={style}
|
||||
data-target="ok"
|
||||
data-player={p.id}
|
||||
data-fx-seat={p.id}
|
||||
aria-pressed={mark.selected}
|
||||
aria-label={`${seatLabel(p, players, me, shownRole(p, v, me))}. 대상으로 고르기`}
|
||||
onClick={() => onPick(p.id)}
|
||||
@@ -356,7 +435,7 @@ function Seat({
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} role="group" aria-label={seatLabel(p, players, me, shownRole(p, v, me)) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
||||
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} data-fx-seat={p.id} role="group" aria-label={seatLabel(p, players, me, shownRole(p, v, me)) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
@@ -379,15 +458,15 @@ function Center({ v, players }: { v: BangView; players: Record<string, PublicUse
|
||||
const last = v.log[v.log.length - 1];
|
||||
return (
|
||||
<div className="bg-center">
|
||||
<div className="bg-piles">
|
||||
<span className="bg-back" role="img" aria-label={`카드 더미 ${v.deckCount}장`}>
|
||||
<div className="bg-piles" data-fx="bang-piles">
|
||||
<span className="bg-back" data-fx="bang-deck" role="img" aria-label={`카드 더미 ${v.deckCount}장`}>
|
||||
{v.deckCount}
|
||||
</span>
|
||||
{top ? <CardArt card={top} small label /> : <span className="bg-chip">버린 카드 없음</span>}
|
||||
{top ? <CardArt card={top} small label fx="bang-discard" /> : <span className="bg-chip" data-fx="bang-discard">버린 카드 없음</span>}
|
||||
</div>
|
||||
{v.phase !== 'draft' && <span className="bg-chip">{v.round}라운드</span>}
|
||||
{chk && (
|
||||
<span className={`bg-chip ${chk.success ? 'ok' : 'bad'}`} aria-live="polite">
|
||||
<span className={`bg-chip ${chk.success ? 'ok' : 'bad'}`} data-fx="bang-check" aria-live="polite">
|
||||
{nick(players, chk.player)}님 {PURPOSE[chk.purpose]} 판정: {chk.cards.map((c) => `${SUIT_SYMBOL[c.suit]}${c.rank}`).join(' · ')} → {chk.success ? '성공' : '실패'}
|
||||
</span>
|
||||
)}
|
||||
@@ -474,12 +553,14 @@ function HandCards({
|
||||
picked,
|
||||
onTap,
|
||||
label,
|
||||
fx,
|
||||
}: {
|
||||
hand: Card[];
|
||||
okOf?: (c: Card) => boolean | undefined;
|
||||
picked: (c: Card) => boolean;
|
||||
onTap: (c: Card) => void;
|
||||
label: string;
|
||||
fx?: string;
|
||||
}) {
|
||||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||||
@@ -490,7 +571,7 @@ function HandCards({
|
||||
btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length]?.focus();
|
||||
};
|
||||
return (
|
||||
<div className="bg-hand" role="group" aria-label={label} onKeyDown={onKey}>
|
||||
<div className="bg-hand" data-fx={fx} role="group" aria-label={label} onKeyDown={onKey}>
|
||||
{hand.map((c) => {
|
||||
const ok = okOf?.(c);
|
||||
return (
|
||||
@@ -595,7 +676,7 @@ function MyArea({
|
||||
|
||||
return (
|
||||
<section className="bg-me" aria-label="내 자리">
|
||||
<div className="bg-mehead">
|
||||
<div className="bg-mehead" data-fx="bang-me">
|
||||
<RoleCard role={my.role} hints={hints} always={!!v.winner || !meP?.alive} />
|
||||
<span className="stack" style={{ gap: 2, flex: '1 1 220px', minWidth: 0 }}>
|
||||
<strong>
|
||||
@@ -619,6 +700,7 @@ function MyArea({
|
||||
{prompt?.kind === 'draw' && <DrawPanel prompt={prompt} act={act} pending={pending} players={players} />}
|
||||
{meP?.alive && (
|
||||
<HandCards
|
||||
fx="bang-hand"
|
||||
hand={my.hand}
|
||||
label={`내 카드 ${my.hand.length}장. 좌우 방향키로 고르고 Enter로 눌러요`}
|
||||
okOf={(c) => (discarding || sidMode ? undefined : playing ? !!optOf(c.id)?.ok : undefined)}
|
||||
@@ -974,6 +1056,8 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
||||
useEffect(() => {
|
||||
if (last && !mine) setAnnounce(logText(last, players));
|
||||
}, [last?.seq, last?.t]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const [banner, showBanner] = useBanner();
|
||||
useBangFx(v, me, players, showBanner);
|
||||
|
||||
const n = v.players.length;
|
||||
const myIdx = v.players.findIndex((p) => p.id === me);
|
||||
@@ -1018,10 +1102,313 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const TEAM_TONE: Record<Team, BannerTone> = { law: 'blue', outlaws: 'red', renegade: 'gold' };
|
||||
|
||||
/**
|
||||
* Sounds + motion for every change of the table, mine or anyone else's: the log entries that are new since the last
|
||||
* view (never on the first render, so joining / reloading / a replay jump stays quiet).
|
||||
*/
|
||||
function useBangFx(v: BangView, me: string | null, players: Record<string, PublicUser>, showBanner: (text: string, tone?: BannerTone, sub?: string) => void) {
|
||||
// Entries of one action share `seq`; count repeats (two 판정 cards, Black Jack's two draws) so every key is unique.
|
||||
const keyed = useMemo(() => {
|
||||
const seen = new Map<string, number>();
|
||||
return v.log.map((e) => {
|
||||
const base = `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`;
|
||||
const i = seen.get(base) ?? 0;
|
||||
seen.set(base, i + 1);
|
||||
return { e, k: `${base}-${i}` };
|
||||
});
|
||||
}, [v.log]);
|
||||
/** Last known place of my hand cards: a card I played is gone from the DOM once the view arrives. */
|
||||
const handRects = useRef(new Map<string, { r: DOMRect; f: CardFace }>());
|
||||
/** Where my next new hand cards come from (deck by default) and when. */
|
||||
const handSrc = useRef<{ from: Element | DOMRect | null; at: number } | null>(null);
|
||||
|
||||
const visible = (el: Element | null) => (el && el.getBoundingClientRect().width > 0 ? el : null);
|
||||
/** A player's seat; my own seat is hidden on phones, so my area stands in for it. */
|
||||
const place = (id: string): Element | null => visible(seatEl(id)) ?? (id === me ? fxEl('bang-me') : null);
|
||||
/** Where a card I (or someone) just used came from. */
|
||||
const srcOf = (id: string, f?: CardFace): Element | DOMRect | null => {
|
||||
if (id === me && f) {
|
||||
const hand = new Set(v.my?.hand.map((c) => c.id) ?? []);
|
||||
for (const [cid, x] of handRects.current) {
|
||||
if (hand.has(cid) || !sameFace(x.f, f)) continue;
|
||||
handRects.current.delete(cid);
|
||||
return x.r;
|
||||
}
|
||||
}
|
||||
return place(id);
|
||||
};
|
||||
const name = (id: string) => `${nick(players, id)}님`;
|
||||
|
||||
useNewEntries(
|
||||
keyed,
|
||||
(x) => x.k,
|
||||
(fresh) => {
|
||||
const deck = fxEl('bang-deck');
|
||||
const pile = fxEl('bang-discard') ?? deck;
|
||||
const piles = fxEl('bang-piles');
|
||||
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
|
||||
const toPile = (from: Element | DOMRect | null, f: CardFace | null, delay: number) => flyGhost(from, pile, { delay, ms: 420, ...(f ? faceGhost(f) : BACK_GHOST) });
|
||||
const toMe = (from: Element | null, at: number) => (handSrc.current = { from, at });
|
||||
const others = (p: string) => v.players.filter((x) => x.alive && x.id !== p).map((x) => x.id);
|
||||
let healed = false;
|
||||
let t = 0;
|
||||
for (const { e } of fresh) {
|
||||
const at = Math.min(t, 3000);
|
||||
switch (e.t) {
|
||||
case 'play': {
|
||||
const k = e.as ?? e.card.kind;
|
||||
toPile(srcOf(e.p, e.card), e.card, at);
|
||||
later(at, sfx.cardPlay);
|
||||
if (k === 'bang' && e.target) {
|
||||
const tg = e.target;
|
||||
flyGhost(place(e.p), place(tg), { kind: 'coin', label: '💥', className: 'bg-bullet', ms: 260, delay: at + 100 });
|
||||
bangSfx.shot(at + 100);
|
||||
later(at + 340, () => bump(place(tg), 'shake'));
|
||||
if (tg === me) later(at, () => showBanner('뱅!', 'red', `${name(e.p)}이 쐈어요`));
|
||||
t += 450;
|
||||
} else if (k === 'gatling') {
|
||||
bangSfx.gatling(at + 80);
|
||||
later(at, () => showBanner('개틀링!', 'red', name(e.p)));
|
||||
others(e.p).forEach((id, i) => later(at + 200 + i * 85, () => bump(place(id), 'shake')));
|
||||
t += 750;
|
||||
} else if (k === 'indians') {
|
||||
bangSfx.drums(at + 60);
|
||||
later(at, () => showBanner('인디언!', 'gold', name(e.p)));
|
||||
others(e.p).forEach((id, i) => later(at + 150 + i * 90, () => bump(place(id))));
|
||||
t += 650;
|
||||
} else if (k === 'duel') {
|
||||
bangSfx.duel(at + 80);
|
||||
if (e.target && (e.p === me || e.target === me)) later(at, () => showBanner('결투!', 'dark', `${name(e.p)} vs ${name(e.target!)}`));
|
||||
if (e.target) later(at + 120, () => bump(place(e.target!)));
|
||||
t += 650;
|
||||
} else if (k === 'generalStore') {
|
||||
later(at + 100, sfx.shuffle);
|
||||
t += 300;
|
||||
} else if (k === 'panic' || k === 'catBalou') {
|
||||
later(at + 100, sfx.whoosh);
|
||||
t += 250;
|
||||
} else t += 200;
|
||||
break;
|
||||
}
|
||||
case 'equip': {
|
||||
const to = e.target ?? e.p;
|
||||
flyGhost(srcOf(e.p, e.card), place(to), { delay: at, ms: 420, ...faceGhost(e.card) });
|
||||
later(at, sfx.cardPlay);
|
||||
if (e.card.kind === 'jail') {
|
||||
bangSfx.clank(at + 400);
|
||||
later(at + 400, () => bump(place(to), 'shake'));
|
||||
} else later(at + 400, () => bump(place(to)));
|
||||
if (e.replaced) toPile(place(to), e.replaced, at + 300);
|
||||
t += 400;
|
||||
break;
|
||||
}
|
||||
case 'check': {
|
||||
e.cards.forEach((c, i) => {
|
||||
flyGhost(deck, pile, { delay: at + i * 220, ms: 380, label: `${SUIT_SYMBOL[c.suit]}${c.rank}`, className: `bg-ghost chk${sr(c) === 'r' ? ' r' : ''}` });
|
||||
later(at + i * 220, sfx.cardFlip);
|
||||
});
|
||||
const end = at + 300 + (e.cards.length - 1) * 220;
|
||||
flip(fxEl('bang-check'), end);
|
||||
later(end + 80, e.success ? sfx.good : sfx.bad);
|
||||
t += 450 + (e.cards.length - 1) * 220;
|
||||
break;
|
||||
}
|
||||
case 'dynamite':
|
||||
if (e.exploded) {
|
||||
bangSfx.boom(at);
|
||||
later(at, () => {
|
||||
showBanner('펑!', 'dark', `${name(e.p)} 앞에서 다이너마이트가 터졌어요`);
|
||||
bump(place(e.p), 'shake');
|
||||
});
|
||||
t += 700;
|
||||
} else if (e.to) {
|
||||
flyGhost(place(e.p), place(e.to), { delay: at, ms: 420, label: '🧨', className: 'bg-ghost blue' });
|
||||
later(at, sfx.whoosh);
|
||||
t += 400;
|
||||
}
|
||||
break;
|
||||
case 'jail':
|
||||
flyGhost(place(e.p), pile, { delay: at + 200, ms: 400, label: '🔒', className: 'bg-ghost blue' });
|
||||
if (e.escaped) {
|
||||
later(at, () => {
|
||||
sfx.good();
|
||||
bump(place(e.p));
|
||||
});
|
||||
} else {
|
||||
bangSfx.clank(at);
|
||||
later(at, () => bump(place(e.p), 'shake'));
|
||||
if (e.p === me) later(at, () => showBanner('감옥!', 'dark', '이번 턴을 쉬어요'));
|
||||
}
|
||||
t += 450;
|
||||
break;
|
||||
case 'missed':
|
||||
e.cards.forEach((c, i) => toPile(srcOf(e.p, c), c, at + i * 80));
|
||||
bangSfx.ricochet(at);
|
||||
later(at, () => bump(place(e.p)));
|
||||
t += 350;
|
||||
break;
|
||||
case 'barrelSave':
|
||||
bangSfx.ricochet(at);
|
||||
later(at, () => bump(place(e.p)));
|
||||
t += 300;
|
||||
break;
|
||||
case 'respond':
|
||||
e.cards.forEach((c) => toPile(srcOf(e.p, c), c, at));
|
||||
if (e.why === 'duel') bangSfx.shot(at + 80);
|
||||
else later(at, sfx.cardPlay);
|
||||
t += 350;
|
||||
break;
|
||||
case 'hit':
|
||||
bangSfx.hit(at);
|
||||
later(at, () => {
|
||||
bump(place(e.p), 'shake');
|
||||
if (e.p === me) haptic([40, 40, 40]);
|
||||
});
|
||||
t += 350;
|
||||
break;
|
||||
case 'heal':
|
||||
e.cards?.forEach((c) => toPile(srcOf(e.p, c), c, at));
|
||||
if (!healed) bangSfx.beer(at);
|
||||
healed = healed || e.why === 'saloon';
|
||||
later(at + 200, () => bump(place(e.p)));
|
||||
t += e.why === 'saloon' ? 60 : 400;
|
||||
break;
|
||||
case 'draw': {
|
||||
const n = Math.min(e.n, 6);
|
||||
if (e.p === me) toMe(deck, at);
|
||||
else flyGhost(deck, place(e.p), { count: n, gap: 80, delay: at, ...BACK_GHOST });
|
||||
later(at, () => sfx.draw(Math.min(n, 4)));
|
||||
t += 120 + 80 * Math.min(n, 4);
|
||||
break;
|
||||
}
|
||||
case 'blackJack':
|
||||
later(at, sfx.cardFlip);
|
||||
if (e.extra) later(at + 150, () => {
|
||||
sfx.good();
|
||||
bump(place(e.p));
|
||||
});
|
||||
t += 250;
|
||||
break;
|
||||
case 'pedro':
|
||||
if (e.p === me) toMe(pile, at);
|
||||
else flyGhost(pile, place(e.p), { delay: at, ms: 420, ...faceGhost(e.card) });
|
||||
later(at, () => sfx.cardDeal());
|
||||
t += 250;
|
||||
break;
|
||||
case 'take':
|
||||
if (e.p === me) toMe(place(e.from), at);
|
||||
else flyGhost(place(e.from), place(e.p), { delay: at, ms: 420, ...(e.equip ? faceGhost(e.equip) : e.card ? faceGhost(e.card) : BACK_GHOST) });
|
||||
later(at, sfx.whoosh);
|
||||
t += 300;
|
||||
break;
|
||||
case 'discarded':
|
||||
toPile(place(e.p), e.card, at);
|
||||
later(at, () => {
|
||||
sfx.whoosh();
|
||||
bump(place(e.p), 'shake');
|
||||
});
|
||||
t += 300;
|
||||
break;
|
||||
case 'limit':
|
||||
e.cards.forEach((c, i) => toPile(srcOf(e.p, c), c, at + i * 70));
|
||||
later(at, () => sfx.deal(Math.min(e.cards.length, 4)));
|
||||
t += 250;
|
||||
break;
|
||||
case 'store':
|
||||
if (e.p === me) toMe(piles, at);
|
||||
else flyGhost(piles, place(e.p), { delay: at, ms: 420, ...faceGhost(e.card) });
|
||||
later(at, () => sfx.cardDeal());
|
||||
t += 250;
|
||||
break;
|
||||
case 'storeOpen':
|
||||
later(at, () => sfx.deal(Math.min(e.cards.length, 7)));
|
||||
later(at, () => bump(piles));
|
||||
t += 300;
|
||||
break;
|
||||
case 'dead': {
|
||||
const role = ROLE_INFO[e.role];
|
||||
bangSfx.death(at);
|
||||
later(at, () => {
|
||||
showBanner(e.left ? `${name(e.p)} 탈락` : `${name(e.p)} 쓰러짐`, 'dark', `${role.icon} ${role.name}였어요`);
|
||||
bump(place(e.p), 'shake');
|
||||
});
|
||||
flip(place(e.p)?.querySelector('.bg-role'), at + 200);
|
||||
t += 900;
|
||||
break;
|
||||
}
|
||||
case 'reward':
|
||||
later(at, sfx.collect);
|
||||
t += 150;
|
||||
break;
|
||||
case 'penalty':
|
||||
toPile(place(e.p), null, at);
|
||||
later(at, sfx.bad);
|
||||
t += 250;
|
||||
break;
|
||||
case 'vulture':
|
||||
if (e.p === me) toMe(place(e.from), at);
|
||||
else flyGhost(place(e.from), place(e.p), { count: Math.min(e.n, 6), gap: 70, delay: at, ...BACK_GHOST });
|
||||
later(at, sfx.collect);
|
||||
t += 350;
|
||||
break;
|
||||
case 'character':
|
||||
later(at, sfx.select);
|
||||
break;
|
||||
case 'turn':
|
||||
later(at, () => bump(place(e.p)));
|
||||
t += 100;
|
||||
break;
|
||||
case 'timeout':
|
||||
later(at, sfx.tick);
|
||||
break;
|
||||
case 'reshuffle':
|
||||
later(at, () => {
|
||||
sfx.shuffle();
|
||||
bump(deck, 'shake');
|
||||
});
|
||||
t += 300;
|
||||
break;
|
||||
case 'end':
|
||||
// The room already plays the win / lose sound.
|
||||
later(at + 300, () => showBanner(`${TEAM_KO[e.winner]} 승리!`, TEAM_TONE[e.winner]));
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
30,
|
||||
);
|
||||
|
||||
// New cards in my hand fly in from wherever they came from (deck, discard pile, another seat, the store).
|
||||
useNewEntries(
|
||||
v.my?.hand,
|
||||
(c) => c.id,
|
||||
(fresh) => {
|
||||
const src = handSrc.current ?? { from: fxEl('bang-deck'), at: 0 };
|
||||
fresh.forEach((c, i) =>
|
||||
flyFrom(document.querySelector(`[data-fx="bang-hand"] [data-id="${cssEsc(c.id)}"]`), src.from, { delay: Math.min(src.at, 3000) + i * 70, rotate: 8 }),
|
||||
);
|
||||
},
|
||||
20,
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
handSrc.current = null;
|
||||
const m = new Map<string, { r: DOMRect; f: CardFace }>();
|
||||
for (const c of v.my?.hand ?? []) {
|
||||
const el = document.querySelector(`[data-fx="bang-hand"] [data-id="${cssEsc(c.id)}"]`);
|
||||
if (el) m.set(c.id, { r: el.getBoundingClientRect(), f: c });
|
||||
}
|
||||
handRects.current = m;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
||||
@@ -1034,7 +1421,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 +1519,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 +1555,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 +1595,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 +1628,7 @@ function CardTable() {
|
||||
);
|
||||
}
|
||||
|
||||
function Rules() {
|
||||
function Rules({ options }: { options?: BangOptions }) {
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
@@ -1256,7 +1645,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>
|
||||
|
||||
228
apps/web/src/games/card-fx.tsx
Normal file
228
apps/web/src/games/card-fx.tsx
Normal 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);
|
||||
}
|
||||
@@ -4,7 +4,8 @@ import type { ClaimEntry, CockroachOptions, CockroachView, FrontView, Kind, Last
|
||||
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, flyGhost, seatEl, useBanner } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -213,6 +214,7 @@ const CSS = `
|
||||
.cp-seats { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 10px; }
|
||||
.cp-seat { position: relative; background: var(--surface); border-radius: var(--radius-lg); padding: 9px 11px; box-shadow: var(--shadow); border: 3px solid transparent; display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
||||
.cp-seat.turn { border-color: var(--focus); }
|
||||
.fx-ghost.cp-ghost { background: linear-gradient(135deg, #7c2d12, #431407); border: 2px solid #fdba74; border-radius: 7px; box-shadow: 0 3px 8px rgba(0,0,0,.35); }
|
||||
.cp-seat.loser { border-color: var(--danger); }
|
||||
.cp-head { display: flex; align-items: center; gap: 7px; min-height: 30px; min-width: 0; }
|
||||
.cp-name { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; }
|
||||
@@ -354,7 +356,7 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: Cockroa
|
||||
const role = v.phase === 'finished' ? null : r.holder === id ? (r.peeked ? '넘기는 중' : '받는 중') : r.holder === null && r.starter === id ? '건네는 중' : null;
|
||||
const label = `${u.nickname}님${id === me ? '(나)' : ''}: 손패 ${v.handCounts[id]}장, ${frontText(front, v.loseCount)}${role ? `, ${role}` : ''}${r.seen.includes(id) && r.holder !== null ? ', 이 카드를 봤어요' : ''}${v.away[id] ? ', 자리 비움' : ''}`;
|
||||
return (
|
||||
<section className={`cp-seat${active ? ' turn' : ''}${loser ? ' loser' : ''}`} aria-label={label}>
|
||||
<section className={`cp-seat${active ? ' turn anim-glow' : ''}${loser ? ' loser' : ''}`} data-fx-seat={id} aria-label={label}>
|
||||
{bubble && (
|
||||
<span className="cp-bubble" aria-hidden>
|
||||
{bubble}
|
||||
@@ -705,7 +707,7 @@ function MyArea({
|
||||
const active = waitingOn(v) === me;
|
||||
const total = v.handCounts[me] ?? 0;
|
||||
return (
|
||||
<section className={`cp-me${active ? ' turn' : ''}`} aria-label="내 자리">
|
||||
<section className={`cp-me${active ? ' turn anim-glow' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||
{bubble && (
|
||||
<span className="cp-bubble" aria-hidden>
|
||||
{bubble}
|
||||
@@ -752,7 +754,15 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [bubbles, setBubbles] = useState<Record<string, string>>({});
|
||||
const [fresh, setFresh] = useState({ slide: false, flip: false });
|
||||
const prev = useRef({ claims: v.round.claims.length + v.round.no * 100, reveal: v.lastReveal?.round ?? 0, said: v.said[v.said.length - 1]?.seq ?? 0, waiting: waitingOn(v) });
|
||||
const [banner, showBanner] = useBanner();
|
||||
const prev = useRef({
|
||||
claims: v.round.claims.length + v.round.no * 100,
|
||||
reveal: v.lastReveal?.round ?? 0,
|
||||
said: v.said[v.said.length - 1]?.seq ?? 0,
|
||||
waiting: waitingOn(v),
|
||||
peek: `${v.round.no}:${v.round.seen.length}`,
|
||||
over: v.phase === 'finished',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
@@ -763,6 +773,37 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
let msg = '';
|
||||
const slide = claimsKey !== p.claims && v.round.holder !== null;
|
||||
const flip = revealKey !== p.reveal && !!v.lastReveal;
|
||||
const peekKey = `${v.round.no}:${v.round.seen.length}`;
|
||||
const over = v.phase === 'finished';
|
||||
// Sounds + motion (2026-10-13): the same diff drives everyone's moves, so other players' and computers' moves show too.
|
||||
if (slide && v.round.lastPasser && v.round.holder) {
|
||||
flyGhost(seatEl(v.round.lastPasser), seatEl(v.round.holder), { ms: 460, className: 'cp-ghost' });
|
||||
sfx.cardDeal();
|
||||
cpSfx.sneak(80);
|
||||
} else if (!flip && peekKey !== p.peek && v.round.peeked) {
|
||||
sfx.cardFlip(); // someone takes a secret look before passing on
|
||||
}
|
||||
if (flip) {
|
||||
const rv = v.lastReveal!;
|
||||
sfx.cardFlip();
|
||||
setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), 260);
|
||||
showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`);
|
||||
flyGhost(document.querySelector('.cp-table'), seatEl(rv.takenBy), { delay: 380, ms: 480, className: 'cp-ghost' });
|
||||
setTimeout(() => {
|
||||
bump(seatEl(rv.takenBy), 'shake');
|
||||
const n = v.fronts[rv.takenBy]?.counts[rv.kind] ?? 0;
|
||||
if (!over && n >= v.loseCount - 1) cpSfx.danger();
|
||||
else cpSfx.splat();
|
||||
}, 820);
|
||||
}
|
||||
if (over && !p.over && v.final) {
|
||||
const f = v.final;
|
||||
setTimeout(() => {
|
||||
showBanner(`${f.loser === me ? '내가' : `${nick(players, f.loser)}님`} 패배!`, 'dark', f.losingKind ? `${KIND_KO[f.losingKind]}${hasBatchim(KIND_KO[f.losingKind]) ? '이' : '가'} 너무 많아요` : undefined);
|
||||
cpSfx.danger();
|
||||
bump(seatEl(f.loser), 'shake');
|
||||
}, flip ? 1300 : 0);
|
||||
}
|
||||
if (flip) {
|
||||
const rv = v.lastReveal!;
|
||||
msg = `${nick(players, rv.caller)}님이 ${rv.call === 'true' ? '진짜라고' : '거짓말이라고'} 했고 ${rv.correct ? '맞혔어요' : '틀렸어요'}. ${kj(rv.kind, '은', '는')} ${nick(players, rv.takenBy)}님 앞마당으로 갔어요.`;
|
||||
@@ -779,10 +820,11 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
if (lastSaid > p.said) {
|
||||
const add: Record<string, string> = {};
|
||||
for (const s of v.said) if (s.seq > p.said) add[s.player] = PHRASE_KO[s.phrase];
|
||||
sfx.pop();
|
||||
setBubbles((b) => ({ ...b, ...add }));
|
||||
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in add)))), 3500);
|
||||
}
|
||||
prev.current = { claims: claimsKey, reveal: revealKey, said: lastSaid, waiting: w };
|
||||
prev.current = { claims: claimsKey, reveal: revealKey, said: lastSaid, waiting: w, peek: peekKey, over };
|
||||
if (slide || flip) {
|
||||
setFresh({ slide, flip });
|
||||
const t = setTimeout(() => setFresh({ slide: false, flip: false }), 700);
|
||||
@@ -818,10 +860,34 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 바퀴벌레 포커 sounds on top of the shared palette (synthesized, no files). */
|
||||
const cpSfx = {
|
||||
/** The card slides over with a little scuttle. */
|
||||
sneak: (delay = 0) => {
|
||||
for (let i = 0; i < 4; i++) noise(25, 0.05, delay + i * 45, 'bandpass', 3200 + i * 300, 2);
|
||||
},
|
||||
/** Wrong guess: a sour "bwomp". */
|
||||
wrong: () => {
|
||||
tone(260, 160, 'sawtooth', 0.05, 0, { slideTo: 180 });
|
||||
tone(180, 260, 'sawtooth', 0.05, 150, { slideTo: 110 });
|
||||
},
|
||||
/** The card lands face up in front of someone: a soft "splat". */
|
||||
splat: () => {
|
||||
noise(90, 0.12, 0, 'lowpass', 600);
|
||||
tone(140, 90, 'sine', 0.12, 0, { slideTo: 90 });
|
||||
},
|
||||
/** One more of that critter and you lose (or you just lost). */
|
||||
danger: () => {
|
||||
[880, 660, 880].forEach((f, i) => tone(f, 110, 'square', 0.05, i * 130));
|
||||
tone(110, 400, 'sawtooth', 0.04, 0, { slideTo: 70 });
|
||||
},
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardProps<CockroachView>) {
|
||||
@@ -956,7 +1022,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 +1052,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 +1081,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 +1124,7 @@ function Rules({ options }: { options?: CockroachOptions }) {
|
||||
<p>카드를 앞마당에 놓은 사람이 다음 라운드를 시작해요. 그때 손에 카드가 한 장도 없으면 바로 져요.</p>
|
||||
{o?.eightKindsRule && <p>하우스 룰: 앞마당에 8종을 모두 한 장 이상 모아도 져요.</p>}
|
||||
<p className="muted">
|
||||
시간 안에 고르지 않으면 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
|
||||
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
|
||||
것으로 끝나요.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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월 열끗(국진)을 열끗으로 셀지 쌍피로 셀지 정하는 중이에요. 정하면 이번 판 점수를 계산해요.`);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
/** 고스톱 / 맞고 화면 (docs/games/gostop.md §9). Points are room-only play points. */
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import type { BakKind, CardView, GostopOptions, GostopView, HandCardView, OutcomeView, SeatView, TurnTag } from '@bg/games/gostop';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, Sheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { HwatuCard, type HwatuInfo } from '../../components/cards/HwatuCard';
|
||||
import { ChipIcon } 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, type BannerTone } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -51,7 +52,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). */
|
||||
@@ -152,10 +153,6 @@ const CSS = `
|
||||
background: #dc2626; color: #fff; pointer-events: none; }
|
||||
.gs-hcard .tag.shake { background: #7c3aed; }
|
||||
.gs-hint { margin: 0; text-align: center; font-size: .9rem; color: var(--text-sub); }
|
||||
.gs-flash { position: fixed; left: 50%; top: 36%; transform: translate(-50%, -50%); z-index: 30; pointer-events: none; text-align: center;
|
||||
font-size: 3rem; font-weight: 900; color: #fde047; text-shadow: 0 3px 10px rgba(0,0,0,.7); animation: gs-pop .35s ease-out; white-space: nowrap; }
|
||||
.gs-flash small { display: block; font-size: 1.1rem; color: #fff; }
|
||||
@keyframes gs-pop { from { transform: translate(-50%, -50%) scale(.5); opacity: 0 } to { transform: translate(-50%, -50%) scale(1); opacity: 1 } }
|
||||
.gs-big { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||
.gs-big .btn { min-height: 76px; font-size: 1.3rem; flex-direction: column; gap: 2px; line-height: 1.2; }
|
||||
.gs-big .btn small { font-size: .85rem; font-weight: 600; opacity: .95; }
|
||||
@@ -177,7 +174,6 @@ const CSS = `
|
||||
.gs-me { padding: 6px 4px; }
|
||||
.gs-hand { gap: 4px; }
|
||||
.gs-hcard { border-width: 2px; }
|
||||
.gs-flash { font-size: 2.4rem; }
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -197,9 +193,14 @@ function Card({ c, size = 'sm', className, style }: { c: CardView | null; size?:
|
||||
function CapturedRow({ seat, label }: { seat: SeatView; label: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const groups = (['gwang', 'yeol', 'tti', 'pi'] as const).filter((k) => seat.captured[k].length > 0);
|
||||
if (groups.length === 0) return <span className="small muted">먹은 패 없음</span>;
|
||||
if (groups.length === 0)
|
||||
return (
|
||||
<span className="small muted" data-fx-cap={seat.id}>
|
||||
먹은 패 없음
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<button type="button" className="gs-cap" aria-expanded={open} onClick={() => setOpen(!open)} aria-label={`${label} 먹은 패: ${groups.map((k) => `${KIND_LABEL[k]} ${seat.captured[k].length}장`).join(', ')}. 눌러서 ${open ? '접기' : '펼치기'}`}>
|
||||
<button type="button" className="gs-cap" data-fx-cap={seat.id} aria-expanded={open} onClick={() => setOpen(!open)} aria-label={`${label} 먹은 패: ${groups.map((k) => `${KIND_LABEL[k]} ${seat.captured[k].length}장`).join(', ')}. 눌러서 ${open ? '접기' : '펼치기'}`}>
|
||||
{groups.map((k) => (
|
||||
<span key={k} className="gs-pile">
|
||||
<b>
|
||||
@@ -207,7 +208,9 @@ function CapturedRow({ seat, label }: { seat: SeatView; label: string }) {
|
||||
</b>
|
||||
<span className="gs-pile-cards">
|
||||
{seat.captured[k].map((c) => (
|
||||
<HwatuCard key={c.key} card={c as HwatuInfo} size="sm" />
|
||||
<span key={c.key} data-gs-cap={c.key} style={{ display: 'inline-flex' }}>
|
||||
<HwatuCard card={c as HwatuInfo} size="sm" />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</span>
|
||||
@@ -260,7 +263,7 @@ function SeatBox({ seat, v, players, me, deadline }: { seat: SeatView; v: Gostop
|
||||
const u = userOf(players, seat.id);
|
||||
const active = actorOf(v) === seat.id;
|
||||
return (
|
||||
<li className={`gs-seat${active ? ' turn' : ''}${!seat.participant && v.step !== 'sell' ? ' out' : ''}`} aria-label={`${u.nickname}, 방 점수 ${signed(seat.total)}${seat.isDealer ? ', 선' : ''}${seat.participant ? `, 지금 ${seat.score.total}점, 손패 ${seat.handCount}장` : ''}`}>
|
||||
<li className={`gs-seat${active ? ' turn anim-glow' : ''}${!seat.participant && v.step !== 'sell' ? ' out' : ''}`} data-fx-seat={seat.id} aria-label={`${u.nickname}, 방 점수 ${signed(seat.total)}${seat.isDealer ? ', 선' : ''}${seat.participant ? `, 지금 ${seat.score.total}점, 손패 ${seat.handCount}장` : ''}`}>
|
||||
<div className="gs-head">
|
||||
<Avatar user={u} size={26} />
|
||||
<span className="nm">
|
||||
@@ -308,7 +311,7 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
||||
const pf = v.pendingFlip;
|
||||
return (
|
||||
<div className="gs-table" role="region" aria-label="바닥">
|
||||
<ul className="gs-floor" aria-label="바닥 패(월별)">
|
||||
<ul className="gs-floor" data-fx="gs-floor" aria-label="바닥 패(월별)">
|
||||
{months.map((m) => {
|
||||
const g = v.floor.find((x) => x.month === m);
|
||||
const cls = `gs-slot${g ? ' has' : ''}${g && g.cards.length === 3 ? (g.natural ? ' ppeok natural' : ' ppeok') : ''}`;
|
||||
@@ -316,14 +319,16 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
||||
? `${m}월 ${g.cards.length}장${g.cards.length === 3 ? (g.natural ? ', 처음 깔린 3장' : `, ${nick(players, g.ppeokBy)}님이 싼 뻑`) : ''}: ${g.cards.map((c) => c.name).join(', ')}`
|
||||
: `${m}월 없음`;
|
||||
return (
|
||||
<li key={m} className={cls} aria-label={label}>
|
||||
<li key={m} className={cls} data-gs-month={m} aria-label={label}>
|
||||
<span className="m" aria-hidden>
|
||||
{m}월
|
||||
</span>
|
||||
{g && (
|
||||
<span className="gs-slot-cards">
|
||||
{g.cards.map((c) => (
|
||||
<Card key={c.key} c={c} size={narrow ? 'sm' : 'md'} className={glow.has(c.id) ? 'gs-glow' : undefined} />
|
||||
<span key={c.key} className={glow.has(c.id) ? 'gs-glow' : undefined} data-gs-floor={c.key} style={{ display: 'inline-flex' }}>
|
||||
<HwatuCard card={c as HwatuInfo} size={narrow ? 'sm' : 'md'} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
@@ -333,7 +338,7 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
||||
</ul>
|
||||
<div className="gs-side">
|
||||
<div className="gs-deck">
|
||||
<div aria-label={`더미 ${v.deckCount}장`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
|
||||
<div data-fx="gs-deck" aria-label={`더미 ${v.deckCount}장`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
|
||||
<HwatuCard card={null} size={narrow ? 'sm' : 'md'} />
|
||||
<strong>{v.deckCount}장</strong>
|
||||
</div>
|
||||
@@ -351,7 +356,9 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
||||
{pf && (
|
||||
<div aria-label={`뒤집은 패 ${pf.flipped.name}`} style={{ textAlign: 'center' }}>
|
||||
<div className="small">뒤집은 패</div>
|
||||
<Card c={pf.flipped} size="sm" className="gs-glow" />
|
||||
<span className="gs-glow" data-fx="gs-pflip" style={{ display: 'inline-flex' }}>
|
||||
<HwatuCard card={pf.flipped as HwatuInfo} size="sm" />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -423,8 +430,8 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a
|
||||
setAsk(null);
|
||||
}, [v.turn, v.step, v.roundNo, v.lastTurn?.seq]);
|
||||
const hand = v.myHand ?? [];
|
||||
const send = (a: object) => {
|
||||
sounds.stone();
|
||||
const send = (a: { card: number | 'dummy'; target?: number; shake?: boolean; bomb?: boolean }) => {
|
||||
rememberPlay(a.card);
|
||||
act({ type: 'play', ...a });
|
||||
setLifted(null);
|
||||
setAsk(null);
|
||||
@@ -446,7 +453,7 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a
|
||||
const floorCards = (ids: number[]) => v.floor.flatMap((g) => g.cards).filter((c) => ids.includes(c.id));
|
||||
return (
|
||||
<>
|
||||
<div className="gs-hand" role="group" aria-label="내 손패">
|
||||
<div className="gs-hand" data-fx="gs-hand" role="group" aria-label="내 손패">
|
||||
{hand.map((h) => {
|
||||
const match = hints && h.matches.length > 0;
|
||||
const tag = h.canBomb ? '폭탄' : h.canShake ? '흔들기' : null;
|
||||
@@ -456,6 +463,7 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a
|
||||
key={h.card.key}
|
||||
type="button"
|
||||
className="gs-hcard"
|
||||
data-gs-hand={h.card.key}
|
||||
data-match={match || undefined}
|
||||
data-lifted={lifted === h.card.id || undefined}
|
||||
disabled={!canPlay}
|
||||
@@ -540,7 +548,7 @@ function MyArea(props: BoardProps<GostopView> & { onFocusCard: (h: HandCardView
|
||||
const active = actorOf(v) === me;
|
||||
if (v.phase !== 'playing') return null;
|
||||
return (
|
||||
<div className={`gs-me${active ? ' turn' : ''}`} aria-label="내 자리">
|
||||
<div className={`gs-me${active ? ' turn anim-glow' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||
<div className="gs-head">
|
||||
<Avatar user={userOf(players, me)} size={26} />
|
||||
<span className="nm">나 · 합계 {signed(seat.total)}</span>
|
||||
@@ -672,7 +680,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>
|
||||
@@ -703,7 +711,7 @@ function RoundResult({ view: v, me, players, act, pending }: BoardProps<GostopVi
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
const nextMult = v.rules.nagariMultiplier === 'x2' ? Math.min(2 ** v.nagariStreak, v.rules.nagariMaxMultiplier) : 1;
|
||||
return (
|
||||
<section className="gs-panel gs-res" aria-label={`${v.roundNo}판 결과`} aria-live="polite">
|
||||
<section className="gs-panel gs-res" data-fx="gs-result" aria-label={`${v.roundNo}판 결과`} aria-live="polite">
|
||||
<h2 style={{ margin: 0 }}>
|
||||
{v.roundNo}판 결과 · {outcomeTitle(o, players, me)}
|
||||
</h2>
|
||||
@@ -777,13 +785,336 @@ function RoundResult({ view: v, me, players, act, pending }: BoardProps<GostopVi
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- motion + sound
|
||||
|
||||
/** 고스톱 sounds on top of the shared palette (synthesized, no files). */
|
||||
const gsSfx = {
|
||||
/** "탁!" — a hwatu card slapped on the floor. */
|
||||
slap: (gain = 1, delay = 0) => {
|
||||
noise(70, 0.3 * gain, delay, 'lowpass', 900);
|
||||
noise(22, 0.12 * gain, delay, 'highpass', 3200);
|
||||
tone(120, 90, 'sine', 0.22 * gain, delay, { slideTo: 60 });
|
||||
},
|
||||
/** Cards taken into the pile ("착착"). */
|
||||
gather: (n: number) => {
|
||||
for (let i = 0; i < Math.min(n, 4); i++) noise(45, 0.12, i * 60, 'bandpass', 1700 + i * 200, 1);
|
||||
},
|
||||
/** 쪽 */
|
||||
kiss: () => {
|
||||
tone(1100, 70, 'sine', 0.14, 0, { slideTo: 2300 });
|
||||
noise(25, 0.08, 55, 'highpass', 5000);
|
||||
},
|
||||
/** 뻑 — a dull, deflating thud. */
|
||||
ppeok: () => {
|
||||
noise(140, 0.22, 0, 'lowpass', 500);
|
||||
tone(320, 280, 'sawtooth', 0.06, 0, { slideTo: 90 });
|
||||
},
|
||||
/** 따닥 — two quick slaps. */
|
||||
ttadak: () => {
|
||||
gsSfx.slap(0.9);
|
||||
gsSfx.slap(1, 110);
|
||||
tone(988, 90, 'triangle', 0.08, 200);
|
||||
},
|
||||
/** 싹쓸이 — a broom sweep, then the pile. */
|
||||
sweep: () => {
|
||||
noise(260, 0.12, 0, 'bandpass', 1200, 0.5);
|
||||
sfx.collect();
|
||||
},
|
||||
/** 폭탄 */
|
||||
boom: () => {
|
||||
noise(450, 0.35, 0, 'lowpass', 280);
|
||||
tone(85, 420, 'sine', 0.3, 0, { slideTo: 38 });
|
||||
},
|
||||
/** 흔들기 — cards rattled in the hand. */
|
||||
rattle: () => {
|
||||
for (let i = 0; i < 6; i++) noise(35, 0.12, i * 60, 'bandpass', 2300 + (i % 2) * 700, 3);
|
||||
},
|
||||
/** 고 — rising, one step higher per 고. */
|
||||
go: (n: number) => {
|
||||
const up = Math.min(n, 5) * 60;
|
||||
[523, 659, 784].forEach((f, i) => tone(f + up, 110, 'square', 0.06, i * 70));
|
||||
},
|
||||
nagari: () => [440, 370, 311].forEach((f, i) => tone(f, 200, 'triangle', 0.12, i * 160)),
|
||||
};
|
||||
|
||||
/** Where my last played card was (its button is gone once the view arrives), so the floor card flies from there. */
|
||||
let myPlayRect: DOMRect | null = null;
|
||||
function rememberPlay(card: number | 'dummy'): void {
|
||||
myPlayRect = card === 'dummy' ? null : (document.querySelector(`.gs-hcard[data-gs-hand$="c${card}"]`)?.getBoundingClientRect() ?? null);
|
||||
}
|
||||
|
||||
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
|
||||
const byAttr = (attr: string, key: string | number): Element | null => document.querySelector(`[${attr}="${cssEsc(String(key))}"]`);
|
||||
const slotEl = (month: number) => (month > 0 ? byAttr('data-gs-month', month) : null);
|
||||
const capEl = (id: string) => byAttr('data-fx-cap', id) ?? seatEl(id);
|
||||
const CAP_KINDS = ['gwang', 'yeol', 'tti', 'pi'] as const;
|
||||
|
||||
/** A card turned face up (Web Animations, composite add, so it can run together with a fly-in). */
|
||||
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: 380, delay, easing: 'ease', fill: 'backwards', composite: 'add' },
|
||||
);
|
||||
}
|
||||
|
||||
function capOwners(v: GostopView): Map<string, string> {
|
||||
const m = new Map<string, string>();
|
||||
for (const s of v.seats) for (const k of CAP_KINDS) for (const c of s.captured[k]) m.set(c.key, s.id);
|
||||
return m;
|
||||
}
|
||||
|
||||
const TAG_ORDER: TurnTag[] = ['samPpeok', 'yeonPpeok', 'firstPpeok', 'bomb', 'ttadak', 'jaPpeok', 'ppeokEat', 'ppeok', 'jjok', 'sseul', 'shake', 'bonus', 'bonusFlip'];
|
||||
const TAG_TONE: Partial<Record<TurnTag, BannerTone>> = {
|
||||
samPpeok: 'red', yeonPpeok: 'red', firstPpeok: 'red', ppeok: 'red', bomb: 'red',
|
||||
ttadak: 'gold', jaPpeok: 'gold', ppeokEat: 'gold', jjok: 'gold', sseul: 'green', shake: 'blue', bonus: 'blue', bonusFlip: 'blue',
|
||||
};
|
||||
|
||||
/** Sound (and a shake) for the most important tag of a turn. */
|
||||
function tagFx(tag: TurnTag | undefined, actor: string | null): void {
|
||||
switch (tag) {
|
||||
case 'samPpeok':
|
||||
gsSfx.ppeok();
|
||||
later(250, sfx.fanfare);
|
||||
break;
|
||||
case 'yeonPpeok':
|
||||
case 'firstPpeok':
|
||||
gsSfx.ppeok();
|
||||
later(280, sfx.good);
|
||||
break;
|
||||
case 'ppeok':
|
||||
gsSfx.ppeok();
|
||||
bump(fxEl('gs-floor'), 'shake');
|
||||
break;
|
||||
case 'bomb':
|
||||
gsSfx.boom();
|
||||
bump(fxEl('gs-floor'), 'shake');
|
||||
break;
|
||||
case 'ttadak':
|
||||
gsSfx.ttadak();
|
||||
break;
|
||||
case 'jaPpeok':
|
||||
case 'ppeokEat':
|
||||
sfx.good();
|
||||
break;
|
||||
case 'jjok':
|
||||
gsSfx.kiss();
|
||||
break;
|
||||
case 'sseul':
|
||||
gsSfx.sweep();
|
||||
break;
|
||||
case 'shake':
|
||||
gsSfx.rattle();
|
||||
if (actor) bump(seatEl(actor), 'shake');
|
||||
break;
|
||||
case 'bonus':
|
||||
case 'bonusFlip':
|
||||
sfx.pop();
|
||||
break;
|
||||
default:
|
||||
sfx.capture();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sounds + motion for every change of the table — mine, the other players' and the bots' — by diffing the previous
|
||||
* view: deal, card played (탁), deck card flipped, cards taken into a pile, 피 taken from another pile, 뻑·쪽·따닥·
|
||||
* 싹쓸이·폭탄·흔들기 banners, 고, 광 팔기 and the round result. Nothing on the first render (join / reload / replay),
|
||||
* except the first deal when mounted right at the start of the game.
|
||||
*/
|
||||
function useGostopFx(v: GostopView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
const prev = useRef<GostopView | null>(null);
|
||||
const origin = (id: string | null): Element | DOMRect | null =>
|
||||
!id ? null : id === me ? (myPlayRect ?? fxEl('gs-hand') ?? seatEl(id)) : seatEl(id);
|
||||
|
||||
const deal = () => {
|
||||
const deck = fxEl('gs-deck');
|
||||
sfx.shuffle();
|
||||
later(300, () => sfx.deal(8, 55));
|
||||
document.querySelectorAll('[data-gs-floor]').forEach((el, i) => flyFrom(el, deck, { delay: 300 + i * 45, rotate: 8 }));
|
||||
const mine = document.querySelectorAll('[data-gs-hand]');
|
||||
mine.forEach((el, i) => flyFrom(el, deck, { delay: 300 + i * 40, rotate: 10 }));
|
||||
for (const s of v.seats) {
|
||||
if (s.handCount === 0 || (s.id === me && mine.length > 0)) continue;
|
||||
flyGhost(deck, seatEl(s.id), { kind: 'hwatu', count: 3, gap: 90, delay: 300 });
|
||||
}
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
if (!p) {
|
||||
// Mounted right at the start of the game (nothing played yet): show the deal once.
|
||||
if (v.roundNo === 1 && v.phase === 'playing' && !v.lastTurn && !v.sell?.decisions.length) deal();
|
||||
return;
|
||||
}
|
||||
if (p === v) return;
|
||||
// A new round, or the same round dealt again (총통 다시 돌리기).
|
||||
if (v.roundNo !== p.roundNo || (v.phase === 'playing' && p.phase === 'playing' && v.deckCount > p.deckCount)) {
|
||||
myPlayRect = null;
|
||||
if (v.phase === 'playing') deal();
|
||||
return;
|
||||
}
|
||||
const deck = fxEl('gs-deck');
|
||||
const lt = v.lastTurn;
|
||||
const newTurn = !!lt && lt.seq !== (p.lastTurn?.seq ?? 0);
|
||||
const pendingNew = !!v.pendingFlip && !p.pendingFlip;
|
||||
// The flip that needed a choice: the played card and the flip were already shown with the choice.
|
||||
const resumed = newTurn && !!p.pendingFlip;
|
||||
const actor = newTurn ? lt!.player : (v.pendingFlip?.player ?? p.turn);
|
||||
let bannerShown = false;
|
||||
|
||||
if (newTurn || pendingNew) {
|
||||
const fresh = newTurn && !resumed;
|
||||
const flippedKeys = new Set(fresh ? lt!.flipped.map((c) => c.key) : []);
|
||||
const before = new Set(p.floor.flatMap((g) => g.cards.map((c) => c.key)));
|
||||
const onFloor = new Set<string>();
|
||||
let played = false;
|
||||
let flipped = false;
|
||||
for (const g of v.floor)
|
||||
for (const c of g.cards) {
|
||||
onFloor.add(c.key);
|
||||
if (before.has(c.key)) continue;
|
||||
const el = byAttr('data-gs-floor', c.key);
|
||||
if (flippedKeys.has(c.key)) {
|
||||
flyFrom(el, deck, { delay: 380, ms: 300, rotate: 0, scale: 0.8 });
|
||||
flipIn(el, 380);
|
||||
flipped = true;
|
||||
} else {
|
||||
flyFrom(el, origin(actor), { ms: 340, rotate: -14 });
|
||||
played = true;
|
||||
}
|
||||
}
|
||||
if (fresh) {
|
||||
// Cards that were taken right away never stay on the floor: a copy flies to their month.
|
||||
for (const c of lt!.played) {
|
||||
played = true;
|
||||
if (!onFloor.has(c.key) && c.month > 0) flyGhost(origin(actor), slotEl(c.month), { kind: 'hwatu', ms: 340 });
|
||||
}
|
||||
for (const c of lt!.flipped) {
|
||||
flipped = true;
|
||||
if (!onFloor.has(c.key) && c.month > 0) flyGhost(deck, slotEl(c.month), { kind: 'hwatu', delay: 380, ms: 300 });
|
||||
}
|
||||
// 보너스패: the player takes one more card from the deck.
|
||||
if (lt!.tags.includes('bonus') && actor !== me) flyGhost(deck, seatEl(actor!), { kind: 'hwatu', delay: 300 });
|
||||
}
|
||||
if (pendingNew) {
|
||||
const el = fxEl('gs-pflip');
|
||||
flyFrom(el, deck, { delay: 380, ms: 300, rotate: 0, scale: 0.8 });
|
||||
flipIn(el, 380);
|
||||
flipped = true;
|
||||
played = true;
|
||||
}
|
||||
const bomb = fresh && lt!.tags.includes('bomb');
|
||||
if (played) later(260, () => gsSfx.slap(bomb ? 1.4 : 1));
|
||||
if (flipped) {
|
||||
later(380, sfx.cardFlip);
|
||||
later(640, () => gsSfx.slap(0.6));
|
||||
}
|
||||
|
||||
// Cards that reached a pile: from the floor (their month), the deck or hand (bonus cards), or another pile (피 뺏기).
|
||||
const capAt = resumed ? 120 : 720;
|
||||
const owners = capOwners(p);
|
||||
const robbed = new Set<string>();
|
||||
let got = 0;
|
||||
for (const s of v.seats)
|
||||
for (const k of CAP_KINDS)
|
||||
for (const c of s.captured[k]) {
|
||||
const was = owners.get(c.key);
|
||||
if (was === s.id) continue;
|
||||
const el = byAttr('data-gs-cap', c.key);
|
||||
if (was) {
|
||||
flyFrom(el, capEl(was), { delay: capAt + 250, ms: 420, scale: 0.8, rotate: 0 });
|
||||
robbed.add(was);
|
||||
} else {
|
||||
flyFrom(el, slotEl(c.month) ?? (flippedKeys.has(c.key) ? deck : origin(actor)), { delay: capAt, ms: 400, scale: 0.9, rotate: 0 });
|
||||
got++;
|
||||
}
|
||||
}
|
||||
if (got) later(capAt + 40, () => gsSfx.gather(got));
|
||||
if (robbed.size) {
|
||||
later(capAt + 250, sfx.whoosh);
|
||||
for (const id of robbed) later(capAt + 250, () => bump(seatEl(id), 'shake'));
|
||||
}
|
||||
|
||||
if (newTurn) {
|
||||
const f = flashText(v, players);
|
||||
if (f) {
|
||||
const top = TAG_ORDER.find((x) => lt!.tags.includes(x));
|
||||
later(resumed ? 150 : 600, () => {
|
||||
showBanner(f.big, (top && TAG_TONE[top]) ?? 'blue', f.small);
|
||||
tagFx(top, actor);
|
||||
});
|
||||
bannerShown = true;
|
||||
}
|
||||
}
|
||||
if (actor === me) myPlayRect = null;
|
||||
}
|
||||
|
||||
// My new hand cards during a round (보너스패 draw).
|
||||
if (v.myHand && p.myHand) {
|
||||
const had = new Set(p.myHand.map((h) => h.card.key));
|
||||
v.myHand.filter((h) => !had.has(h.card.key)).forEach((h, i) => flyFrom(byAttr('data-gs-hand', h.card.key), deck, { delay: 300 + i * 60, rotate: 10 }));
|
||||
}
|
||||
|
||||
// 고
|
||||
for (const s of v.seats) {
|
||||
const b = p.seats.find((x) => x.id === s.id);
|
||||
if (!b || s.goCount <= b.goCount) continue;
|
||||
showBanner(`${s.goCount}고!`, 'red', s.id === me ? undefined : `${nick(players, s.id)}님`);
|
||||
gsSfx.go(s.goCount);
|
||||
bump(seatEl(s.id));
|
||||
bannerShown = true;
|
||||
}
|
||||
|
||||
// 광팔기: a player sits out (and shows the cards they sell).
|
||||
for (const d of v.sell?.decisions.slice(p.sell?.decisions.length ?? 0) ?? []) {
|
||||
if (!d.sell) {
|
||||
sfx.select();
|
||||
continue;
|
||||
}
|
||||
const n = v.seats.find((s) => s.id === d.player)?.seller?.shown.length ?? 0;
|
||||
showBanner(n ? '광 팔기!' : '죽기', 'blue', `${nick(players, d.player)}님${n ? ` · 광 ${n}장` : ''}`);
|
||||
if (n) sfx.chips(Math.min(n, 4));
|
||||
else sfx.whoosh();
|
||||
bump(seatEl(d.player));
|
||||
bannerShown = true;
|
||||
}
|
||||
|
||||
// Round result: 스톱 / 총통 / 삼뻑 / 나가리.
|
||||
const o = v.outcome;
|
||||
if (o && !p.outcome) {
|
||||
const at = bannerShown ? 1000 : 0;
|
||||
const who = o.winner === me ? '내가 이겼어요' : `${nick(players, o.winner)}님이 이겼어요`;
|
||||
const nextMult = v.rules.nagariMultiplier === 'x2' ? Math.min(2 ** v.nagariStreak, v.rules.nagariMaxMultiplier) : 1;
|
||||
const mySeat = v.seats.find((s) => s.id === me);
|
||||
later(at, () => {
|
||||
if (o.type === 'nagari') showBanner('나가리', 'dark', nextMult > 1 ? `다음 판 x${nextMult}` : undefined);
|
||||
else showBanner(o.type === 'chongtong' ? '총통!' : o.type === 'samppeok' ? '삼뻑!' : '스톱!', o.type === 'samppeok' ? 'red' : 'gold', who);
|
||||
// The last round: the result dialog already plays the win/lose sound.
|
||||
if (o.type === 'nagari') gsSfx.nagari();
|
||||
else if (v.phase === 'finished' && mySeat) return;
|
||||
else if (o.winner === me) sounds.win();
|
||||
else if (mySeat?.participant) sounds.lose();
|
||||
else sfx.fanfare();
|
||||
});
|
||||
if (o.winner) {
|
||||
const to = seatEl(o.winner) ?? fxEl('gs-result');
|
||||
o.payments.forEach((pay, i) => {
|
||||
if (pay.amount > 0) flyGhost(seatEl(pay.from) ?? fxEl('gs-result'), to, { kind: 'chip', count: 3, gap: 70, delay: at + 250 + i * 120 });
|
||||
});
|
||||
if (o.payments.some((pay) => pay.amount > 0)) later(at + 500, () => sfx.chips(4));
|
||||
}
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function GostopBoard(props: BoardProps<GostopView>) {
|
||||
const { view: v, me, players } = props;
|
||||
const narrow = useNarrow();
|
||||
const [focus, setFocus] = useState<HandCardView | null>(null);
|
||||
const [flash, setFlash] = useState<{ big: string; small: string } | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const mine = isMyTurn(v, me);
|
||||
const prevMine = useRef(false);
|
||||
@@ -796,10 +1127,6 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
`${nick(players, t.player)}님: ${t.played.map((c) => c.name).join(', ')}${t.played.length ? ' 냄, ' : ''}${t.flipped.map((c) => c.name).join(', ')} 뒤집음, ${t.captured.length}장 먹음${f ? `. ${f.big}` : ''}`,
|
||||
);
|
||||
}
|
||||
setFlash(f);
|
||||
if (!f) return undefined;
|
||||
const tm = setTimeout(() => setFlash(null), 1300);
|
||||
return () => clearTimeout(tm);
|
||||
}, [seq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (mine && !prevMine.current && v.phase === 'playing') {
|
||||
@@ -811,10 +1138,11 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
}, [mine]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (v.outcome && v.phase !== 'playing') {
|
||||
if (v.outcome.winner === me) sounds.win();
|
||||
setAnnounce(`${v.roundNo}판 결과: ${outcomeTitle(v.outcome, players, me)}`);
|
||||
}
|
||||
}, [v.roundNo, v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const [banner, showBanner] = useBanner();
|
||||
useGostopFx(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 glow = new Set<number>(v.rules.hints && focus ? focus.matches : []);
|
||||
@@ -831,12 +1159,7 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
<RoundResult {...props} />
|
||||
<MyArea {...props} onFocusCard={setFocus} />
|
||||
<Decisions {...props} />
|
||||
{flash && v.phase === 'playing' && (
|
||||
<div className="gs-flash" aria-hidden>
|
||||
{flash.big}
|
||||
<small>{flash.small}</small>
|
||||
</div>
|
||||
)}
|
||||
{banner}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -1033,12 +1356,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 +1405,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 +1416,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 +1480,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 ? '' : '광팔기 없음',
|
||||
]
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
/** 구십구 화면 (docs/games/ninety-nine.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 { CardFace, CardKind, ChoiceView, HandCardView, LogEntry, NNOptions, NinetyNineView, SeatView } from '@bg/games/ninety-nine';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { PlayingCard } from '../../components/cards/PlayingCard';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, 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 { helpNow, resolvedHandSize } from './help';
|
||||
@@ -148,6 +149,7 @@ const CSS = `
|
||||
.nn-rules td, .nn-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); }
|
||||
.nn-rules .nn-face { width: 34px; height: 48px; --cw: 34px; }
|
||||
.nn-rules .nn-art::before { inset: 3px; }
|
||||
.fx-ghost.nn-ghost { background: #fffdf7; color: #1f2937; border: 2px solid #334155; box-shadow: 0 3px 8px rgba(0,0,0,.35); display: flex; align-items: center; justify-content: center; font: 900 13px/1 system-ui, sans-serif; }
|
||||
@keyframes nn-pop { 0% { transform: scale(.7); } 70% { transform: scale(1.08); } 100% { transform: scale(1); } }
|
||||
@keyframes nn-break { 0% { transform: scale(1); color: #e11d48; opacity: 1; } 40% { transform: scale(1.5) rotate(-15deg); } 100% { transform: scale(1); } }
|
||||
/* PC/tablet: many players stack into even rows (9 → 5 + 4) instead of scrolling sideways. Phones keep one swipeable row. */
|
||||
@@ -239,7 +241,7 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: NinetyNineV
|
||||
const u = userOf(players, s.id);
|
||||
const rank = v.result?.ranking.find((r) => r.player === s.id)?.rank;
|
||||
return (
|
||||
<li className={`nn-seat${s.isTurn ? ' turn' : ''}${s.alive ? '' : ' out'}`} aria-label={seatLabel(s, v, players, me)}>
|
||||
<li className={`nn-seat${s.isTurn ? ' turn anim-glow' : ''}${s.alive ? '' : ' out'}`} data-fx-seat={s.id} aria-label={seatLabel(s, v, players, me)}>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={24} />
|
||||
<span className="nm">{u.nickname}</span>
|
||||
@@ -287,12 +289,12 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor
|
||||
<TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={cur === me} size={40} />
|
||||
</span>
|
||||
)}
|
||||
<span className="nn-chip" aria-label={`뽑을 카드 ${v.drawPileCount}장`}>
|
||||
<span className="nn-chip" data-fx="nn-deck" aria-label={`뽑을 카드 ${v.drawPileCount}장`}>
|
||||
더미 {v.drawPileCount}장
|
||||
</span>
|
||||
{v.livesStart > 0 && <span className="nn-chip">{v.round}판째</span>}
|
||||
</div>
|
||||
<div className="nn-dial" role="img" aria-label={`지금 합계 ${v.total}`}>
|
||||
<div className="nn-dial" data-fx="nn-dial" role="img" aria-label={`지금 합계 ${v.total}`}>
|
||||
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden>
|
||||
<circle cx="50" cy="50" r={r} fill="rgba(0,0,0,.28)" stroke="rgba(255,255,255,.18)" strokeWidth="8" />
|
||||
<circle cx="50" cy="50" r={r} fill="none" stroke={gaugeColor(v.total)} strokeWidth="8" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - frac)} />
|
||||
@@ -396,8 +398,14 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
setNote('');
|
||||
}, [v.turnNo]);
|
||||
const chosen = my.hand.find((c) => c.id === sel) ?? null;
|
||||
// Cards that came to me (refill, a new round): fly in from the draw pile.
|
||||
useNewEntries(my.hand, (c) => c.id, (fresh) => {
|
||||
const deck = fxEl('nn-deck');
|
||||
fresh.forEach((c, i) => flyFrom(document.querySelector(`.nn-card[data-id="${cssEsc(c.id)}"]`), deck, { delay: 120 + i * 70, rotate: 8 }));
|
||||
}, 30);
|
||||
const send = (c: HandCardView, extra: Record<string, unknown> = {}) => {
|
||||
if (pending) return;
|
||||
rememberPlay(c.id);
|
||||
act({ type: 'play', cardId: c.id, ...extra });
|
||||
setSel(null);
|
||||
};
|
||||
@@ -419,6 +427,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
else setSel(null);
|
||||
return;
|
||||
}
|
||||
sfx.select();
|
||||
setSel(c.id);
|
||||
};
|
||||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
@@ -449,7 +458,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="nn-hand" role="group" aria-label="내 카드. 좌우 방향키로 고르고 Enter로 고른 뒤 한 번 더 누르면 내요" onKeyDown={onKey} style={{ '--cw': cw } as CSSProperties}>
|
||||
<div className="nn-hand" data-fx="nn-hand" role="group" aria-label="내 카드. 좌우 방향키로 고르고 Enter로 고른 뒤 한 번 더 누르면 내요" onKeyDown={onKey} style={{ '--cw': cw } as CSSProperties}>
|
||||
{my.hand.map((c) => {
|
||||
const p = previewOf(c);
|
||||
return (
|
||||
@@ -457,6 +466,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
key={c.id}
|
||||
type="button"
|
||||
className="nn-card"
|
||||
data-id={c.id}
|
||||
data-legal={myTurn ? c.legal : undefined}
|
||||
aria-pressed={sel === c.id}
|
||||
aria-label={`${cardAria(c, myTurn)}${sel === c.id && myTurn && single(c) ? '. 한 번 더 누르면 내요' : ''}`}
|
||||
@@ -559,6 +569,8 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps<Nine
|
||||
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
||||
const opps = useSeatRows<HTMLUListElement>(others.length);
|
||||
const meSeat = v.seats.find((s) => s.id === me);
|
||||
const [banner, showBanner] = useBanner();
|
||||
useNinetyNineFx(v, me, players, showBanner);
|
||||
return (
|
||||
<div className="nn">
|
||||
<style>{CSS}</style>
|
||||
@@ -577,10 +589,145 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps<Nine
|
||||
<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 nnSfx = {
|
||||
/** Direction flips: a rising then falling swoop. */
|
||||
reverse: () => {
|
||||
tone(420, 200, 'triangle', 0.09, 0, { slideTo: 880 });
|
||||
tone(880, 200, 'triangle', 0.07, 150, { slideTo: 420 });
|
||||
},
|
||||
/** 홀드 / 0: a short "tock", nothing changes. */
|
||||
hold: () => {
|
||||
tone(600, 60, 'square', 0.04);
|
||||
tone(600, 60, 'square', 0.04, 110);
|
||||
},
|
||||
/** Straight to 99: alarm-ish rising siren. */
|
||||
to99: () => {
|
||||
tone(330, 380, 'sawtooth', 0.05, 0, { slideTo: 990 });
|
||||
tone(990, 160, 'square', 0.05, 380);
|
||||
},
|
||||
/** Total gets close to 99: a quick tense heartbeat. */
|
||||
tense: () => {
|
||||
tone(90, 120, 'sine', 0.2);
|
||||
tone(80, 140, 'sine', 0.16, 180);
|
||||
},
|
||||
/** A life (heart) breaks. */
|
||||
heart: () => {
|
||||
noise(120, 0.1, 0, 'highpass', 2500);
|
||||
tone(660, 300, 'triangle', 0.08, 40, { slideTo: 220 });
|
||||
},
|
||||
};
|
||||
|
||||
/** Where my last played card was (its button is gone once the view arrives), so the ghost starts there. */
|
||||
let myPlayRect: DOMRect | null = null;
|
||||
const rememberPlay = (id: string) => {
|
||||
myPlayRect = document.querySelector(`.nn-card[data-id="${cssEsc(id)}"]`)?.getBoundingClientRect() ?? null;
|
||||
};
|
||||
|
||||
const nnLogKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`;
|
||||
|
||||
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
|
||||
function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
|
||||
const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`);
|
||||
const dealAll = (delay: number) => {
|
||||
const deck = fxEl('nn-deck');
|
||||
later(delay, sfx.shuffle);
|
||||
later(delay + 300, () => sfx.deal(Math.min(8, v.seats.filter((s) => s.alive).length * 2), 60));
|
||||
for (const s of v.seats) if (s.alive && s.id !== me) flyGhost(deck, seatEl(s.id), { count: 3, gap: 90, delay: delay + 280 });
|
||||
};
|
||||
useNewEntries(v.log, nnLogKey, (fresh) => {
|
||||
let t = 0;
|
||||
for (const e of fresh) {
|
||||
const at = t;
|
||||
switch (e.t) {
|
||||
case 'play': {
|
||||
const from = e.p === me ? (myPlayRect ?? fxEl('nn-hand')) : seatEl(e.p);
|
||||
if (e.p === me) myPlayRect = null;
|
||||
flyGhost(from, fxEl('nn-dial'), { delay: at, ms: 380, label: faceName(e.face), className: 'nn-ghost' });
|
||||
later(at + 300, () => {
|
||||
sfx.cardPlay();
|
||||
// (a direction flip sounds from the direction change below)
|
||||
if (e.kind === 'hold' || e.choice === '방향 그대로') nnSfx.hold();
|
||||
if (e.kind === 'to99') nnSfx.to99();
|
||||
else if (e.total >= 90 && e.total > e.from) nnSfx.tense();
|
||||
});
|
||||
if (e.kind === 'to99') later(at + 300, () => showBanner('99!', 'red', `${who(e.p)} 바로 99`));
|
||||
// Refill: the player takes one card from the pile (mine flies in from MyHand).
|
||||
if (v.options.refill && e.p !== me) flyGhost(fxEl('nn-deck'), seatEl(e.p), { delay: at + 420, ms: 380 });
|
||||
t += 160;
|
||||
break;
|
||||
}
|
||||
case 'noCard':
|
||||
showBanner('낼 카드가 없어요!', 'red', who(e.p));
|
||||
later(at, sfx.bad);
|
||||
bump(seatEl(e.p), 'shake');
|
||||
t += 200;
|
||||
break;
|
||||
case 'life':
|
||||
later(at, nnSfx.heart);
|
||||
bump(seatEl(e.p), 'shake');
|
||||
t += 200;
|
||||
break;
|
||||
case 'out':
|
||||
if (e.why === 'noCard') {
|
||||
showBanner('탈락!', 'dark', who(e.p));
|
||||
later(at + 120, sfx.bad);
|
||||
}
|
||||
t += 200;
|
||||
break;
|
||||
case 'round':
|
||||
if (e.round > 1) {
|
||||
dealAll(at + 400);
|
||||
t += 900;
|
||||
}
|
||||
break;
|
||||
case 'reshuffle':
|
||||
later(at, sfx.shuffle);
|
||||
bump(fxEl('nn-deck'), 'shake');
|
||||
break;
|
||||
case 'timeout':
|
||||
later(at, sfx.tick);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
// The total jumps: the dial pops (shakes when it is close to 99).
|
||||
useChange(v.total, (now, before) => {
|
||||
if (now !== before) later(320, () => bump(fxEl('nn-dial'), now >= 90 ? 'shake' : 'pop'));
|
||||
});
|
||||
// Only a card flips it (a new round just resets it to clockwise, which the deal already covers).
|
||||
const round = useRef(v.round);
|
||||
useChange(v.direction, () => {
|
||||
if (round.current !== v.round) return;
|
||||
later(300, nnSfx.reverse);
|
||||
bump(document.querySelector('.nn-dir b'));
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
round.current = v.round;
|
||||
});
|
||||
// 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.phase === 'playing' && v.round === 1 && !v.log.some((e) => e.t === 'play')) {
|
||||
dealAll(0);
|
||||
const deck = fxEl('nn-deck');
|
||||
document.querySelectorAll('.nn-hand .nn-card').forEach((el, i) => flyFrom(el, deck, { delay: 280 + i * 70, rotate: 10 }));
|
||||
}
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function rulesLine(o: NNOptions): string {
|
||||
@@ -686,7 +833,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 +882,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 +937,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 +1019,7 @@ function Rules({ options }: { options?: NNOptions }) {
|
||||
</p>
|
||||
<SpecialTable o={o} />
|
||||
<p className="small muted">
|
||||
시간 안에 내지 않으면 합계가 가장 작아지는 카드를 자동으로 내요. 어린이와 할 때는 조커 0~99를 추천해요. 목숨(하트)은 이 판에서만 쓰는 표시예요.
|
||||
{o.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 내지 않으면'} 합계가 가장 작아지는 카드를 자동으로 내요. 어린이와 할 때는 조커 0~99를 추천해요. 목숨(하트)은 이 판에서만 쓰는 표시예요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** 스플렌더 화면 (docs/games/splendor.md §9). Everything is drawn from the view; art is own CSS/SVG. */
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import type {
|
||||
BuyOption,
|
||||
Color,
|
||||
@@ -17,7 +17,8 @@ import type {
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } 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, useBanner, useChange, useNewEntries } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -50,7 +51,6 @@ const iGa = (w: string) => {
|
||||
};
|
||||
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 reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const emptyTokens = (): Tokens => ({ W: 0, U: 0, G: 0, R: 0, K: 0, gold: 0 });
|
||||
const sum = (t: Partial<Record<TokenColor, number>>) => TOKEN_COLORS.reduce((a, c) => a + (t[c] ?? 0), 0);
|
||||
const costText = (cost: Partial<Record<TokenColor, number>>) =>
|
||||
@@ -93,8 +93,6 @@ const CSS = `
|
||||
.sp-card.can .sp-flag { background: var(--success); color: #fff; }
|
||||
.sp-card.gold .sp-flag { background: #a16207; color: #fff; }
|
||||
.sp-card.empty { background: transparent; border: 2px dashed var(--border); box-shadow: none; cursor: default; display: flex; align-items: center; justify-content: center; color: var(--text-sub); font-size: .8rem; }
|
||||
.sp-card.fresh { animation: sp-in .45s ease-out; }
|
||||
@keyframes sp-in { from { transform: scale(.7) rotate(-4deg); opacity: 0; } to { transform: none; opacity: 1; } }
|
||||
.sp-card.mini { --cw: 62px; --ch: 84px; border-width: 2px; }
|
||||
.sp-back { background: repeating-linear-gradient(45deg, #3b3157, #3b3157 6px, #4a3f6b 6px, #4a3f6b 12px); color: #fff; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; font-weight: 800; }
|
||||
.sp-back.t1 { --bk: #2f5d46; background: repeating-linear-gradient(45deg, #2f5d46, #2f5d46 6px, #3a6d54 6px, #3a6d54 12px); }
|
||||
@@ -176,9 +174,19 @@ button.sp-noble { cursor: pointer; }
|
||||
.sp-mini-cols > span { display: flex; flex-direction: column; align-items: center; background: var(--surface-2); border-radius: 8px; padding: 2px 0; line-height: 1.25; }
|
||||
.sp-badge { display: inline-block; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .74rem; line-height: 1.6; }
|
||||
|
||||
.sp-crown { position: fixed; left: 50%; top: 38%; transform: translate(-50%, -50%); z-index: 30; pointer-events: none; font-size: 2.4rem; font-weight: 900;
|
||||
color: #fde047; text-shadow: 0 3px 10px rgba(0,0,0,.6); animation: sp-pop .6s ease-out both; white-space: nowrap; }
|
||||
@keyframes sp-pop { 0% { transform: translate(-50%, -50%) scale(.4); opacity: 0; } 60% { transform: translate(-50%, -50%) scale(1.12); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); } }
|
||||
|
||||
/* flying copies (card-fx ghosts): gem tokens, cards, card backs, noble tiles */
|
||||
.fx-ghost.sp-fx-gem { border: 3px solid rgba(0,0,0,.35); background: var(--g); color: var(--gt); font-size: 9px; box-shadow: inset 0 0 0 3px rgba(255,255,255,.3), 0 2px 5px rgba(0,0,0,.4); }
|
||||
.fx-ghost.sp-fx-W { --g: #f4f6f9; --gt: #1c1e21; border-color: #8a94a6; } .fx-ghost.sp-fx-U { --g: #2563eb; --gt: #fff; } .fx-ghost.sp-fx-G { --g: #15803d; --gt: #fff; }
|
||||
.fx-ghost.sp-fx-R { --g: #c81e1e; --gt: #fff; } .fx-ghost.sp-fx-K { --g: #23262d; --gt: #fff; border-color: #6b7280; } .fx-ghost.sp-fx-gold { --g: #eab308; --gt: #2b1d00; border-color: #a16207; }
|
||||
.fx-ghost.sp-fx-card { border: 2px solid #cbbf9f; border-radius: 6px; background: linear-gradient(160deg, var(--g, #e8edf3) 0%, #fffaf0 70%); color: #1c1e21;
|
||||
box-shadow: 0 3px 8px rgba(0,0,0,.35); font: 900 15px/1 system-ui, sans-serif; padding: 3px 4px; }
|
||||
.fx-ghost.sp-fx-b-W { --g: #e8edf3; } .fx-ghost.sp-fx-b-U { --g: #c9dcff; } .fx-ghost.sp-fx-b-G { --g: #c8efd3; } .fx-ghost.sp-fx-b-R { --g: #ffd0cc; } .fx-ghost.sp-fx-b-K { --g: #c9ccd3; }
|
||||
.fx-ghost.sp-fx-t1 { background: repeating-linear-gradient(45deg, #2f5d46, #2f5d46 5px, #3a6d54 5px, #3a6d54 10px); border-color: rgba(0,0,0,.3); }
|
||||
.fx-ghost.sp-fx-t2 { background: repeating-linear-gradient(45deg, #7a5a14, #7a5a14 5px, #8a6a20 5px, #8a6a20 10px); border-color: rgba(0,0,0,.3); }
|
||||
.fx-ghost.sp-fx-t3 { background: repeating-linear-gradient(45deg, #34407a, #34407a 5px, #404d8c 5px, #404d8c 10px); border-color: rgba(0,0,0,.3); }
|
||||
.fx-ghost.sp-fx-noble { border: 2px solid #b08d3c; border-radius: 8px; background: linear-gradient(135deg, #fff4d1, #f2d79a); box-shadow: 0 3px 10px rgba(0,0,0,.35);
|
||||
display: flex; align-items: center; justify-content: center; font-size: 20px; }
|
||||
.sp-help { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: .9rem; }
|
||||
.sp-help b { background: var(--primary-soft); border-radius: 8px; padding: 2px 8px; }
|
||||
|
||||
@@ -210,7 +218,7 @@ button.sp-noble { cursor: pointer; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.sp-card, .sp-token { transition: none; }
|
||||
.sp-card.fresh, .sp-token.shake, .sp-crown { animation: none; }
|
||||
.sp-token.shake { animation: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -321,7 +329,7 @@ function CardBack({ tier, n, label }: { tier: Tier; n?: number; label?: string }
|
||||
);
|
||||
}
|
||||
|
||||
function NobleTile({ noble, need, onClick, pick }: { noble: Noble; need?: number; onClick?: () => void; pick?: boolean }) {
|
||||
function NobleTile({ noble, need, onClick, pick, fx }: { noble: Noble; need?: number; onClick?: () => void; pick?: boolean; fx?: boolean }) {
|
||||
const name = NOBLE_NAME[noble.id] ?? `귀족 ${Number(noble.id.slice(1))}`;
|
||||
const req = COLORS.filter((c) => noble.req[c] > 0);
|
||||
const label = `${name}, ${noble.points}점, 필요한 보너스 ${req.map((c) => `${SHORT[c]} ${noble.req[c]}`).join(' ')}${need !== undefined ? `, 남은 보너스 ${need}` : ''}`;
|
||||
@@ -362,7 +370,7 @@ function NobleTile({ noble, need, onClick, pick }: { noble: Noble; need?: number
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<div className="sp-noble" role="img" aria-label={label}>
|
||||
<div className="sp-noble" role="img" aria-label={label} data-fx-noble={fx ? noble.id : undefined}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
@@ -384,7 +392,6 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
const [back, setBack] = useState<Tokens>(emptyTokens);
|
||||
const [msg, setMsg] = useState<{ text: string; bad: boolean } | null>(null);
|
||||
const [shake, setShake] = useState<{ c: TokenColor; n: number } | null>(null);
|
||||
const [crown, setCrown] = useState<string | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [openOpp, setOpenOpp] = useState<string | null>(null);
|
||||
const [askPass, setAskPass] = useState(false);
|
||||
@@ -397,8 +404,8 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
});
|
||||
const prevTurn = useRef(v.turnSeq);
|
||||
const prevLog = useRef(v.log.at(-1)?.n ?? 0);
|
||||
const prevBoard = useRef<Record<string, string | null>>({});
|
||||
const [fresh, setFresh] = useState<Set<string>>(new Set());
|
||||
const [banner, showBanner] = useBanner();
|
||||
useSplendorFx(v, me, players, showBanner);
|
||||
|
||||
// Reset local choices whenever the turn or phase moves on.
|
||||
useEffect(() => {
|
||||
@@ -419,45 +426,16 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
}
|
||||
}, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// New log lines → screen reader text, sounds, noble crown.
|
||||
// New log lines → screen reader text (sounds and motion: useSplendorFx).
|
||||
useEffect(() => {
|
||||
const last = prevLog.current;
|
||||
const news = v.log.filter((e) => e.n > last);
|
||||
prevLog.current = v.log.at(-1)?.n ?? last;
|
||||
if (!news.length || last === 0) return;
|
||||
setAnnounce(news.map((e) => logText(e, players, me)).join(' '));
|
||||
if (news.some((e) => e.k === 'buy' || e.k === 'take')) sounds.stone();
|
||||
const noble = news.find((e) => e.k === 'noble');
|
||||
if (noble && noble.k === 'noble') {
|
||||
setCrown(`👑 ${noble.p === me ? '나에게' : `${nick(players, noble.p)}님에게`} ${NOBLE_NAME[noble.nobleId] ?? '귀족'} 방문!`);
|
||||
haptic([60, 40, 60]);
|
||||
}
|
||||
if (news.some((e) => e.k === 'noble')) haptic([60, 40, 60]);
|
||||
}, [v.log]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!crown) return;
|
||||
const t = setTimeout(() => setCrown(null), reducedMotion() ? 2200 : 1500);
|
||||
return () => clearTimeout(t);
|
||||
}, [crown]);
|
||||
|
||||
// Newly revealed board cards get a short entrance animation.
|
||||
useEffect(() => {
|
||||
const now: Record<string, string | null> = {};
|
||||
const changed = new Set<string>();
|
||||
for (const t of TIERS_DOWN)
|
||||
v.board[t].forEach((c, i) => {
|
||||
const k = `b${t}-${i}`;
|
||||
now[k] = c?.id ?? null;
|
||||
if (prevBoard.current[k] !== undefined && prevBoard.current[k] !== now[k] && c) changed.add(k);
|
||||
});
|
||||
prevBoard.current = now;
|
||||
if (changed.size) {
|
||||
setFresh(changed);
|
||||
const t = setTimeout(() => setFresh(new Set()), 600);
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [v.board]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!shake) return;
|
||||
const t = setTimeout(() => setShake(null), 400);
|
||||
@@ -480,18 +458,26 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
setManual(null);
|
||||
if (v.supply[c] <= 0) return refuse(c, '남아 있지 않은 색이에요.');
|
||||
setMsg(null);
|
||||
if (same) return setPicks([c]);
|
||||
if (same) {
|
||||
sfx.select();
|
||||
return setPicks([c]);
|
||||
}
|
||||
if (picks.length === 1 && picks[0] === c) {
|
||||
if (my?.takeSame.includes(c)) {
|
||||
sfx.select();
|
||||
setPicks([c, c]);
|
||||
setMsg({ text: `${NAME[c]} 2개를 가져와요.`, bad: false });
|
||||
return;
|
||||
}
|
||||
return refuse(c, '같은 색 2개는 4개 이상 남은 색에서만 가져올 수 있어요.');
|
||||
}
|
||||
if (picks.includes(c)) return setPicks(picks.filter((x) => x !== c));
|
||||
if (picks.includes(c)) {
|
||||
sfx.click();
|
||||
return setPicks(picks.filter((x) => x !== c));
|
||||
}
|
||||
if (takeCount === 0) return refuse(c, '서로 다른 색 보석은 가져올 수 없어요.');
|
||||
if (picks.length >= takeCount) return refuse(c, `서로 다른 색은 ${takeCount}개까지 골라요.`);
|
||||
sfx.select();
|
||||
setPicks([...picks, c]);
|
||||
};
|
||||
const take = () => {
|
||||
@@ -517,7 +503,10 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
setPicks([]);
|
||||
setManual(null);
|
||||
setMsg(null);
|
||||
setSel(sel && selKey(sel) === selKey(s) ? null : s);
|
||||
const off = !!sel && selKey(sel) === selKey(s);
|
||||
if (off) sfx.click();
|
||||
else sfx.select();
|
||||
setSel(off ? null : s);
|
||||
};
|
||||
const payment = manual ?? buyOpt?.payment ?? null;
|
||||
const deckSel = sel?.kind === 'deck' ? sel : null;
|
||||
@@ -558,6 +547,8 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
if (next[c] >= mine.tokens[c]) return;
|
||||
next[c]++;
|
||||
} else if (next[c] > 0) next[c]--;
|
||||
else return;
|
||||
sfx.select();
|
||||
setMsg(null);
|
||||
setBack(next);
|
||||
};
|
||||
@@ -565,7 +556,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
const cardClass = (key: string, extra = '') => {
|
||||
const opt = my?.buy[key];
|
||||
const hl = hints && opt && !mine?.conceded ? (opt.gold > 0 ? ' gold' : ' can') : '';
|
||||
return `sp-card${hl}${sel && selKey(sel) === key ? ' sel' : ''}${fresh.has(key) ? ' fresh' : ''}${extra}`;
|
||||
return `sp-card${hl}${sel && selKey(sel) === key ? ' sel' : ''}${extra}`;
|
||||
};
|
||||
const cardAria = (card: DevCard, key: string) => {
|
||||
const opt = my?.buy[key];
|
||||
@@ -595,7 +586,8 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
key={p}
|
||||
type="button"
|
||||
role="listitem"
|
||||
className={`sp-chip${v.current === p ? ' turn' : ''}`}
|
||||
className={`sp-chip${v.current === p ? ` turn${v.phase !== 'finished' ? ' anim-glow' : ''}` : ''}`}
|
||||
data-fx-seat={p}
|
||||
aria-expanded={openOpp === p}
|
||||
aria-label={`${nick(players, p)} ${pv.points}점, 보석 ${pv.tokenCount}개, 카드 ${pv.cards.length}장, 예약 ${pv.reservedCount}장${v.current === p ? ', 지금 차례' : ''}. 누르면 자세히 보여요`}
|
||||
onClick={() => setOpenOpp(openOpp === p ? null : p)}
|
||||
@@ -640,9 +632,9 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
</div>
|
||||
)}
|
||||
<div className="sp-table">
|
||||
<section className="sp-nobles" aria-label={`귀족 ${v.nobles.length}명`}>
|
||||
<section className="sp-nobles" aria-label={`귀족 ${v.nobles.length}명`} data-fx="sp-nobles">
|
||||
{v.nobles.map((n) => (
|
||||
<NobleTile key={n.id} noble={n} need={hints && my ? my.nobleNeed[n.id] : undefined} />
|
||||
<NobleTile key={n.id} noble={n} need={hints && my ? my.nobleNeed[n.id] : undefined} fx />
|
||||
))}
|
||||
{v.nobles.length === 0 && <span className="small muted">남은 귀족이 없어요</span>}
|
||||
</section>
|
||||
@@ -652,6 +644,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
<button
|
||||
type="button"
|
||||
className={`sp-deck sp-back t${t}${sel?.kind === 'deck' && sel.tier === t ? ' sel' : ''}`}
|
||||
data-fx={`sp-deck-${t}`}
|
||||
disabled={v.deckCounts[t] === 0}
|
||||
aria-label={`${t}단계 더미 ${v.deckCounts[t]}장${my?.reserveDecks.includes(t) ? '. 누르면 안 보고 예약할 수 있어요' : ''}`}
|
||||
onClick={() => choose({ kind: 'deck', tier: t })}
|
||||
@@ -662,12 +655,12 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
const key = `b${t}-${i}`;
|
||||
if (!card)
|
||||
return (
|
||||
<div key={key} className="sp-card empty" aria-label="빈 칸">
|
||||
<div key={key} className="sp-card empty" aria-label="빈 칸" data-fx={`sp-slot-${key}`}>
|
||||
빈 칸
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<button key={key} type="button" className={cardClass(key)} data-b={card.bonus} aria-label={cardAria(card, key)} aria-pressed={sel ? selKey(sel) === key : false} onClick={() => choose({ kind: 'board', tier: t, slot: i })}>
|
||||
<button key={key} type="button" className={cardClass(key)} data-b={card.bonus} data-fx={`sp-slot-${key}`} aria-label={cardAria(card, key)} aria-pressed={sel ? selKey(sel) === key : false} onClick={() => choose({ kind: 'board', tier: t, slot: i })}>
|
||||
<CardFace card={card} />
|
||||
{flag(key)}
|
||||
</button>
|
||||
@@ -687,6 +680,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
type="button"
|
||||
className={`sp-token${n === 0 ? ' out' : ''}${count ? ' picked' : ''}${count === 2 ? ' picked2' : ''}${shake?.c === c ? ' shake' : ''}`}
|
||||
data-c={c}
|
||||
data-fx={`sp-bank-${c}`}
|
||||
disabled={isGold || !acting}
|
||||
aria-pressed={!isGold && acting ? count > 0 : undefined}
|
||||
aria-label={`${NAME[c]} ${n}개 남음${count ? `, ${count}개 고름` : ''}${isGold ? ' (예약하면 1개 받아요)' : ''}`}
|
||||
@@ -876,16 +870,224 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{crown && (
|
||||
<div className="sp-crown" aria-hidden>
|
||||
{crown}
|
||||
</div>
|
||||
)}
|
||||
{banner}
|
||||
{askPass && <ConfirmSheet title="차례를 넘길까요?" body="지금은 할 수 있는 행동이 없어요." confirm="넘기기" onConfirm={() => act({ type: 'PASS' })} onClose={() => setAskPass(false)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- motion + sound
|
||||
|
||||
/** 스플렌더 sounds on top of the shared palette (synthesized; `delay` in ms). */
|
||||
const spSfx = {
|
||||
/** Glassy gem "clink" (bank → player). */
|
||||
clink: (delay = 0, i = 0) => {
|
||||
const f = 2350 + (i % 4) * 170;
|
||||
tone(f, 70, 'triangle', 0.08, delay);
|
||||
tone(f * 1.5, 130, 'sine', 0.035, delay + 6);
|
||||
},
|
||||
/** Gems put back on the bank: lower and softer. */
|
||||
clack: (delay = 0, i = 0) => {
|
||||
tone(1500 + (i % 3) * 110, 60, 'triangle', 0.06, delay);
|
||||
noise(25, 0.05, delay, 'highpass', 5000);
|
||||
},
|
||||
/** A development card bought: card slide + "ka-ching". */
|
||||
buy: (delay = 0) => {
|
||||
noise(80, 0.15, delay, 'bandpass', 1600, 0.9);
|
||||
tone(784, 90, 'triangle', 0.1, delay + 40);
|
||||
tone(1175, 170, 'triangle', 0.1, delay + 120);
|
||||
},
|
||||
/** A card put aside (reserved). */
|
||||
reserve: (delay = 0) => {
|
||||
noise(90, 0.14, delay, 'bandpass', 2200, 0.8);
|
||||
tone(660, 90, 'triangle', 0.08, delay + 50);
|
||||
tone(520, 120, 'triangle', 0.06, delay + 120);
|
||||
},
|
||||
gold: (delay = 0) => {
|
||||
tone(1318, 70, 'square', 0.05, delay);
|
||||
tone(1976, 160, 'square', 0.05, delay + 70);
|
||||
},
|
||||
/** New market card turned face up. */
|
||||
flip: (delay = 0) => {
|
||||
noise(60, 0.12, delay, 'highpass', 2500);
|
||||
tone(1400, 40, 'triangle', 0.05, delay + 10);
|
||||
},
|
||||
/** Noble visit: a little bell chime. */
|
||||
noble: (delay = 0) => [1047, 1319, 1568, 2093].forEach((f, i) => tone(f, 420, 'sine', 0.1, delay + i * 110)),
|
||||
};
|
||||
|
||||
const isShown = (el: Element | null | undefined): el is Element => {
|
||||
if (!el) return false;
|
||||
const r = el.getBoundingClientRect();
|
||||
return r.width > 0 || r.height > 0;
|
||||
};
|
||||
/** A player's place on screen: my area, else the first visible seat (side list on wide screens, chip on narrow ones). */
|
||||
function seatOf(p: string, me: string | null): Element | null {
|
||||
if (p === me) {
|
||||
const m = fxEl('sp-mine');
|
||||
if (isShown(m)) return m;
|
||||
}
|
||||
for (const el of document.querySelectorAll(`[data-fx-seat="${cssEsc(p)}"]`)) if (isShown(el)) return el;
|
||||
return null;
|
||||
}
|
||||
/** Where a player's colour `c` is shown (my column, an opponent's mini column), else their seat. */
|
||||
function gemSpot(p: string, c: TokenColor, me: string | null): Element | null {
|
||||
if (p === me) {
|
||||
const el = fxEl(`sp-tok-${c}`);
|
||||
if (isShown(el)) return el;
|
||||
}
|
||||
const seat = seatOf(p, me);
|
||||
const col = seat?.querySelector(`[data-fx-tok="${c}"]`);
|
||||
return isShown(col) ? col : seat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sounds + motion for every change of the table, mine or anyone else's (new log entries and board diffs since the
|
||||
* previous view). Nothing on the first render (join, reload, replay jump).
|
||||
*/
|
||||
function useSplendorFx(v: SplendorView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
|
||||
// Board of the previous view (slot key → card id) to know where a bought / reserved card was.
|
||||
const prevBoard = useRef<Record<string, string | null> | null>(null);
|
||||
// Nobles and my reserved cards disappear from the DOM with the new view: remember their rects while the DOM still
|
||||
// shows the previous view (render phase, only when the log moved).
|
||||
const snap = useRef<{ n: number; rects: Map<string, DOMRect> }>({ n: -1, rects: new Map() });
|
||||
const tail = v.log.at(-1)?.n ?? 0;
|
||||
if (snap.current.n !== tail && typeof document !== 'undefined') {
|
||||
const rects = new Map<string, DOMRect>();
|
||||
document.querySelectorAll('[data-fx-noble], [data-fx="sp-reserved"] [data-fx-res]').forEach((el) => {
|
||||
const id = el.getAttribute('data-fx-noble');
|
||||
rects.set(id ? `n:${id}` : `r:${el.getAttribute('data-fx-res')}`, el.getBoundingClientRect());
|
||||
});
|
||||
snap.current = { n: tail, rects };
|
||||
}
|
||||
|
||||
const gemsFly = (tokens: Partial<Tokens>, p: string, toBank: boolean, at: number) => {
|
||||
let i = 0;
|
||||
for (const c of TOKEN_COLORS) {
|
||||
const n = Math.min(tokens[c] ?? 0, 6);
|
||||
if (!n) continue;
|
||||
const bank = fxEl(`sp-bank-${c}`);
|
||||
const spot = gemSpot(p, c, me);
|
||||
flyGhost(toBank ? spot : bank, toBank ? bank : spot, { kind: 'chip', count: n, gap: 80, delay: at + i * 80, ms: 420, label: SHORT[c], className: `sp-fx-gem sp-fx-${c}` });
|
||||
for (let k = 0; k < n; k++) (toBank ? spSfx.clack : spSfx.clink)(at + (i + k) * 80 + (toBank ? 380 : 120), i + k);
|
||||
i += n;
|
||||
}
|
||||
return i;
|
||||
};
|
||||
|
||||
useNewEntries(
|
||||
v.log,
|
||||
(e) => e.n,
|
||||
(fresh) => {
|
||||
const board = prevBoard.current ?? {};
|
||||
const slotOf = (id: string) => Object.keys(board).find((k) => board[k] === id);
|
||||
let t = 0;
|
||||
for (const e of fresh) {
|
||||
const at = t;
|
||||
switch (e.k) {
|
||||
case 'take':
|
||||
gemsFly(e.tokens, e.p, false, at);
|
||||
t += 200;
|
||||
break;
|
||||
case 'discard':
|
||||
gemsFly(e.tokens, e.p, true, at);
|
||||
t += 200;
|
||||
break;
|
||||
case 'buy': {
|
||||
const bonus = e.cardId[1] as Color;
|
||||
const to = gemSpot(e.p, bonus, me);
|
||||
const slot = e.fromReserve ? undefined : slotOf(e.cardId);
|
||||
const from: Element | DOMRect | null = slot
|
||||
? fxEl(`sp-slot-${slot}`)
|
||||
: e.fromReserve && e.p === me
|
||||
? (snap.current.rects.get(`r:${e.cardId}`) ?? fxEl('sp-reserved'))
|
||||
: seatOf(e.p, me);
|
||||
flyGhost(from, to, { kind: 'card', delay: at, ms: 520, className: `sp-fx-card sp-fx-b-${bonus}` });
|
||||
later(at + 480, () => bump(to));
|
||||
spSfx.buy(at);
|
||||
const paid = sum(e.paid);
|
||||
if (paid) gemsFly(e.paid, e.p, true, at + 120);
|
||||
t += 300 + Math.min(paid, 6) * 40;
|
||||
break;
|
||||
}
|
||||
case 'reserve': {
|
||||
const slot = e.cardId ? slotOf(e.cardId) : undefined;
|
||||
const from = slot ? fxEl(`sp-slot-${slot}`) : fxEl(`sp-deck-${e.tier}`);
|
||||
const look = e.cardId ? `sp-fx-b-${e.cardId[1]}` : `sp-fx-t${e.tier}`;
|
||||
const mineEls = e.p === me ? document.querySelectorAll('[data-fx="sp-reserved"] [data-fx-res]') : null;
|
||||
const newCard = mineEls?.length ? mineEls[mineEls.length - 1] : null;
|
||||
if (newCard && isShown(newCard)) flyFrom(newCard, from, { delay: at, ms: 460, rotate: -8 });
|
||||
else flyGhost(from, e.p === me ? fxEl('sp-reserved') : seatOf(e.p, me), { kind: 'card', delay: at, ms: 500, className: `sp-fx-card ${look}` });
|
||||
spSfx.reserve(at);
|
||||
if (e.gold) {
|
||||
flyGhost(fxEl('sp-bank-gold'), gemSpot(e.p, 'gold', me), { kind: 'chip', delay: at + 180, ms: 420, label: SHORT.gold, className: 'sp-fx-gem sp-fx-gold' });
|
||||
spSfx.gold(at + 520);
|
||||
}
|
||||
t += 300;
|
||||
break;
|
||||
}
|
||||
case 'noble': {
|
||||
const from = snap.current.rects.get(`n:${e.nobleId}`) ?? fxEl('sp-nobles');
|
||||
const at2 = at + 150;
|
||||
flyGhost(from, seatOf(e.p, me), { kind: 'card', delay: at2, ms: 560, label: '👑', className: 'sp-fx-noble' });
|
||||
later(at2, () => showBanner('👑 귀족 방문!', 'gold', `${NOBLE_NAME[e.nobleId] ?? '귀족'} → ${e.p === me ? '나' : `${nick(players, e.p)}님`} (+3점)`));
|
||||
spSfx.noble(at2);
|
||||
later(at2 + 560, () => bump(seatOf(e.p, me)));
|
||||
t += 700;
|
||||
break;
|
||||
}
|
||||
case 'end':
|
||||
// The game may already be over (last turn of the round): the finish banner below covers it.
|
||||
if (v.phase !== 'finished')
|
||||
later(at, () => {
|
||||
showBanner('🏁 마지막 라운드!', 'blue', `${e.p === me ? '내가' : `${nick(players, e.p)}님이`} ${e.points}점에 도달했어요`);
|
||||
sfx.fanfare();
|
||||
});
|
||||
t += 900;
|
||||
break;
|
||||
case 'pass':
|
||||
later(at, sfx.whoosh);
|
||||
break;
|
||||
case 'concede':
|
||||
later(at, sfx.bad);
|
||||
bump(seatOf(e.p, me), 'shake');
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Market refill: the new card deals in from its deck and turns face up.
|
||||
useLayoutEffect(() => {
|
||||
const now: Record<string, string | null> = {};
|
||||
for (const t of TIERS_DOWN) v.board[t].forEach((c, i) => (now[`b${t}-${i}`] = c?.id ?? null));
|
||||
const before = prevBoard.current;
|
||||
prevBoard.current = now;
|
||||
if (!before) return;
|
||||
let n = 0;
|
||||
for (const t of TIERS_DOWN)
|
||||
v.board[t].forEach((c, i) => {
|
||||
const k = `b${t}-${i}`;
|
||||
if (!c || before[k] === c.id || before[k] === undefined) return;
|
||||
const delay = 260 + n * 120;
|
||||
flyFrom(fxEl(`sp-slot-${k}`), fxEl(`sp-deck-${t}`), { delay, ms: 420, rotate: 8, scale: 0.7 });
|
||||
spSfx.flip(delay + 380);
|
||||
n++;
|
||||
});
|
||||
}, [v.board]);
|
||||
|
||||
// Game over (results and win/lose sounds come from the room page; this is the on-board moment).
|
||||
useChange(v.phase, (now) => {
|
||||
if (now !== 'finished' || !v.result) return;
|
||||
const w = v.result.winners;
|
||||
const sub = w.length ? (w.includes(me ?? '') && w.length === 1 ? '내가 이겼어요!' : `${w.map((p) => nick(players, p)).join(', ')}님 승리`) : undefined;
|
||||
later(700, () => showBanner('게임 끝', 'gold', sub));
|
||||
});
|
||||
}
|
||||
|
||||
function MyArea({
|
||||
v,
|
||||
pv,
|
||||
@@ -907,7 +1109,7 @@ function MyArea({
|
||||
}) {
|
||||
const turn = v.current === me;
|
||||
return (
|
||||
<section className="sp-mine" aria-label="내 자리" style={{ border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}>
|
||||
<section className={`sp-mine${turn && v.phase !== 'finished' ? ' anim-glow' : ''}`} aria-label="내 자리" data-fx="sp-mine" style={{ border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}>
|
||||
<div className="sp-mine-head">
|
||||
<strong>
|
||||
나 · <span style={{ fontSize: '1.2rem' }}>{pv.points}점</span>
|
||||
@@ -919,7 +1121,7 @@ function MyArea({
|
||||
</div>
|
||||
<div className="sp-cols" role="list" aria-label="색별 보너스와 보석">
|
||||
{TOKEN_COLORS.map((c) => (
|
||||
<div key={c} className="sp-col" role="listitem" aria-label={c === 'gold' ? `황금 ${pv.tokens.gold}개` : `${NAME[c]}: 보너스 ${pv.bonuses[c as Color]}, 보석 ${pv.tokens[c]}개`}>
|
||||
<div key={c} className="sp-col" data-fx={`sp-tok-${c}`} role="listitem" aria-label={c === 'gold' ? `황금 ${pv.tokens.gold}개` : `${NAME[c]}: 보너스 ${pv.bonuses[c as Color]}, 보석 ${pv.tokens[c]}개`}>
|
||||
<Gem c={c} size={20} />
|
||||
<span className="bn" aria-hidden>
|
||||
{c === 'gold' ? '황금' : `할인 ${pv.bonuses[c as Color]}`}
|
||||
@@ -930,14 +1132,14 @@ function MyArea({
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="sp-reserved" role="group" aria-label={`내 예약 카드 ${pv.reservedCount}장`}>
|
||||
<div className="sp-reserved" role="group" aria-label={`내 예약 카드 ${pv.reservedCount}장`} data-fx="sp-reserved">
|
||||
<span className="small muted">예약 {pv.reservedCount}/3</span>
|
||||
{pv.reserved.map((r, i) => {
|
||||
if (r.hidden) return null;
|
||||
const card = r as Extract<ReservedView, { hidden: false }>;
|
||||
const key = `r${i}`;
|
||||
return (
|
||||
<button key={key} type="button" className={cardClass(key, ' mini')} data-b={card.bonus} aria-label={`예약 카드: ${cardAria(card, key)}${card.blind ? ' (더미에서 안 보고 예약)' : ''}`} aria-pressed={sel ? selKey(sel) === key : false} onClick={() => onPick(i)}>
|
||||
<button key={key} type="button" className={cardClass(key, ' mini')} data-b={card.bonus} data-fx-res={card.id} aria-label={`예약 카드: ${cardAria(card, key)}${card.blind ? ' (더미에서 안 보고 예약)' : ''}`} aria-pressed={sel ? selKey(sel) === key : false} onClick={() => onPick(i)}>
|
||||
<CardFace card={card} />
|
||||
{flag(key)}
|
||||
</button>
|
||||
@@ -954,7 +1156,7 @@ function PlayerDetail({ pv, name }: { pv: SplendorPlayerView; name: string }) {
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<div className="sp-mini-cols" role="list" aria-label={`${name}의 보너스와 보석`}>
|
||||
{TOKEN_COLORS.map((c) => (
|
||||
<span key={c} role="listitem" aria-label={c === 'gold' ? `황금 ${pv.tokens.gold}개` : `${NAME[c]} 보너스 ${pv.bonuses[c as Color]}, 보석 ${pv.tokens[c]}개`}>
|
||||
<span key={c} role="listitem" data-fx-tok={c} aria-label={c === 'gold' ? `황금 ${pv.tokens.gold}개` : `${NAME[c]} 보너스 ${pv.bonuses[c as Color]}, 보석 ${pv.tokens[c]}개`}>
|
||||
<Gem c={c} size={15} />
|
||||
<span aria-hidden>{c === 'gold' ? '-' : `+${pv.bonuses[c as Color]}`}</span>
|
||||
<strong aria-hidden>{pv.tokens[c]}</strong>
|
||||
@@ -1029,7 +1231,7 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps<Splend
|
||||
const pv = v.players[p]!;
|
||||
const turn = v.current === p;
|
||||
return (
|
||||
<div key={p} className={`sp-player${turn ? ' turn' : ''}${pv.conceded ? ' gone' : ''}`}>
|
||||
<div key={p} className={`sp-player${turn ? ` turn${v.phase !== 'finished' ? ' anim-glow' : ''}` : ''}${pv.conceded ? ' gone' : ''}`} data-fx-seat={p}>
|
||||
<div className="row" style={{ gap: 8, flexWrap: 'nowrap' }}>
|
||||
<span className="muted small" style={{ width: 14 }} title={i === 0 ? '선 플레이어' : undefined}>
|
||||
{i === 0 ? '선' : i + 1}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user