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

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,10 +1,10 @@
/** 요트 다이스 화면 (docs/games/yacht.md §9). */
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import type { Category, ScoreEntry, YachtOptions, YachtSheetView, YachtView } from '@bg/games/yacht';
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, tone } from '../../lib/feedback';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
@@ -33,6 +33,52 @@ const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.n
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;
// ---------------------------------------------------------------- sounds (docs/games/yacht.md §9 소리·움직임)
/** Dice rattled in the cup, then each rolled die clacking down as the tumble animation ends. */
function rollSound(n: number, animated: boolean) {
if (!animated) return sfx.dice();
for (let i = 0; i < 7; i++) noise(30, 0.1, i * 50, 'bandpass', 1600 + (i % 3) * 350, 3);
const land = ROLL_MS - 110;
for (let i = 0; i < Math.min(n, 5); i++) {
noise(45, 0.13, land + i * 28, 'lowpass', 1100);
tone(680 + i * 70, 30, 'triangle', 0.05, land + i * 28);
}
}
/** Die set aside (lower knock) or put back in the cup (lighter tick). */
function holdSound(on: boolean) {
if (on) {
tone(520, 45, 'triangle', 0.13);
noise(25, 0.06, 0, 'lowpass', 1800);
} else tone(780, 40, 'triangle', 0.1);
}
/** Pencil scribble on the score sheet. */
function writeSound() {
for (let i = 0; i < 3; i++) noise(45, 0.07, i * 55, 'highpass', 3500 + i * 300);
tone(990, 70, 'triangle', 0.08, 170);
}
/** A zero crossed into a box. */
function zeroSound() {
noise(160, 0.07, 0, 'lowpass', 500);
tone(260, 180, 'triangle', 0.08, 0, { slideTo: 180 });
}
/** "Your turn" chime (the room page already plays one when the tab is hidden). */
function turnCue(delay: number) {
tone(660, 120, 'sine', 0.13, delay);
tone(880, 160, 'sine', 0.13, delay + 120);
}
/** Wraps a number that should bump when it changes (not on the first render). */
function Bump({ value, children }: { value: number; children: ReactNode }) {
const r = useRef({ v: value, n: 0 });
if (r.current.v !== value) r.current = { v: value, n: r.current.n + 1 };
return (
<span key={r.current.n} className={r.current.n ? 'anim-bump' : undefined} style={{ display: 'inline-block' }}>
{children}
</span>
);
}
const CSS = `
.yt-wrap { width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 12px; }
.yt-tray { display: flex; flex-direction: column; gap: 12px; align-items: stretch; }
@@ -50,9 +96,11 @@ const CSS = `
@keyframes yt-tumble { 0% { transform: translateY(-18px) rotate(-30deg) scale(.9); } 40% { transform: translateY(4px) rotate(200deg); }
70% { transform: translateY(-6px) rotate(330deg); } 100% { transform: translateY(0) rotate(360deg); } }
.yt-die.rolling { animation: yt-tumble ${ROLL_MS}ms ease-out both; }
@keyframes yt-pop { 0% { transform: translate(-50%, -50%) scale(.4); opacity: 0; } 60% { transform: translate(-50%, -50%) scale(1.15); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); } }
.yt-flash { position: fixed; left: 50%; top: 40%; transform: translate(-50%, -50%); z-index: 30; pointer-events: none; font-size: 4rem; font-weight: 900;
color: #fde047; text-shadow: 0 4px 12px rgba(0,0,0,.55), 0 0 2px #854d0e; animation: yt-pop .5s ease-out both; white-space: nowrap; }
.yt-flash { position: fixed; inset: 0; z-index: 30; pointer-events: none; display: flex; align-items: center; justify-content: center; padding-bottom: 18vh; }
.yt-flash > div { font-size: clamp(2.4rem, 10vw, 4rem); font-weight: 900; line-height: 1.1; text-align: center; white-space: nowrap;
color: #fde047; text-shadow: 0 4px 12px rgba(0,0,0,.55), 0 0 2px #854d0e; }
.yt-flash small { display: block; font-size: .4em; color: #fff; }
.yt-flash.sub > div { font-size: clamp(1.8rem, 7vw, 2.8rem); }
.yt-roll { min-height: 64px; font-size: 1.2rem; }
.yt-sheet { padding: 0; overflow: auto; }
.yt-table { border-collapse: separate; border-spacing: 0; width: 100%; font-variant-numeric: tabular-nums; }
@@ -75,8 +123,9 @@ const CSS = `
.yt-cell:hover:not(:disabled) { border-color: var(--primary); color: var(--text); }
.yt-cell:disabled { cursor: not-allowed; opacity: .35; }
.yt-cell:focus-visible { outline: 3px solid var(--focus); outline-offset: 1px; }
@keyframes yt-new { from { background: #fde68a; } to { background: transparent; } }
.yt-new { animation: yt-new 1.6s ease-out; border-radius: 6px; }
@keyframes yt-new { from { background: #fde68a; color: #1c1e21; } to { background: transparent; } }
.yt-new { display: inline-block; min-width: 2em; animation: yt-new 1.6s ease-out, anim-bump .35s ease; border-radius: 6px; }
.yt-new.zero { animation: yt-new 1.6s ease-out, anim-shake .4s ease; }
.yt-bar { height: 8px; border-radius: 4px; background: var(--surface-2); overflow: hidden; }
.yt-bar > span { display: block; height: 100%; background: var(--success); transition: width .3s; }
.yt-pname { display: inline-block; max-width: 72px; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom; }
@@ -89,7 +138,7 @@ const CSS = `
}
@media (prefers-reduced-motion: reduce) {
.yt-die, .yt-die.held { transition: none; }
.yt-die.rolling, .yt-flash, .yt-new { animation: none; }
.yt-die.rolling, .yt-new, .yt-flash .anim-banner { animation: none; }
}
`;
@@ -144,11 +193,15 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
const [held, setHeld] = useState<boolean[]>(v.held);
const [anim, setAnim] = useState<RollAnim | null>(null);
const [flick, setFlick] = useState<number[] | null>(null);
const [flash, setFlash] = useState<string | null>(null);
const [flash, setFlash] = useState<{ text: string; sub?: string; key: number } | null>(null);
const [announce, setAnnounce] = useState('');
const [confirm, setConfirm] = useState<{ category: Category; points: number } | null>(null);
const prevRoll = useRef(v.rollSeq);
const prevTurn = useRef(v.turnSeq);
const prevCurrent = useRef(v.current);
const prevScore = useRef(v.lastScore ? `${v.lastScore.player}:${v.lastScore.category}` : '');
const prevUpper = useRef<Record<string, number>>(Object.fromEntries(Object.entries(v.sheets).map(([p, sh]) => [p, sh.upperBonus])));
const prevHold = useRef({ seq: `${v.turnSeq}:${v.rollSeq}`, held: v.held.join() });
const pointer = useRef<string>('');
// Server holds win once our own pending action is answered (optimistic taps in between).
@@ -156,7 +209,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
if (!pending) setHeld(v.held);
}, [v.held, v.turnSeq, v.rollSeq, pending]);
// Roll animation, yacht flash and screen-reader text when a new roll arrives.
// Roll animation, sound, yacht flash and screen-reader text when a new roll arrives (anyone's roll).
useLayoutEffect(() => {
if (v.rollSeq <= prevRoll.current || !v.dice) {
prevRoll.current = v.rollSeq;
@@ -165,25 +218,33 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
prevRoll.current = v.rollSeq;
const who = v.current === me ? '내가' : `${nick(players, v.current ?? '')}님이`;
setAnnounce(`${who} 굴렸어요: ${v.dice.join(', ')}`);
const mask = v.rollsUsed === 1 ? [true, true, true, true, true] : v.held.map((h) => !h);
const animated = !reducedMotion();
rollSound(mask.filter(Boolean).length, animated);
if (v.dice.every((d) => d === v.dice![0])) {
setFlash('요트!');
setFlash({ text: '요트!', sub: v.current === me ? undefined : nick(players, v.current ?? ''), key: v.rollSeq });
sfx.fanfare();
haptic([80, 40, 80]);
}
if (reducedMotion()) {
sounds.stone();
return;
}
const mask = v.rollsUsed === 1 ? [true, true, true, true, true] : v.held.map((h) => !h);
setAnim({ key: v.rollSeq, mask });
if (animated) setAnim({ key: v.rollSeq, mask });
}, [v.rollSeq]); // eslint-disable-line react-hooks/exhaustive-deps
// Someone else (re)holding dice: the same knock I hear on my own taps.
useEffect(() => {
const seq = `${v.turnSeq}:${v.rollSeq}`;
const h = v.held.join();
const p = prevHold.current;
prevHold.current = { seq, held: h };
if (p.seq !== seq || p.held === h || v.current === me) return;
holdSound(v.held.filter(Boolean).length >= p.held.split(',').filter((x) => x === 'true').length);
}, [v.held, v.turnSeq, v.rollSeq]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!anim) return;
const t = setInterval(() => setFlick([0, 1, 2, 3, 4].map(() => 1 + Math.floor(Math.random() * 6))), 70);
const end = setTimeout(() => {
setAnim(null);
setFlick(null);
sounds.stone();
}, ROLL_MS);
return () => {
clearInterval(t);
@@ -193,24 +254,37 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
useEffect(() => {
if (!flash) return;
const t = setTimeout(() => setFlash(null), 1500);
const t = setTimeout(() => setFlash(null), 1600);
return () => clearTimeout(t);
}, [flash]);
// Score announcement + my-turn cue on turn changes.
// Score sound/banner/announcement + my-turn cue on turn changes (anyone's score).
useEffect(() => {
if (v.turnSeq === prevTurn.current) return;
prevTurn.current = v.turnSeq;
setConfirm(null);
const ls = v.lastScore;
if (ls) {
const key = ls ? `${ls.player}:${ls.category}` : '';
if (ls && key !== prevScore.current) {
const who = ls.player === me ? '내가' : `${nick(players, ls.player)}님이`;
setAnnounce(`${who} ${catName(ls.category, v.options.scoring)}에 ${ls.points}점을 기록했어요${ls.bonus ? ` (요트 보너스 +${ls.bonus})` : ''}${ls.auto ? ' (시간 초과로 자동 기록)' : ''}.`);
const big = ls.bonus > 0 || (ls.points > 0 && (ls.category === 'yacht' || ls.category === 'largeStraight'));
if (ls.points === 0 && !ls.bonus) zeroSound();
else writeSound();
if (big) sfx.good();
const gotUpper = (v.sheets[ls.player]?.upperBonus ?? 0) > 0 && !(prevUpper.current[ls.player] ?? 0);
if (gotUpper) {
sfx.collect();
setFlash({ text: '상단 보너스 +35', sub: ls.player === me ? undefined : nick(players, ls.player), key: v.turnSeq });
} else if (ls.bonus) setFlash({ text: `요트 보너스 +${ls.bonus}`, sub: ls.player === me ? undefined : nick(players, ls.player), key: v.turnSeq });
}
if (v.phase === 'playing' && v.current === me) {
haptic(40);
if (document.visibilityState === 'hidden') sounds.myTurn();
}
prevScore.current = key;
prevUpper.current = Object.fromEntries(Object.entries(v.sheets).map(([p, sh]) => [p, sh.upperBonus]));
const mineNow = v.phase === 'playing' && v.current === me;
if (mineNow) haptic(40);
// Only when the turn comes back from someone else; a hidden tab gets the room page's chime instead.
if (mineNow && prevCurrent.current !== me && document.visibilityState === 'visible') turnCue(350);
prevCurrent.current = v.current;
}, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps
const canRoll = myTurn && !pending && v.rollsUsed < 3 && !(v.rollsUsed > 0 && held.every(Boolean));
@@ -219,6 +293,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
const toggle = (i: number) => {
if (!canHold) return;
const next = held.map((h, j) => (j === i ? !h : h));
holdSound(next[i]!);
setHeld(next);
act({ type: 'hold', held: next });
};
@@ -248,7 +323,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
{v.phase === 'finished' ? '게임 끝' : `${v.round} / ${v.totalRounds} 라운드`}
</strong>
{v.current && (
<span className="row small" style={{ gap: 6, flexWrap: 'nowrap', minWidth: 0 }}>
<span key={v.turnSeq} className="row small anim-slide-up" style={{ gap: 6, flexWrap: 'nowrap', minWidth: 0 }}>
<Avatar user={userOf(players, v.current)} size={24} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{curName} 차례</span>
<span className="badge" aria-label={`굴린 횟수 ${v.rollsUsed}번`}>
@@ -280,7 +355,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
})}
</div>
{myTurn ? (
<button className="btn btn-primary btn-block yt-roll" disabled={!canRoll} onClick={roll}>
<button className={`btn btn-primary btn-block yt-roll${canRoll ? ' anim-glow' : ''}`} disabled={!canRoll} onClick={roll}>
{rollLabel}
</button>
) : (
@@ -289,15 +364,18 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
</p>
)}
{myTurn && v.rollsUsed > 0 && v.rollsUsed < 3 && <p className="muted small" style={{ textAlign: 'center' }}>남길 주사위를 누르면 고정돼요. 점수표의 칸을 누르면 기록해요.</p>}
{v.lastScore && <LastScore entry={v.lastScore} view={v} me={me} players={players} />}
{v.lastScore && <LastScore key={`${v.lastScore.player}:${v.lastScore.category}`} entry={v.lastScore} view={v} me={me} players={players} />}
</section>
<ScoreSheet view={v} me={me} players={players} myTurn={myTurn} pending={pending} onScore={score} pointer={pointer} />
<p className="sr-only" aria-live="polite">
{announce}
</p>
{flash && (
<div className="yt-flash" aria-hidden>
{flash}
<div className={`yt-flash${flash.text.length > 4 ? ' sub' : ''}`} aria-hidden>
<div key={flash.key} className="anim-banner">
{flash.text}
{flash.sub && <small>{flash.sub}</small>}
</div>
</div>
)}
{confirm && (
@@ -315,7 +393,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
function LastScore({ entry: e, view: v, me, players }: { entry: ScoreEntry; view: YachtView; me: string | null; players: Record<string, PublicUser> }) {
return (
<p className="small row" style={{ justifyContent: 'center', gap: 6 }}>
<p className="small row anim-slide-up" style={{ justifyContent: 'center', gap: 6 }}>
<span className="muted">방금:</span>
<strong>{e.player === me ? '나' : nick(players, e.player)}</strong>
<DiceRow dice={e.dice} size={20} />
@@ -359,7 +437,7 @@ function ScoreSheet({
if (val !== undefined) {
const fresh = ls && ls.player === p && ls.category === c;
return (
<span key={fresh ? `n${v.turnSeq}` : 'f'} className={`yt-filled${fresh ? ' yt-new' : ''}`}>
<span key={fresh ? `n${v.turnSeq}` : 'f'} className={`yt-filled${fresh ? ` yt-new${val === 0 ? ' zero' : ''}` : ''}`}>
{val}
</span>
);
@@ -443,7 +521,7 @@ function ScoreSheet({
{sumRow('보너스 +35', (s) => (s.upperBonus ? `+${s.upperBonus}` : <span className="muted small">{`${Math.max(0, v.upperBonusThreshold - s.upper)} 남음`}</span>))}
{lower.map(row)}
{yz && sumRow('요트 보너스', (s) => (s.yahtzeeBonus ? `+${s.yahtzeeBonus}` : '-'))}
{sumRow('총점', (s) => s.total, 'yt-total')}
{sumRow('총점', (s) => <Bump value={s.total}>{s.total}</Bump>, 'yt-total')}
</tbody>
</table>
</section>
@@ -463,7 +541,11 @@ function YachtSide({ view: v, me, players, act, deadline }: BoardProps<YachtView
const sh = v.sheets[p]!;
const turn = v.current === p;
return (
<div key={p} className="row" style={{ gap: 10, flexWrap: 'nowrap', padding: '4px 6px', borderRadius: 10, border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}>
<div
key={p}
className={`row${turn && v.phase === 'playing' ? ' anim-glow' : ''}`}
style={{ gap: 10, flexWrap: 'nowrap', padding: '4px 6px', borderRadius: 10, border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}
>
<span className="muted small" style={{ width: 16, textAlign: 'right' }}>
{i + 1}
</span>
@@ -478,7 +560,7 @@ function YachtSide({ view: v, me, players, act, deadline }: BoardProps<YachtView
</div>
</div>
<span style={{ fontWeight: 800, fontSize: '1.3rem', fontVariantNumeric: 'tabular-nums' }} aria-label={`${nick(players, p)} 총점 ${sh.total}점`}>
{sh.total}
<Bump value={sh.total}>{sh.total}</Bump>
</span>
{turn && v.phase === 'playing' && <TurnTimer deadline={deadline} totalMs={total} mine={p === me} size={40} />}
</div>
@@ -572,7 +654,7 @@ function Options({ value: o, onChange }: OptionsProps<YachtOptions>) {
</Field>
)}
<Field label="한 차례 제한 시간">
<Seg value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [0, '제한 없음']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Seg value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [0, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
<Field label="점수 미리 보기">
<Seg value={o.showPreview ? 'on' : 'off'} options={[['on', '빈 칸에 보여 주기'], ['off', '보여 주지 않기']]} onChange={(k) => set({ showPreview: k === 'on' })} />
@@ -586,7 +668,7 @@ function optionsSummary(o: YachtOptions): string {
o.scoring === 'yacht51' ? '요트 12칸' : '13칸 변형',
...(o.scoring === 'yacht51' && !o.fullHouseAllowsYacht ? ['풀 하우스에 요트 불인정'] : []),
...(o.scoring === 'yahtzee' ? [o.yahtzeeJoker === 'forced' ? '추가 요트는 정해진 순서' : '추가 요트는 아무 칸'] : []),
o.turnSeconds > 0 ? `한 차례 ${o.turnSeconds}초` : '시간 제한 없음',
o.turnSeconds > 0 ? `한 차례 ${o.turnSeconds}초` : '시간 무제한',
...(o.showPreview ? [] : ['미리 보기 끔']),
].join(' · ');
}