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

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

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

View File

@@ -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>