루미큐브·다빈치 코드·마작·라스베가스·부루마불·요트 다이스 소리·애니메이션: 상대·컴퓨터 행동도 화면 변화로 한 번만 울림(처음 들어올 때·재접속은 조용), 타일 놓기·뒤집기, 주사위 굴림, 말 한 칸씩 이동, 점수 통 튀기, 큰 순간 배너

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 13:09:19 +09:00
parent 1b4c80a2df
commit a6ace5b5e8
8 changed files with 1557 additions and 273 deletions

View File

@@ -1,12 +1,12 @@
/** 루미큐브 화면 (docs/games/rummikub.md §9). Tap a tile to pick it up, then tap where it goes. */
import { useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
// Pure tile/set helpers only (no zod): keeps this lazy chunk small.
import { findMeld, normalizeSet, pickDisjoint, setProblem, sortTiles, tileLabel, tileOf, type DraftSet, type JokerAs, type TileColor } from '@bg/games/rummikub/rules';
import type { LogEntry, RummikubOptions, RummikubView } from '@bg/games/rummikub';
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 type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
@@ -17,8 +17,67 @@ const userOf = (players: Record<string, PublicUser>, id: string): PublicUser =>
/** Colour + shape mark so colours never have to be told apart by hue alone (§9). */
const MARK: Record<TileColor, string> = { K: '●', R: '♥', B: '◆', O: '★' };
/** Plastic-tile sounds (synthesized; the site volume is applied by feedback.ts). */
const snd = {
/** Tile picked up: a light tick. */
pick: () => {
noise(22, 0.07, 0, 'highpass', 5200);
tone(2300, 26, 'triangle', 0.05);
},
/** Tile put down on the table / rack: short hard "딱". */
place: (delay = 0) => {
noise(32, 0.16, delay, 'bandpass', 3300, 2.4);
tone(1550, 28, 'triangle', 0.07, delay);
tone(430, 45, 'sine', 0.06, delay + 4);
},
/** Several tiles laid down one after another. */
places: (n: number) => {
for (let i = 0; i < Math.max(1, Math.min(n, 5)); i++) snd.place(i * 85);
},
/** A tile drawn from the face-down pool: slide, then onto the rack. */
draw: (delay = 0) => {
noise(130, 0.07, delay, 'bandpass', 1300, 0.7);
snd.place(delay + 140);
},
/** Somebody else moving tiles while thinking (quiet). */
shuffleQuiet: () => noise(28, 0.06, 0, 'bandpass', 3000, 2),
};
/** A value that shows for `ms` and then clears itself (timer cleaned up on unmount). */
function useTimed<T>(): [T | null, (v: T, ms: number) => void] {
const [val, setVal] = useState<T | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const set = useCallback((v: T, ms: number) => {
clearTimeout(timer.current);
setVal(v);
timer.current = setTimeout(() => setVal(null), ms);
}, []);
return [val, set];
}
/** Wraps a number that bumps (anim-bump) whenever it changes after the first render. */
function Bump({ value, children }: { value: number; children: React.ReactNode }) {
const prev = useRef(value);
const n = useRef(0);
if (prev.current !== value) {
prev.current = value;
n.current += 1;
}
return (
<span key={n.current} className={n.current ? 'rk-bump anim-bump' : 'rk-bump'}>
{children}
</span>
);
}
const CSS = `
.rk-root { width: 100%; align-self: stretch; flex: 1; min-height: 0; display: flex; flex-direction: column; gap: 10px; }
.rk-root { position: relative; width: 100%; align-self: stretch; flex: 1; min-height: 0; display: flex; flex-direction: column; gap: 10px; }
.rk-bump { display: inline-block; }
.rk-banner { position: fixed; z-index: 40; top: 34%; left: 0; right: 0; margin: 0 auto; width: max-content; max-width: 92vw; text-align: center;
padding: 12px 26px; border-radius: 18px; font-size: clamp(1.4rem, 5vw, 2.2rem); font-weight: 900; letter-spacing: -.01em;
background: linear-gradient(#fffdf7, #f1e7cf); color: #111827; border: 2px solid #c9b98f; box-shadow: 0 4px 0 #b5a172, 0 12px 30px rgba(0,0,0,.35); }
.rk-banner.big { background: linear-gradient(#fde68a, #f59e0b); border-color: #b45309; box-shadow: 0 4px 0 #92400e, 0 12px 30px rgba(0,0,0,.35); }
.rk-players { display: flex; flex-wrap: wrap; gap: 6px; }
.rk-player { display: flex; align-items: center; gap: 6px; background: var(--surface); color: var(--text); border: 3px solid transparent;
border-radius: 12px; padding: 4px 10px 4px 6px; box-shadow: var(--shadow); font-size: .9rem; min-height: 44px; }
@@ -89,6 +148,7 @@ button.rk-tile:disabled { cursor: default; }
}
@media (prefers-reduced-motion: reduce) {
.rk-tile { transition: none; }
.rk-banner { display: none; }
.rk-set.changed { animation: none; box-shadow: 0 0 0 3px #fde047; }
}
`;
@@ -116,12 +176,15 @@ interface TileProps {
selected?: boolean;
hint?: boolean;
fresh?: boolean;
/** Extra animation class (anim-deal / anim-pop) and its CSS variables. */
anim?: string;
style?: CSSProperties;
onClick?: () => void;
}
function Tile({ id, size = 'md', as, selected, hint, fresh, onClick }: TileProps) {
function Tile({ id, size = 'md', as, selected, hint, fresh, anim, style, onClick }: TileProps) {
const t = tileOf(id);
const cls = `rk-tile${size !== 'md' ? ` ${size}` : ''}${hint ? ' hint' : ''}${fresh ? ' fresh' : ''}`;
const cls = `rk-tile${size !== 'md' ? ` ${size}` : ''}${hint ? ' hint' : ''}${fresh ? ' fresh' : ''}${anim ? ` ${anim}` : ''}`;
const body =
t.kind === 'joker' ? (
<>
@@ -140,13 +203,13 @@ function Tile({ id, size = 'md', as, selected, hint, fresh, onClick }: TileProps
const dataC = t.kind === 'num' ? t.color : undefined;
if (!onClick) {
return (
<span className={cls} data-c={dataC} role="img" aria-label={label}>
<span className={cls} data-c={dataC} role="img" aria-label={label} style={style}>
{body}
</span>
);
}
return (
<button type="button" className={cls} data-c={dataC} aria-pressed={!!selected} aria-label={label} onClick={onClick}>
<button type="button" className={cls} data-c={dataC} aria-pressed={!!selected} aria-label={label} onClick={onClick} style={style}>
{body}
</button>
);
@@ -194,6 +257,14 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
const [announce, setAnnounce] = useState('');
const wasMine = useRef(false);
const lastLog = useRef<string>('');
// Animations: tiles flying onto my rack, tiles newly on the table, a shaking area, a big banner.
const [fly, setFly] = useTimed<{ ids: string[]; gap: number }>();
const [pop, setPop] = useTimed<Set<string>>();
const [shake, setShake] = useTimed<string>();
const [banner, setBanner] = useTimed<{ text: string; big: boolean; seq: number }>();
const bannerSeq = useRef(0);
const showBanner = (text: string, big = false) => setBanner({ text, big, seq: ++bannerSeq.current }, 1700);
const snap = useRef<{ log: string; gameNo: number; phase: string; turnNo: number; edits: number; melded: Record<string, boolean>; table: Set<string> } | null>(null);
const serverSets: DraftSet[] = useMemo(
() => (v.draft ? v.draft.map((d) => (d.as ? { tileIds: d.tileIds, as: d.as } : { tileIds: d.tileIds })) : v.table.map((t) => ({ tileIds: t.tileIds, as: t.kind }))),
@@ -231,6 +302,67 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
if (e.by !== me) setAnnounce(logText(e, players, me));
}, [v.log]); // eslint-disable-line react-hooks/exhaustive-deps
// Sounds + animations for what everybody did, from view changes only (the first view is just recorded).
useEffect(() => {
const e = v.log[v.log.length - 1];
const now = {
log: e ? `${v.match.gameNo}-${e.turn}-${e.kind}-${e.by}` : '',
gameNo: v.match.gameNo,
phase: v.phase,
turnNo: v.turnNo,
edits: v.draftEdits,
melded: Object.fromEntries(v.seats.map((s) => [s.id, s.melded])),
table: new Set(v.table.flatMap((t) => t.tileIds)),
};
const prev = snap.current;
snap.current = now;
if (!prev) return;
// A new round: tiles shuffled and dealt onto my rack.
if (now.gameNo !== prev.gameNo) {
if (v.phase === 'playing') {
sfx.shuffle();
sfx.deal(6, 70);
if (v.my) setFly({ ids: v.my.rack, gap: 35 }, 1400);
}
return;
}
if (e && now.log !== prev.log) {
const mineMove = e.by === me;
const name = nick(players, e.by);
if (e.kind === 'commit' || e.kind === 'timeoutCommit') {
snd.places(e.count);
const added = [...now.table].filter((id) => !prev.table.has(id));
if (!mineMove && added.length) setPop(new Set(added), 900);
const firstMeld = !prev.melded[e.by] && now.melded[e.by];
if (mineMove || firstMeld) sfx.good();
if (firstMeld && !(v.phase !== 'playing' && v.round?.endReason === 'rackEmpty')) showBanner(mineMove ? '첫 등록 성공!' : `${name}님 첫 등록!`);
} else if (e.kind === 'draw' || e.kind === 'timeoutDraw') {
snd.draw();
if (mineMove && v.my?.lastDrawn.length) setFly({ ids: v.my.lastDrawn, gap: 90 }, 900);
} else if (e.kind === 'penalty') {
sfx.bad();
for (let i = 0; i < Math.min(e.count, 3); i++) snd.draw(250 + i * 160);
setShake(mineMove ? 'rack' : `p:${e.by}`, 500);
if (mineMove) {
haptic([60, 40, 60]);
if (v.my?.lastDrawn.length) setFly({ ids: v.my.lastDrawn, gap: 120 }, 1100);
showBanner(`벌칙! ${e.count}장 가져오기`);
}
} else if (e.kind === 'pass') {
sfx.whoosh();
}
} else if (v.current && v.current !== me && now.turnNo === prev.turnNo && now.edits > prev.edits) {
// Somebody else is moving tiles around in their turn.
snd.shuffleQuiet();
}
// The round is over: "다 냈다!" (the match result sound itself is played by the room page).
if (prev.phase === 'playing' && v.phase !== 'playing' && v.round?.endReason === 'rackEmpty') {
const w = v.round.winners;
showBanner(w.includes(me ?? '') ? '다 냈다!' : `${w.map((p) => nick(players, p)).join(', ')}님 다 냈다!`, true);
if (v.phase === 'roundEnd') sfx.fanfare();
}
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
// Drop selected tiles that disappeared (e.g. after undo on the server).
useEffect(() => {
setSel((s) => (s.every((id) => inSets.has(id) || rack.includes(id)) ? s : s.filter((id) => inSets.has(id) || rack.includes(id))));
@@ -245,6 +377,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
if (!mine) return;
setHintIds([]);
setMsg('');
snd.pick();
setSel((s) => (s.includes(id) ? s.filter((x) => x !== id) : [...s, id]));
};
@@ -258,6 +391,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
else setMsg('');
const next = moveTiles(sets, sel, target, onTable0);
if (!next) return;
snd.place();
setSel([]);
send(next);
};
@@ -278,6 +412,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
setMsg(my?.melded ? '받침대 타일만으로 바로 만들 수 있는 묶음이 없어요. 바닥 묶음에 붙여 보거나 한 장 가져오세요.' : `받침대 타일만으로 ${v.options.initialMeldPoints}점을 만들기 어려워요. 한 장 가져오세요.`);
return;
}
snd.pick();
setHintIds(found.flat());
setSel(found[0]!);
setMsg(found.length > 1 ? `보라색 타일로 묶음 ${found.length}개를 만들 수 있어요. 첫 묶음을 골라 두었어요. "새 묶음"을 눌러 보세요.` : '보라색 타일로 묶음을 만들 수 있어요. 골라 두었으니 "새 묶음"을 눌러 보세요.');
@@ -288,8 +423,18 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
setConfirm('commit');
return;
}
// The server refuses this commit (nothing changes in the view), so the "틀렸어요" feedback is local.
if (my?.check && !my.check.ok && (v.options.invalidCommitPenalty === 'reject' || !my.check.fromRack)) {
sfx.bad();
haptic(80);
setShake('table', 500);
}
act({ type: 'commit', turn: v.turnNo });
};
const undoLike = (type: 'undoDraft' | 'resetDraft') => {
sfx.whoosh();
act({ type });
};
const draw = () => {
if (my?.changed) setConfirm('draw');
else act({ type: v.poolCount ? 'draw' : 'pass' });
@@ -305,15 +450,17 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
return (
<div className="rk-root">
<style>{CSS}</style>
<Players v={v} me={me} players={players} deadline={deadline} />
<Players v={v} me={me} players={players} deadline={deadline} shake={shake} />
<section className="rk-table" aria-label="바닥">
<section className={`rk-table${shake === 'table' ? ' anim-shake' : ''}`} aria-label="바닥">
<div className="rk-table-head">
<span>
{showingDraft && !mine ? `${curName}님이 고민 중인 배치` : mine && my?.changed ? '바닥(확정 전)' : '바닥'}
{thinking && !showingDraft ? ` · ${curName}님이 생각 중…` : ''}
</span>
<span aria-label={`남은 타일 ${v.poolCount}장`}>남은 타일 {v.poolCount}장</span>
<span aria-label={`남은 타일 ${v.poolCount}장`}>
남은 타일 <Bump value={v.poolCount}>{v.poolCount}</Bump>장
</span>
</div>
{mine && my && !my.melded && (
<div className="rk-meld">
@@ -346,7 +493,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
</button>
)}
{d.tileIds.map((id) => (
<Tile key={id} id={id} size="sm" as={jokerAs[id]} selected={sel.includes(id)} onClick={mine ? () => toggle(id) : undefined} />
<Tile key={id} id={id} size="sm" as={jokerAs[id]} selected={sel.includes(id)} anim={pop?.has(id) ? 'anim-pop' : undefined} onClick={mine ? () => toggle(id) : undefined} />
))}
{mine && sel.length > 0 && (
<button type="button" className="rk-slot" aria-label={`묶음 ${i + 1} 뒤에 놓기`} onClick={() => move({ set: i, at: 'end' })}>
@@ -385,10 +532,10 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
: '타일을 눌러 고른 뒤 놓을 곳을 누르세요.')}
</p>
<div className="rk-bar" role="group" aria-label="내 차례 행동">
<button type="button" className="btn btn-secondary" disabled={!my?.canUndo || pending} onClick={() => act({ type: 'undoDraft' })}>
<button type="button" className="btn btn-secondary" disabled={!my?.canUndo || pending} onClick={() => undoLike('undoDraft')}>
되돌리기
</button>
<button type="button" className="btn btn-secondary" disabled={!my?.changed || pending} onClick={() => act({ type: 'resetDraft' })}>
<button type="button" className="btn btn-secondary" disabled={!my?.changed || pending} onClick={() => undoLike('resetDraft')}>
처음으로
</button>
{selFromSets ? (
@@ -445,11 +592,23 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
))}
</div>
</div>
<div className="rk-rack" role="group" aria-label="내 받침대">
<div className={`rk-rack${shake === 'rack' ? ' anim-shake' : ''}`} role="group" aria-label="내 받침대">
{rack.length === 0 && <span className="rk-rack-empty">{my.rack.length ? '모두 바닥에 놓았어요.' : '타일이 없어요.'}</span>}
{rack.map((id) => (
<Tile key={id} id={id} selected={sel.includes(id)} hint={hintIds.includes(id)} fresh={fresh.has(id)} onClick={mine ? () => toggle(id) : undefined} />
))}
{rack.map((id) => {
const k = fly ? fly.ids.indexOf(id) : -1;
return (
<Tile
key={id}
id={id}
selected={sel.includes(id)}
hint={hintIds.includes(id)}
fresh={fresh.has(id)}
anim={k >= 0 ? 'anim-deal' : undefined}
style={k >= 0 ? ({ '--from-y': '-140px', '--from-x': '0px', '--anim-delay': `${k * fly!.gap}ms` } as CSSProperties) : undefined}
onClick={mine ? () => toggle(id) : undefined}
/>
);
})}
</div>
</div>
)}
@@ -457,6 +616,11 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
<p className="sr-only" aria-live="polite">
{announce}
</p>
{banner && (
<div key={banner.seq} className={`rk-banner anim-banner${banner.big ? ' big' : ''}`} aria-hidden>
{banner.text}
</div>
)}
{confirm === 'draw' && (
<ConfirmSheet
title="놓은 타일을 되돌리고 한 장 가져올까요?"
@@ -480,7 +644,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
);
}
function Players({ v, me, players, deadline }: { v: RummikubView; me: string | null; players: Record<string, PublicUser>; deadline: number | null }) {
function Players({ v, me, players, deadline, shake }: { v: RummikubView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; shake: string | null }) {
return (
<div className="rk-players" role="list" aria-label="참가자">
{v.seats.map((s) => {
@@ -490,7 +654,7 @@ function Players({ v, me, players, deadline }: { v: RummikubView; me: string | n
<div
key={s.id}
role="listitem"
className={`rk-player${turn ? ' turn' : ''}${s.left || !s.inRound ? ' gone' : ''}`}
className={`rk-player${turn ? ' turn' : ''}${s.left || !s.inRound ? ' gone' : ''}${shake === `p:${s.id}` ? ' anim-shake' : turn && v.phase === 'playing' ? ' anim-glow' : ''}`}
aria-label={`${u.nickname}${s.id === me ? '(나)' : ''}, 타일 ${s.tiles}장, ${s.melded ? '첫 등록 함' : '첫 등록 전'}${turn ? ', 지금 차례' : ''}${s.left ? ', 나감' : s.away ? ', 자리 비움' : ''}`}
>
<Avatar user={u} size={26} />
@@ -499,7 +663,7 @@ function Players({ v, me, players, deadline }: { v: RummikubView; me: string | n
{s.id === me && <span className="muted"> (나)</span>}
</span>
<span className="rk-count" title="받침대 타일 수">
{s.tiles}장
<Bump value={s.tiles}>{s.tiles}</Bump>장
</span>
{!s.melded && s.inRound && (
<span className="rk-badge" style={{ background: 'var(--surface-2)', color: 'var(--text-sub)' }}>