diff --git a/apps/web/src/games/davinci-code/index.tsx b/apps/web/src/games/davinci-code/index.tsx index 44915a8..58f37cd 100644 --- a/apps/web/src/games/davinci-code/index.tsx +++ b/apps/web/src/games/davinci-code/index.tsx @@ -1,10 +1,10 @@ /** 다빈치 코드 화면 (docs/games/davinci-code.md §9). */ -import { useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState, type CSSProperties } from 'react'; import type { DavinciGuess, DavinciOptions, DavinciTileView, DavinciView, PhaseKind, TColor, TileValue } from '@bg/games/davinci-code'; 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 type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; @@ -20,6 +20,60 @@ const valueKo = (v: TileValue) => (v === 'joker' ? '조커' : String(v)); const faceOf = (v: TileValue) => (v === 'joker' ? '−' : String(v)); const hiddenLeft = (row: DavinciTileView[]) => row.filter((t) => !t.revealed).length; +/** Standing number-tile sounds (synthesized; the site volume is applied by feedback.ts). */ +const snd = { + /** A tile taken from the face-down pile. */ + draw: () => { + noise(120, 0.08, 0, 'bandpass', 1200, 0.7); + tone(330, 60, 'triangle', 0.07, 100); + }, + /** A tile slotted into a row: a solid "딸깍". */ + set: (delay = 0) => { + noise(30, 0.15, delay, 'bandpass', 2600, 2); + tone(950, 38, 'triangle', 0.09, delay); + tone(260, 70, 'sine', 0.08, delay + 10); + }, + /** A tile tipped over face up. */ + flip: (delay = 0) => { + noise(45, 0.11, delay, 'highpass', 3000); + tone(620, 70, 'triangle', 0.08, delay + 25, { slideTo: 1240 }); + }, + /** Somebody guessed my tile right. */ + ouch: (delay = 0) => tone(520, 200, 'triangle', 0.1, delay, { slideTo: 300 }), + /** A joker goes into a row (only when the viewer can see it is a joker). */ + joker: (delay = 0) => [1568, 2093, 2637].forEach((f, i) => tone(f, 90, 'triangle', 0.05, delay + i * 60)), + /** A player is out. */ + out: (delay = 0) => [523, 440, 349].forEach((f, i) => tone(f, 170, 'triangle', 0.09, delay + i * 130)), +}; + +/** A value that shows for `ms` and then clears itself (timer cleaned up on unmount). */ +function useTimed(): [T | null, (v: T, ms: number) => void] { + const [val, setVal] = useState(null); + const timer = useRef | 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 ( + + {children} + + ); +} + function totalMsOf(v: DavinciView): number { if (v.phase === 'chooseStart') return 15_000; if ((v.idle[v.current] ?? 0) >= 3) return 5_000; @@ -46,6 +100,10 @@ function guessLine(g: DavinciGuess, players: Record): string } const CSS = ` +.dv-bump { display: inline-block; } +.dv-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; + background: linear-gradient(160deg, #42454d, #141519); color: #fff; border: 2px solid #050505; box-shadow: 0 4px 0 rgba(0,0,0,.45), 0 12px 30px rgba(0,0,0,.35); } .dv-board { width: 100%; max-width: 980px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; } .dv-opps { display: grid; gap: 10px; } .dv-player { background: var(--surface); border-radius: var(--radius-lg); padding: 10px 12px; box-shadow: var(--shadow); border: 3px solid transparent; } @@ -74,13 +132,16 @@ const CSS = ` .dv-tile.secret { outline: 3px dashed var(--primary); outline-offset: 2px; } .dv-tile.sm { --w: 30px; } .dv-tile.lg { --w: 54px; } -.dv-tile.hit { animation: dv-flip .5s ease-out, dv-hit 1.2s ease-out; } -.dv-tile.miss { animation: dv-flip .5s ease-out, dv-miss 1.2s ease-out; } -.dv-tile.new { animation: dv-drop .35s ease-out; } -@keyframes dv-flip { 0% { transform: rotateY(90deg); } 100% { transform: rotateY(0); } } +.dv-tile.hit { animation: dv-flip .5s ease-out both, dv-hit 1.2s ease-out both; } +.dv-tile.miss { animation: dv-flip .5s ease-out both, dv-miss 1.2s ease-out both; animation-delay: var(--anim-delay, 0ms); } +.dv-tile.new { animation: dv-drop .38s ease-out both; animation-delay: var(--anim-delay, 0ms); } +.dv-tile.shake { animation: anim-shake .45s ease, dv-miss 1.2s ease-out; } +.dv-tile.deal { animation: anim-deal .38s cubic-bezier(0.2, 0.8, 0.3, 1.15) both; animation-delay: var(--anim-delay, 0ms); } +.dv-tile.reveal { animation: dv-flip .45s ease-out both; animation-delay: var(--anim-delay, 0ms); } +@keyframes dv-flip { 0% { transform: perspective(500px) rotateY(90deg); } 60% { transform: perspective(500px) rotateY(-12deg); } 100% { transform: perspective(500px) rotateY(0); } } @keyframes dv-hit { 0%, 60% { box-shadow: 0 0 0 4px #22c55e, 0 0 18px 6px rgba(34,197,94,.7); } 100% { box-shadow: 0 3px 0 rgba(0,0,0,.35); } } @keyframes dv-miss { 0%, 60% { box-shadow: 0 0 0 4px #ef4444, 0 0 18px 6px rgba(239,68,68,.6); } 100% { box-shadow: 0 3px 0 rgba(0,0,0,.35); } } -@keyframes dv-drop { 0% { transform: translateY(-14px); opacity: .3; } 100% { transform: translateY(0); opacity: 1; } } +@keyframes dv-drop { 0% { transform: translateY(-34px) scale(.85); opacity: .2; } 70% { transform: translateY(3px); opacity: 1; } 100% { transform: translateY(0); } } .dv-pick { background: none; border: 0; padding: 3px; border-radius: 11px; cursor: pointer; color: inherit; } .dv-pick:disabled { cursor: default; } .dv-pick.can { box-shadow: 0 0 0 3px var(--primary); } @@ -136,19 +197,26 @@ const CSS = ` .dv-board { max-height: none; overflow: visible; } } @media (prefers-reduced-motion: reduce) { - .dv-tile.hit, .dv-tile.miss, .dv-tile.new { animation: none; } + .dv-tile.hit, .dv-tile.miss, .dv-tile.new, .dv-tile.shake, .dv-tile.deal, .dv-tile.reveal { animation: none; } + .dv-banner { display: none; } } `; // ---------------------------------------------------------------- tiles -type Fx = 'hit' | 'miss' | 'new'; +type FxKind = 'hit' | 'miss' | 'new' | 'shake' | 'deal' | 'reveal'; +/** One tile's animation: kind, start delay, and a sequence number so the same kind can replay. */ +interface Fx { + k: FxKind; + d: number; + s: number; +} function Tile({ color, n, revealed, mine, size, fx }: { color: TColor; n?: TileValue; revealed: boolean; mine?: boolean; size?: 'sm' | 'lg'; fx?: Fx }) { const known = n !== undefined; - const cls = ['dv-tile', color, known ? '' : 'back', revealed ? 'open' : '', mine && !revealed ? 'secret' : '', size ?? '', fx ?? ''].filter(Boolean).join(' '); + const cls = ['dv-tile', color, known ? '' : 'back', revealed ? 'open' : '', mine && !revealed ? 'secret' : '', size ?? '', fx?.k ?? ''].filter(Boolean).join(' '); return ( - + {known ? faceOf(n) : ?} ); @@ -161,6 +229,8 @@ function tileLabel(t: DavinciTileView, pos: number, mine: boolean): string { // ---------------------------------------------------------------- board +const NO_FX = new Map(); + interface Sel { target: string; index: number; @@ -171,10 +241,12 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro const myTurn = amPlayer && v.current === me && !!v.alive[me!] && v.phase !== 'chooseStart' && v.phase !== 'finished'; const [sel, setSel] = useState(null); const [val, setVal] = useState(null); - const [fx, setFx] = useState>(new Map()); + const [fx, setFx] = useTimed>(); + const [pendFx, setPendFx] = useTimed(); + const [banner, setBanner] = useTimed<{ text: string; s: number }>(); const [announce, setAnnounce] = useState(''); - const prevHist = useRef(v.history.length); - const prevPlaced = useRef(JSON.stringify(v.lastPlaced)); + const seq = useRef(0); + const snap = useRef<{ hist: number; phase: PhaseKind; pending: boolean; elim: number; picked: number; rows: Record } | null>(null); const prevTurn = useRef(`${v.current}|${v.phase === 'chooseStart'}`); const resetKey = `${v.phase}|${v.current}|${v.history.length}`; @@ -183,30 +255,89 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro setVal(null); }, [resetKey]); - // Effects + screen-reader text for new guesses and newly placed tiles. + // Sounds, tile animations and screen-reader text for what anybody did, from view changes only + // (the first view after mounting is just recorded, so joining / reconnecting is silent). useEffect(() => { - const placedNow = JSON.stringify(v.lastPlaced); + const now = { + hist: v.history.length, + phase: v.phase, + pending: !!v.pending, + elim: v.eliminationOrder.length, + picked: v.picked ? Object.values(v.picked).filter(Boolean).length : 0, + rows: Object.fromEntries(v.seats.map((p) => [p, (v.rows[p] ?? []).map((t) => t.revealed)])), + }; + const prev = snap.current; + snap.current = now; + if (!prev) return; const next = new Map(); - if (v.history.length > prevHist.current) { - const g = v.history[v.history.length - 1]!; - if (g.correct) next.set(`${g.target}:${g.index}`, 'hit'); - else if (v.lastPlaced && v.lastPlaced.player === g.by && v.lastPlaced.revealed) next.set(`${g.by}:${v.lastPlaced.index}`, 'miss'); - setAnnounce( - `${nick(players, g.by)}님이 ${nick(players, g.target)}님 ${g.index + 1}번째 타일을 ${valueKo(g.said)}(으)로 추리해서 ${g.correct ? '맞혔어요' : '틀렸어요'}.`, - ); - if (g.correct && g.by === me) haptic(30); - } else if (placedNow !== prevPlaced.current && v.lastPlaced) { - next.set(`${v.lastPlaced.player}:${v.lastPlaced.index}`, v.lastPlaced.revealed ? 'miss' : 'new'); + const put = (key: string, k: FxKind, d = 0) => next.set(key, { k, d, s: ++seq.current }); + if (prev.phase === 'chooseStart' && v.phase !== 'chooseStart') { + // Start tiles dealt into every row. + let k = 0; + for (const p of v.seats) (v.rows[p] ?? []).forEach((_, i) => put(`${p}:${i}`, 'deal', Math.min(k++ * 60, 900))); + sfx.deal(Math.min(k, 10), 60); + } else { + if (v.phase === 'chooseStart' && now.picked > prev.picked) sfx.click(); + if (!prev.pending && v.pending) { + snd.draw(); + setPendFx({ k: 'deal', d: 0, s: ++seq.current }, 700); + } + let t = 0; // delay of the next sound, so a miss and the tile it costs are heard one after another + const g = now.hist === prev.hist + 1 ? v.history[v.history.length - 1]! : null; + if (g) { + if (g.correct) { + put(`${g.target}:${g.index}`, 'hit'); + snd.flip(); + if (g.target === me) snd.ouch(140); + else sfx.good(); + if (g.by === me) haptic(30); + } else { + put(`${g.target}:${g.index}`, 'shake'); + sfx.bad(); + t = 320; + } + setAnnounce(`${nick(players, g.by)}님이 ${nick(players, g.target)}님 ${g.index + 1}번째 타일을 ${valueKo(g.said)}(으)로 추리해서 ${g.correct ? '맞혔어요' : '틀렸어요'}.`); + } + for (const p of v.seats) { + const a = prev.rows[p] ?? []; + const b = now.rows[p] ?? []; + const lp = v.lastPlaced; + if (b.length === a.length + 1 && lp?.player === p) { + // A tile slotted into the row (after 멈추기, a miss, a joker, or at the game end). + put(`${p}:${lp.index}`, lp.revealed ? 'miss' : 'new', t); + if (lp.revealed) snd.flip(t); + else snd.set(t); + if (v.rows[p]?.[lp.index]?.n === 'joker') snd.joker(t + 90); + } else if (b.length === a.length) { + // Own tile shown after a miss with an empty pile, or all tiles opened when someone leaves. + let opened = 0; + b.forEach((r, i) => { + if (r && !a[i] && !(g?.correct && g.target === p && g.index === i)) put(`${p}:${i}`, 'miss', t + opened++ * 80); + }); + if (opened) snd.flip(t); + } + } + if (now.elim > prev.elim) { + const out = v.eliminationOrder[v.eliminationOrder.length - 1]!; + if (!v.left[out]) { + setBanner({ text: out === me ? '내 숨은 타일이 다 드러났어요' : `${nick(players, out)}님 탈락!`, s: ++seq.current }, 1700); + // The match result sound itself is played by the room page. + if (v.phase !== 'finished') snd.out(t + 250); + } + } + if (prev.phase !== 'finished' && v.phase === 'finished') { + // Game over: every tile that was still hidden from me is turned over. + let k = 0; + for (const p of v.seats) { + if (p === me) continue; + (v.rows[p] ?? []).forEach((r, i) => { + if (!r.revealed && !next.has(`${p}:${i}`)) put(`${p}:${i}`, 'reveal', Math.min(400 + k++ * 50, 1000)); + }); + } + } } - prevHist.current = v.history.length; - prevPlaced.current = placedNow; - if (next.size) { - setFx(next); - const t = setTimeout(() => setFx(new Map()), 1300); - return () => clearTimeout(t); - } - return undefined; - }, [v.history.length, JSON.stringify(v.lastPlaced)]); // eslint-disable-line react-hooks/exhaustive-deps + if (next.size) setFx(next, 1700); + }, [v]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { const key = `${v.current}|${v.phase === 'chooseStart'}`; @@ -222,6 +353,7 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro const canGuess = myTurn && v.phase === 'guess' && !pending; const pick = (target: string, index: number) => { + sfx.select(); if (sel && sel.target === target && sel.index === index) { setSel(null); setVal(null); @@ -236,17 +368,22 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
{opponentsOf(v, me).map((p) => ( - + ))}
-
+
(setSel(null), setVal(null))} />
- {amPlayer && } + {amPlayer && }

{announce}

+ {banner && ( +
+ {banner.text} +
+ )} ); } @@ -271,7 +408,12 @@ function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view: {v.alive[id] && (v.idle[id] ?? 0) >= 3 && 자리 비움} {v.phase === 'chooseStart' && v.alive[id] && {choosing ? '고르는 중' : '다 골랐어요'}} - {v.phase !== 'chooseStart' && `숨은 타일 ${hiddenLeft(row)}개 · `}맞힘 {st.correct}/{st.guesses} + {v.phase !== 'chooseStart' && ( + <> + 숨은 타일 {hiddenLeft(row)}개 ·{' '} + + )} + 맞힘 {st.correct}/{st.guesses} {(isTurn || choosing) && } @@ -303,7 +445,7 @@ function PlayerRow({ const isTurn = v.phase !== 'finished' && v.phase !== 'chooseStart' && v.current === id; const name = nick(players, id); return ( -
+
{row.length === 0 && {v.phase === 'chooseStart' ? '시작 타일을 기다리는 중이에요' : '타일이 없어요'}} @@ -363,7 +505,7 @@ function MyRow({ ); return ( -
+
{row.length === 0 && {v.phase === 'chooseStart' ? '시작 타일 색을 고르면 여기에 놓여요' : '타일이 없어요'}} @@ -403,7 +545,23 @@ function MyRow({ ); } -function Center({ view: v, me, players, act, pending, myTurn }: { view: DavinciView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; myTurn: boolean }) { +function Center({ + view: v, + me, + players, + act, + pending, + myTurn, + pendFx, +}: { + view: DavinciView; + me: string | null; + players: Record; + act: (a: unknown) => void; + pending: boolean; + myTurn: boolean; + pendFx: Fx | null; +}) { const drawing = myTurn && v.phase === 'draw' && !pending; const total = v.pool.black + v.pool.white; const last = v.history[v.history.length - 1]; @@ -434,7 +592,7 @@ function Center({ view: v, me, players, act, pending, myTurn }: { view: DavinciV )} - {COLOR_SHORT[c]} {v.pool[c]}개 + {COLOR_SHORT[c]} {v.pool[c]}개 ); @@ -444,13 +602,13 @@ function Center({ view: v, me, players, act, pending, myTurn }: { view: DavinciV )} {v.pending ? (
- + {v.current === me ? '내가 가져온 타일' : `${nick(players, v.current)}님이 가져온 타일`}
@@ -633,7 +791,10 @@ function NumberPad({ className={`${x === 'joker' ? 'joker' : ''}${(v.options.deductionHelper || seen.has(`${tile.color}:${x}`)) && impossible(x) ? ' unlikely' : ''}`} aria-pressed={val === x} aria-label={x === 'joker' ? '조커' : String(x)} - onClick={() => setVal(x)} + onClick={() => { + sfx.click(); + setVal(x); + }} > {x === 'joker' ? '조커 (−)' : x} diff --git a/apps/web/src/games/las-vegas/index.tsx b/apps/web/src/games/las-vegas/index.tsx index a9cb83e..8610201 100644 --- a/apps/web/src/games/las-vegas/index.tsx +++ b/apps/web/src/games/las-vegas/index.tsx @@ -1,10 +1,10 @@ /** 라스베가스 화면 (docs/games/las-vegas.md §9). Bills are play points of this room only (docs/04 §6). */ -import { useEffect, useLayoutEffect, useRef, useState } from 'react'; +import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react'; import type { LasVegasChoice, LasVegasOptions, LasVegasPayoutView, LasVegasView } from '@bg/games/las-vegas'; 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,65 @@ const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(pr const seatColor = (v: LasVegasView, owner: string) => (owner === HOUSE ? '#ffffff' : (COLORS[v.seats.indexOf(owner)] ?? '#888')); const initial = (players: Record, id: string) => (id === HOUSE ? '흰' : ([...nick(players, id)][0] ?? '?')); +// ---------------------------------------------------------------- sounds (docs/games/las-vegas.md §9 소리·움직임) + +/** A handful of dice shaken, then clacking down as the tumble animation ends. */ +function rollSound(n: number, animated: boolean) { + if (!animated) return sfx.dice(); + for (let i = 0; i < 8; i++) noise(30, 0.1, i * 48, 'bandpass', 1500 + (i % 3) * 380, 3); + const land = ROLL_MS - 120; + for (let i = 0; i < Math.min(n, 6); i++) { + noise(40, 0.12, land + i * 24, 'lowpass', 1100); + tone(640 + i * 60, 28, 'triangle', 0.05, land + i * 24); + } +} +/** Dice pushed onto a casino card, one soft knock each. */ +function placeSound(n: number) { + for (let i = 0; i < Math.min(n, 6); i++) { + tone(820 - i * 30, 40, 'triangle', 0.1, i * 55); + noise(40, 0.09, i * 55, 'lowpass', 1300); + } +} +/** "Uh-oh": the placement made a tie on that casino. */ +function tieSound(delay: number) { + tone(330, 90, 'square', 0.05, delay); + tone(294, 150, 'square', 0.05, delay + 110); +} +/** Round settlement: ties knocked out, bills handed out (count only, never amounts), a cash chime if I was paid. */ +function settleSound(delay: number, ties: number, bills: number, mine: boolean, refill: boolean) { + let t = delay; + if (ties) { + tone(600, 80, 'square', 0.06, t); + tone(300, 140, 'triangle', 0.12, t + 60); + noise(120, 0.1, t, 'lowpass', 700); + t += 260; + } + const n = Math.min(bills, 6); + for (let i = 0; i < n; i++) noise(80, 0.12, t + i * 80, 'bandpass', 2000 + (i % 3) * 300, 0.8); + t += n * 80; + if (mine) for (let i = 0; i < 6; i++) tone(2200 + i * 140, 50, 'triangle', 0.05, t + i * 45); + // New bills dealt onto the casinos for the next round. + if (refill) for (let i = 0; i < 6; i++) noise(60, 0.08, t + 500 + i * 60, 'bandpass', 2400, 0.8); +} +/** "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 | null; children: ReactNode }) { + const r = useRef({ v: value, n: 0 }); + if (r.current.v !== value) r.current = { v: value, n: r.current.n + 1 }; + return ( + + {children} + + ); +} + +const vars = (o: Record) => o as CSSProperties; + const CSS = ` .lv-wrap { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 10px; } .lv-head { display: flex; align-items: center; gap: 8px; justify-content: space-between; flex-wrap: wrap; padding: 10px 14px; } @@ -69,6 +128,7 @@ button.lv-casino:hover { border-color: var(--primary); } .lv-tag.none { background: var(--surface-2); color: var(--text-sub); border: 1px solid var(--border); } @keyframes lv-hit { 0% { transform: scale(1); } 40% { transform: scale(1.05); box-shadow: 0 0 0 6px var(--primary-soft); } 100% { transform: scale(1); } } .lv-casino.hit { animation: lv-hit .55s ease-out; } +.lv-casino.hit.clash { animation: anim-shake .45s ease; border-color: var(--warning); } .lv-lower { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); gap: 10px; align-items: start; } .lv-tray { display: flex; flex-direction: column; gap: 10px; padding: 12px; } .lv-groups { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; } @@ -99,7 +159,12 @@ button.lv-casino:hover { border-color: var(--primary); } .lv-tieout { display: inline-flex; align-items: center; gap: 3px; color: var(--warning); font-weight: 800; } .lv-tieout .lv-dot { opacity: .55; } @keyframes lv-poof { 0% { transform: scale(1.4); opacity: 0; } 50% { transform: scale(1.15); opacity: 1; } 100% { transform: scale(1); } } -.lv-fresh .lv-tieout, .lv-fresh .lv-chip { animation: lv-poof .6s ease-out both; } +.lv-fresh .lv-tieout { animation: lv-poof .3s ease-out both, anim-shake .45s ease .3s; animation-delay: var(--anim-delay, 0ms), calc(var(--anim-delay, 0ms) + .3s); } +.lv-fresh .lv-pbody > .lv-chip { --from-y: -36px; animation: anim-deal .38s cubic-bezier(0.2, 0.8, 0.3, 1.15) both; animation-delay: var(--anim-delay, 0ms); } +.lv-banner { position: fixed; inset: 0; z-index: 30; pointer-events: none; display: flex; align-items: center; justify-content: center; padding-bottom: 18vh; } +.lv-banner > div { font-size: clamp(1.8rem, 7vw, 2.8rem); font-weight: 900; line-height: 1.15; text-align: center; white-space: nowrap; + color: #fde047; text-shadow: 0 4px 12px rgba(0,0,0,.55), 0 0 2px #854d0e; } +.lv-banner small { display: block; font-size: .5em; color: #fff; } .lv-pname { max-width: 84px; overflow: hidden; text-overflow: ellipsis; display: inline-block; vertical-align: bottom; } .lv-final { padding: 12px; } .lv-final table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; } @@ -127,7 +192,7 @@ button.lv-casino:hover { border-color: var(--primary); } } @media (prefers-reduced-motion: reduce) { .lv-casino, .lv-casino.sel { transition: none; transform: none; } - .lv-casino.hit, .lv-die.rolling, .lv-fresh .lv-tieout, .lv-fresh .lv-chip { animation: none; } + .lv-casino.hit, .lv-casino.hit.clash, .lv-die.rolling, .lv-fresh .lv-tieout, .lv-fresh .lv-pbody > .lv-chip, .lv-banner .anim-banner { animation: none; } } `; @@ -158,23 +223,24 @@ function Die({ value, color, size = '', rolling = false }: { value: number; colo ); } -function Bill({ note, small }: { note: number | null; small?: boolean }) { +function Bill({ note, small, anim, style }: { note: number | null; small?: boolean; anim?: string; style?: CSSProperties }) { + const extra = `${small ? ' sm' : ''}${anim ? ` ${anim}` : ''}`; if (note === null) return ( - + ? ); const [bg, fg] = BILL[note] ?? ['#eee', '#111']; return ( - + {note} ); } -function Dot({ color }: { color: string }) { - return ; +function Dot({ color, anim, style }: { color: string; anim?: string; style?: CSSProperties }) { + return ; } function OwnerChip({ v, players, owner, me }: { v: LasVegasView; players: Record; owner: string; me: string | null }) { @@ -209,11 +275,15 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps(null); const [rolling, setRolling] = useState(false); const [flick, setFlick] = useState(null); - const [hit, setHit] = useState<{ value: number; key: number } | null>(null); + const [hit, setHit] = useState<{ value: number; key: number; clash: boolean } | null>(null); + /** Dice that just landed on a casino (drawn flying in for a moment). */ + const [drop, setDrop] = useState<{ value: number; owner: string; own: number; neutral: number; key: number } | null>(null); + /** Round whose fresh bills are being dealt onto the casinos. */ + const [dealt, setDealt] = useState(null); + const [banner, setBanner] = useState<{ text: string; sub?: string; key: number } | null>(null); const [announce, setAnnounce] = useState(''); const prevRoll = useRef(v.rollSeq); - const prevTurn = useRef(v.turnSeq); - const prevRounds = useRef(v.roundResults.length); + const prevView = useRef(v); // New roll: tumble animation + screen-reader text. useLayoutEffect(() => { @@ -226,11 +296,9 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps a - b); setAnnounce(`${who} 주사위 ${all.length}개를 굴렸어요: ${all.join(', ')}`); - if (reducedMotion()) { - sounds.stone(); - return; - } - setRolling(true); + const animated = !reducedMotion(); + rollSound(all.length, animated); + if (animated) setRolling(true); }, [v.rollSeq]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { @@ -240,7 +308,6 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps { setRolling(false); setFlick(null); - sounds.stone(); }, ROLL_MS); return () => { clearInterval(t); @@ -248,39 +315,94 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps { - if (v.turnSeq === prevTurn.current) return; - prevTurn.current = v.turnSeq; - setSel(null); + const pv = prevView.current; + prevView.current = v; + if (pv === v) return; + const turnChanged = v.turnSeq !== pv.turnSeq; + const settled = v.roundResults.length > pv.roundResults.length; + const finished = v.phase === 'finished' && pv.phase !== 'finished'; + if (!turnChanged && !settled && !finished) return; + if (turnChanged) setSel(null); const parts: string[] = []; const lp = v.lastPlace; - if (lp) { - setHit({ value: lp.value, key: v.turnSeq }); + // A real placement (not a concede that also moved the turn on): the mover was placing and no new roll came in between. + const placed = !!lp && pv.phase === 'place' && pv.current === lp.player && v.rollSeq === pv.rollSeq && v.conceded.length === pv.conceded.length; + let delay = 0; + if (lp && placed) { const who = lp.player === me ? '내가' : `${nick(players, lp.player)}님이`; parts.push( `${who} ${lp.value}번 카지노에 주사위 ${lp.own + lp.neutral}개를 놓았어요${lp.neutral ? `(흰 ${lp.neutral}개 포함)` : ''}${lp.auto ? ' (시간 초과로 자동)' : ''}.`, ); + placeSound(lp.own + lp.neutral); + delay = Math.min(lp.own + lp.neutral, 6) * 55 + 120; + let clash = false; + if (!settled) { + const dice = v.casinos[lp.value - 1]?.dice ?? {}; + const mover = lp.own > 0 ? lp.player : HOUSE; + const mine = dice[mover] ?? 0; + clash = Object.entries(dice).some(([o, n]) => o !== mover && n === mine); + if (clash) { + tieSound(delay); + delay += 300; + } + setDrop({ value: lp.value, owner: lp.player, own: lp.own, neutral: lp.neutral, key: v.turnSeq }); + setHit({ value: lp.value, key: v.turnSeq, clash }); + } } - if (v.roundResults.length > prevRounds.current) { - prevRounds.current = v.roundResults.length; + if (settled) { const rr = v.roundResults[v.roundResults.length - 1]!; const ties = rr.payouts.filter((p) => p.removedTies.length > 0).length; parts.push(`${rr.round}라운드 정산이 끝났어요.${ties ? ` 동점 무효가 ${ties}곳에서 나왔어요.` : ''}`); + const awards = rr.payouts.flatMap((p) => p.awards).filter((a) => a.owner !== HOUSE); + // Only my own bills: with hideMoney the others' amounts stay secret (the bill count is public anyway). + const mineAw = me ? awards.filter((a) => a.owner === me) : []; + const more = v.phase !== 'finished'; + settleSound(delay + 150, ties, awards.length, mineAw.length > 0, more); + const seated = !!me && v.seats.includes(me) && !v.conceded.includes(me); + const got = mineAw.reduce((t, a) => t + (a.note ?? 0), 0); + setBanner({ + text: more ? `${rr.round}라운드 정산` : '최종 정산', + sub: seated ? (mineAw.length ? `+${got}점 (${mineAw.length}장)` : '이번엔 못 받았어요') : undefined, + key: v.roundResults.length, + }); + if (more) setDealt(v.round); haptic([50, 30, 50]); } - if (myTurn) { + const mineNow = v.phase !== 'finished' && !!me && v.current === me; + if (mineNow && turnChanged) { haptic(40); - if (document.visibilityState === 'hidden') sounds.myTurn(); + // Only when the turn comes back from someone else; a hidden tab gets the room page's chime instead. + if (pv.current !== me && document.visibilityState === 'visible') turnCue(settled ? 1400 : delay + 250); } if (parts.length) setAnnounce(parts.join(' ')); - }, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps + }, [v]); // eslint-disable-line react-hooks/exhaustive-deps + + // Short-lived effects: forget them so later re-renders (e.g. the casino turning into a button) don't replay them. + useEffect(() => { + if (!drop) return; + const t = setTimeout(() => setDrop(null), 900); + return () => clearTimeout(t); + }, [drop]); + useEffect(() => { + if (dealt === null) return; + const t = setTimeout(() => setDealt(null), 1500); + return () => clearTimeout(t); + }, [dealt]); + useEffect(() => { + if (!banner) return; + const t = setTimeout(() => setBanner(null), 1700); + return () => clearTimeout(t); + }, [banner]); const choices = v.phase === 'place' && !rolling ? v.choices : []; const selChoice = choices.find((c) => c.value === sel) ?? null; const canPick = myTurn && v.phase === 'place' && !pending && !rolling; const pick = (value: number) => { if (!canPick || !choices.some((c) => c.value === value)) return; + if (sel === value) sfx.click(); + else sfx.select(); setSel(sel === value ? null : value); }; const place = () => { @@ -302,7 +424,7 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps {v.phase === 'finished' ? '게임 끝' : `${v.round} / ${v.rounds} 라운드`} {v.current && ( - + {curName} 차례 @@ -335,7 +457,8 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps `${n}점`).join(', ') : '없음'}. 주사위 ${ owners.length ? owners.map(([o, n]) => `${o === me ? '나' : nick(players, o)} ${n}개`).join(', ') : '없음' }${ch && isSel ? `. ${STANDING_TAG[ch.standing]}` : ''}`; - const cls = `lv-casino${ch && canPick ? ' can' : ''}${isSel ? ` sel ${ch?.standing === 'first' ? 'first' : ch?.standing === 'tie' ? 'tie' : ''}` : ''}${hit?.value === c.value ? ' hit' : ''}`; + const cls = `lv-casino${ch && canPick ? ' can' : ''}${isSel ? ` sel ${ch?.standing === 'first' ? 'first' : ch?.standing === 'tie' ? 'tie' : ''}` : ''}${hit?.value === c.value ? ` hit${hit.clash ? ' clash' : ''}` : ''}`; + const ci = c.value - 1; const body = ( <>
@@ -344,22 +467,45 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps번 카지노
- {c.notes.length ? c.notes.map((n, i) => ) : 지폐 없음} + {c.notes.length ? ( + c.notes.map((n, i) => + dealt === v.round ? ( + + ) : ( + + ), + ) + ) : ( + 지폐 없음 + )}
- {owners.map(([o, n]) => ( -
- - {Array.from({ length: Math.min(n!, 8) }, (_, i) => ( - - ))} - - {n! > 8 ? `${n}` : ''} - - {initial(players, o)} - -
- ))} + {owners.map(([o, n]) => { + const shown = Math.min(n!, 8); + const fresh = drop && drop.value === c.value ? (o === HOUSE ? drop.neutral : o === drop.owner ? drop.own : 0) : 0; + return ( +
+ + {Array.from({ length: shown }, (_, i) => + i >= shown - fresh ? ( + + ) : ( + + ), + )} + + {n! > 8 ? `${n}` : ''} + + {initial(players, o)} + +
+ ); + })} {ch && isSel && (
@@ -450,7 +596,7 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps ) : myTurn ? ( - ) : ( @@ -484,6 +630,14 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps {announce}

+ {banner && ( +
+
+ {banner.text} + {banner.sub && {banner.sub}} +
+
+ )}
); } @@ -501,12 +655,12 @@ function Settlement({ me: string | null; players: Record; }) { - const fresh = v.phase !== 'finished' && round === v.round - 1; + const fresh = round === v.roundResults[v.roundResults.length - 1]?.round; return (

{round}라운드 정산

- {payouts.map((p) => ( -
+ {payouts.map((p, row) => ( +
{p.casino}번
{p.removedTies.length > 0 && ( @@ -518,7 +672,7 @@ function Settlement({ )} {p.awards.map((a, i) => ( - + {a.note === null && 1장} @@ -592,7 +746,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps @@ -617,8 +771,12 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps - {m.total !== null ? `${m.total}점` : '?'} -
{m.count}장
+ + {m.total !== null ? `${m.total}점` : '?'} + +
+ {m.count}장 +
{turn && playing && }
@@ -633,9 +791,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps
-
- {mine.notes && mine.notes.length ? mine.notes.map((n, i) => ) : 아직 없어요} -
+ {v.options.hideMoney && playing && (

다른 사람에게는 장 수만 보여요. @@ -662,6 +818,39 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps { + const i = left.indexOf(x); + if (i < 0) return true; + left.splice(i, 1); + return false; + }); + r.current = { sig, fresh, n: r.current.n + 1 }; + } + const { fresh, n } = r.current; + let k = 0; + return ( +

+ {notes.length ? ( + notes.map((note, i) => + fresh[i] ? ( + + ) : ( + + ), + ) + ) : ( + 아직 없어요 + )} +
+ ); +} + // ---------------------------------------------------------------- status function isMyTurn(v: LasVegasView, me: string | null): boolean { @@ -762,7 +951,7 @@ function optionsSummary(o: LasVegasOptions): string { `${o.rounds}라운드`, o.neutralDice === 'auto' ? '흰 주사위 자동' : o.neutralDice === 'on' ? '흰 주사위 켜기' : '흰 주사위 끄기', o.hideMoney ? '금액 숨김' : '금액 공개', - o.turnSeconds === null ? '시간 제한 없음' : `${o.turnSeconds}초`, + o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`, ].join(' · '); } diff --git a/apps/web/src/games/mahjong/index.tsx b/apps/web/src/games/mahjong/index.tsx index 2721ef2..547bc9f 100644 --- a/apps/web/src/games/mahjong/index.tsx +++ b/apps/web/src/games/mahjong/index.tsx @@ -4,7 +4,7 @@ import type { DiscardView, HandResultView, MahjongOptions, MahjongView, MeldView 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 type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; @@ -30,9 +30,134 @@ const eulReul = (word: string) => { }; const waitText = (ws: WaitView[]) => ws.map((w) => `${tileShort(w.kind)}(${w.left}장${w.yaku ? '' : ', 역 없음'})`).join(', '); +// ---------------------------------------------------------------- sounds (synthesized: bone/plastic tiles on felt) + +const mjSound = { + /** One tile knocking another / the table. */ + clack: (delay = 0, g = 1) => { + noise(26, 0.15 * g, delay, 'highpass', 3200); + tone(2100, 24, 'triangle', 0.06 * g, delay); + tone(720, 42, 'sine', 0.08 * g, delay); + }, + /** 타패: the tile lands in the river. */ + discard: () => { + mjSound.clack(0, 1.15); + noise(55, 0.07, 14, 'lowpass', 900); + }, + /** 쯔모: a tile slid off the wall into the hand. */ + draw: () => { + noise(60, 0.06, 0, 'bandpass', 1800, 0.7); + mjSound.clack(55, 0.55); + }, + /** Picking a tile up in my hand. */ + lift: () => tone(1700, 22, 'triangle', 0.05), + /** 새 국: the wall washed and built (자라자라). */ + shuffle: () => { + for (let i = 0; i < 16; i++) mjSound.clack(i * 42 + (i % 3) * 9, 0.35 + (i % 4) * 0.08); + noise(520, 0.05, 0, 'lowpass', 700); + }, + pon: () => { + mjSound.clack(0); + mjSound.clack(70); + tone(560, 150, 'triangle', 0.13, 110, { slideTo: 400 }); + }, + chi: () => { + [0, 50, 100].forEach((d) => mjSound.clack(d, 0.8)); + tone(784, 80, 'triangle', 0.1, 150); + tone(1046, 110, 'triangle', 0.09, 210); + }, + kan: () => { + [0, 60, 120, 180].forEach((d) => mjSound.clack(d)); + tone(196, 280, 'sawtooth', 0.035, 220); + tone(392, 240, 'triangle', 0.09, 220); + }, + kita: () => { + mjSound.clack(0, 0.9); + tone(660, 90, 'triangle', 0.09, 60); + }, + /** 리치: the 1,000-point stick put down, then a rising chime. */ + riichi: () => { + tone(1600, 26, 'square', 0.035); + noise(32, 0.12, 0, 'highpass', 3600); + tone(1046, 120, 'triangle', 0.1, 110); + tone(1568, 220, 'triangle', 0.09, 210); + }, + tsumo: () => { + mjSound.clack(0, 1.3); + [784, 988, 1175, 1568].forEach((f, i) => tone(f, 170, 'triangle', 0.12, 90 + i * 85)); + }, + ron: () => { + mjSound.clack(0, 1.4); + noise(140, 0.08, 0, 'lowpass', 500); + [1046, 1318, 1568].forEach((f) => tone(f, 260, 'square', 0.035, 90)); + tone(2093, 380, 'triangle', 0.09, 220); + }, + /** Points moving after a win. */ + payout: (delay = 0) => { + for (let i = 0; i < 6; i++) tone(2200 + i * 130, 50, 'triangle', 0.045, delay + i * 45); + }, + /** 유국. */ + ryuukyoku: () => [523, 440, 349].forEach((f, i) => tone(f, 200, 'sine', 0.11, i * 150)), + /** A dora indicator turned over. */ + flip: (delay = 0) => { + noise(60, 0.11, delay, 'highpass', 2500); + tone(1400, 40, 'triangle', 0.05, delay + 10); + }, + /** A call / ron window opened for me. */ + prompt: (ron: boolean) => { + if (ron) [1318, 1760, 1318, 1760].forEach((f, i) => tone(f, 80, 'triangle', 0.1, i * 85)); + else { + tone(988, 70, 'triangle', 0.1); + tone(1318, 100, 'triangle', 0.09, 75); + } + }, +}; + +const CALL_SOUND: Record void> = { pon: mjSound.pon, chi: mjSound.chi, kan: mjSound.kan, kita: mjSound.kita, riichi: mjSound.riichi, tsumo: mjSound.tsumo, ron: mjSound.ron }; + +/** One id for a hand from its deal through its result screen (handsPlayed goes up when the hand ends). */ +const handId = (v: MahjongView) => (v.phase === 'playing' ? v.handsPlayed : v.handsPlayed - 1); + +/** What was already on the table when this screen opened, so only things added later animate (not a reconnect's whole table). */ +interface Seen { + hand: number; + disc: number[]; + melds: number[]; + kita: number[]; + riichi: boolean[]; + dora: number; +} +function useSeen(v: MahjongView): Seen | null { + const [s] = useState(() => ({ + hand: handId(v), + disc: v.seats.map((x) => x.discards.length), + melds: v.seats.map((x) => x.melds.length), + kita: v.seats.map((x) => x.kita.length), + riichi: v.seats.map((x) => x.riichi), + dora: v.doraIndicators.length, + })); + // A later hand: everything in it is new. + return s.hand === handId(v) ? s : null; +} + +/** A number that pops when it changes (not on the first render). */ +function Bump({ value, children }: { value: number; children?: ReactNode }) { + const prev = useRef(value); + const moved = useRef(false); + if (prev.current !== value) { + prev.current = value; + moved.current = true; + } + return ( + + {children ?? fmt(value)} + + ); +} + const CSS = ` .game-main:has(> .mj) { justify-content: flex-start; } -.mj { width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 8px; align-self: center; } +.mj { position: relative; width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 8px; align-self: center; } .mj.wide { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-areas: 'table side' 'me me'; align-items: start; gap: 8px 12px; } .mj.wide .mj-opps { grid-area: side; flex-direction: column; flex-wrap: nowrap; } .mj.wide .mj-seat { max-width: none; flex: none; } @@ -80,7 +205,26 @@ const CSS = ` .mj-edge.r { right: 3px; top: 50%; transform: translateY(-50%) rotate(180deg); writing-mode: vertical-rl; text-orientation: sideways; padding: 6px 0; } .mj-edge.l { left: 3px; top: 50%; transform: translateY(-50%); writing-mode: vertical-rl; text-orientation: sideways; padding: 6px 0; } .mj-callout { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); z-index: 5; background: #b91c1c; color: #fff; font-weight: 900; - font-size: 2rem; padding: 4px 18px; border-radius: 14px; box-shadow: 0 6px 18px rgba(0,0,0,.35); pointer-events: none; animation: mj-pop .35s ease; white-space: nowrap; } + font-size: 2rem; padding: 4px 18px; border-radius: 14px; box-shadow: 0 6px 18px rgba(0,0,0,.35); pointer-events: none; animation: mj-call 1.3s ease both; white-space: nowrap; } +.mj-callout.c-riichi { background: #f59e0b; color: #1c1e21; text-shadow: none; } +.mj-callout.c-chi { background: #15803d; } +.mj-callout.c-kan { background: #6d28d9; } +.mj-callout.c-kita { background: #1d4ed8; } +/* 론·쯔모·유국: over the whole board (the table is hidden on the PC result screen). */ +.mj-banner { position: absolute; left: 0; right: 0; top: 18%; z-index: 20; display: flex; justify-content: center; pointer-events: none; } +.mj-banner > span { display: flex; flex-direction: column; align-items: center; gap: 2px; font-size: 3.2rem; font-weight: 900; line-height: 1.1; color: #fff; background: #b91c1c; + padding: 8px 34px; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,.4); text-shadow: 0 2px 4px rgba(0,0,0,.35); white-space: nowrap; border: 3px solid #fde047; } +.mj-banner.tsumo > span { background: linear-gradient(160deg, #f59e0b, #b45309); } +.mj-banner.draw > span { background: #334155; border-color: #94a3b8; font-size: 2.2rem; } +.mj-banner.final > span { background: linear-gradient(160deg, #15803d, #14532d); font-size: 2.4rem; } +.mj-banner small { font-size: 1rem; font-weight: 800; } +/* 타패: the newest tile lands in the river from its owner's side (ponds are rotated, so +Y is always toward the owner). */ +.mj-toss { animation: mj-toss .34s cubic-bezier(.25,.8,.35,1.25) both; } +@keyframes mj-toss { 0% { transform: translateY(calc(var(--tw) * 1.3)) scale(1.3); opacity: 0; } 55% { opacity: 1; } 100% { transform: none; } } +.mj-drawn { animation: mj-draw .3s ease-out both; animation-delay: var(--anim-delay, 0ms); } +@keyframes mj-draw { from { transform: translateY(-24px) rotate(6deg); opacity: 0; } } +.mj-edge .stick.new { animation: mj-stick .45s cubic-bezier(.3,1.5,.5,1) both; } +@keyframes mj-stick { from { transform: translateY(-14px) scale(1.7); opacity: 0; } } .mj-panel { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; } .mj-panel.claim { border: 3px solid var(--primary); box-shadow: 0 6px 20px rgba(0,0,0,.25); } .mj-panel.win { border: 3px solid var(--success); } @@ -118,10 +262,11 @@ const CSS = ` .mj-toggles input { width: 22px; height: 22px; } .mj-hist { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; max-height: 220px; overflow: auto; font-size: .85rem; } .mj-rules td, .mj-rules th { padding: 3px 6px; text-align: left; border-bottom: 1px solid var(--border); vertical-align: top; } -@keyframes mj-pop { 0% { transform: translate(-50%, -50%) scale(.5); opacity: 0; } 70% { transform: translate(-50%, -50%) scale(1.12); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); } } +@keyframes mj-call { 0% { transform: translate(-50%, -50%) scale(.4); opacity: 0; } 14% { transform: translate(-50%, -50%) scale(1.15); opacity: 1; } 24% { transform: translate(-50%, -50%) scale(1); } 80% { opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1.04); opacity: 0; } } @keyframes mj-pulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.04); } } @media (prefers-reduced-motion: reduce) { - .mj-callout, .mj-win-btn { animation: none; } + /* Banners stay readable (shown still, removed by their timer) instead of fading out at once. */ + .mj-callout, .mj-win-btn, .mj-banner .anim-banner { animation: none; } .mj-htile { transition: none; } } @media (max-width: 719px) { @@ -129,6 +274,8 @@ const CSS = ` .mj-seat { padding: 4px 6px; font-size: .8rem; flex-basis: 30%; } .mj-table { border-width: 5px; padding: 4px; border-radius: 16px; } .mj-callout { font-size: 1.5rem; } + .mj-banner > span { font-size: 2.3rem; padding: 6px 22px; } + .mj-banner.draw > span, .mj-banner.final > span { font-size: 1.7rem; } .mj-actions .btn { min-height: 48px; } } `; @@ -179,9 +326,9 @@ function meldLabel(m: MeldView): string { return `${name} ${m.tiles.map(tileShort).join(' ')}`; } -function Meld({ m, w }: { m: MeldView; w: number }) { +function Meld({ m, w, fresh }: { m: MeldView; w: number; fresh?: boolean }) { return ( - + {m.tiles.map((t, i) => { const hidden = m.type === 'ankan' && (i === 0 || i === 3); const side = m.called !== null && t === m.called && m.type !== 'ankan'; @@ -191,17 +338,19 @@ function Meld({ m, w }: { m: MeldView; w: number }) { ); } -function Melds({ s, w }: { s: Pick; w: number }) { +/** `seen`: how many melds / 북 were already there when the screen opened (later ones pop in). */ +function Melds({ s, w, seen }: { s: Pick; w: number; seen?: [number, number] }) { if (s.melds.length === 0 && s.kita.length === 0) return null; + const [m0, k0] = seen ?? [Infinity, Infinity]; return (
{s.melds.map((m, i) => ( - + = m0} /> ))} {s.kita.length > 0 && ( - {s.kita.map((t) => ( - + {s.kita.map((t, i) => ( + = k0 ? 'anim-pop' : undefined} /> ))} )} @@ -211,6 +360,8 @@ function Melds({ s, w }: { s: Pick; w: number }) { // ---------------------------------------------------------------- seats +const meldSeen = (seen: Seen | null, seat: number): [number, number] => (seen ? [seen.melds[seat] ?? 0, seen.kita[seat] ?? 0] : [0, 0]); + function seatLabel(v: MahjongView, s: SeatView, players: Record, me: string | null): string { const parts = [`${POS_KO[relPos(v, s.seat)]}`, `${nick(players, s.id)}${s.id === me ? '(나)' : ''}`, `${WIND[s.wind]}${s.isDealer ? '(친)' : ''}`, `${fmt(s.points)}점`]; if (s.riichi) parts.push('리치'); @@ -223,11 +374,11 @@ function seatLabel(v: MahjongView, s: SeatView, players: Record; me: string | null; deadline: number | null; w: number }) { +function SeatChip({ v, s, players, me, deadline, w, seen }: { v: MahjongView; s: SeatView; players: Record; me: string | null; deadline: number | null; w: number; seen: Seen | null }) { const u = userOf(players, s.id); const turn = v.phase === 'playing' && v.turn === s.seat && v.stage !== 'claim'; return ( -
  • +
  • {u.nickname} @@ -239,8 +390,10 @@ function SeatChip({ v, s, players, me, deadline, w }: { v: MahjongView; s: SeatV {WIND[s.wind]} {s.isDealer ? ' 친' : ''} - {fmt(s.points)} - {s.riichi && 리치} + + + + {s.riichi && 리치} {(s.away || s.left) && {s.left ? '나감' : '자리 비움'}} {v.phase === 'playing' && ( @@ -249,14 +402,15 @@ function SeatChip({ v, s, players, me, deadline, w }: { v: MahjongView; s: SeatV )}
    - +
  • ); } // ---------------------------------------------------------------- table -function Pond({ discards, tw, lastIndex }: { discards: DiscardView[]; tw: number; lastIndex: number | null }) { +/** `fromIndex`: tiles from here on were discarded while watching and land with a toss. */ +function Pond({ discards, tw, lastIndex, fromIndex }: { discards: DiscardView[]; tw: number; lastIndex: number | null; fromIndex: number }) { const rows: DiscardView[][] = []; for (let i = 0; i < discards.length; i += 6) rows.push(discards.slice(i, i + 6)); return ( @@ -272,7 +426,7 @@ function Pond({ discards, tw, lastIndex }: { discards: DiscardView[]; tw: number w={tw} sideways={d.riichi} dim={d.called} - className={idx === lastIndex ? 'last' : undefined} + className={[idx === lastIndex ? 'last' : '', idx >= fromIndex ? 'mj-toss' : ''].filter(Boolean).join(' ') || undefined} label={`${tileName(d.tile)}${d.tsumogiri ? ', 쯔모기리' : ''}${d.riichi ? ', 리치 선언' : ''}${d.called ? ', 울려 감' : ''}`} /> ); @@ -285,7 +439,7 @@ function Pond({ discards, tw, lastIndex }: { discards: DiscardView[]; tw: number const ROT = [0, -90, 180, 90]; -function Table({ v, players, width, callout }: { v: MahjongView; players: Record; width: number; callout: ReactNode }) { +function Table({ v, players, width, callout, seen }: { v: MahjongView; players: Record; width: number; callout: ReactNode; seen: Seen | null }) { // Pond: 6 tiles per row (+ room for one sideways riichi tile) × 4 rows. Table = H + W + H. // Total width ≈ 2H + W + padding/border = 17·tw + 37. const tw = Math.max(14, Math.min(30, Math.floor((width - 37) / 17))); @@ -303,7 +457,7 @@ function Table({ v, players, width, callout }: { v: MahjongView; players: Record return (
    - +
    ); @@ -314,8 +468,8 @@ function Table({ v, players, width, callout }: { v: MahjongView; players: Record const turn = v.phase === 'playing' && v.turn === s.seat && v.stage !== 'claim'; return ( - {WIND[s.wind]} {fmt(s.points)} - {s.riichi && } + {WIND[s.wind]} + {s.riichi && } ); }; @@ -334,12 +488,12 @@ function Table({ v, players, width, callout }: { v: MahjongView; players: Record
    {roundLabel(v).split(' ')[0]} - {v.honba}본장 · 공탁 {v.riichiPool / 1000}개 + {v.honba}본장 · 공탁 개 남은 패 {v.wallCount}
    - {v.doraIndicators.map((t) => ( - + {v.doraIndicators.map((t, i) => ( + = (seen?.dora ?? 0) ? 'anim-flip' : undefined} style={{ '--anim-delay': '120ms' } as CSSProperties} /> ))} {Array.from({ length: Math.max(0, 5 - v.doraIndicators.length) }, (_, i) => ( @@ -358,7 +512,28 @@ function Table({ v, players, width, callout }: { v: MahjongView; players: Record // ---------------------------------------------------------------- my hand -function MyArea({ v, my, act, pending, players, deadline, tapConfirm }: { v: MahjongView; my: MyView; act: (a: unknown) => void; pending: boolean; players: Record; deadline: number | null; tapConfirm: boolean }) { +function MyArea({ + v, + my, + act, + pending, + players, + deadline, + tapConfirm, + seen, + dealing, +}: { + v: MahjongView; + my: MyView; + act: (a: unknown) => void; + pending: boolean; + players: Record; + deadline: number | null; + tapConfirm: boolean; + seen: Seen | null; + /** A new hand was just dealt: the hand tiles fly in one by one. */ + dealing: boolean; +}) { const [sel, setSel] = useState(null); const [riichiMode, setRiichiMode] = useState(false); const [kanPick, setKanPick] = useState(false); @@ -395,12 +570,16 @@ function MyArea({ v, my, act, pending, players, deadline, tapConfirm }: { v: Mah const tap = (code: string) => { if (!myTurn || pending) return; if (!legal.has(code)) { + sounds.warn(); setNote(locked.has(code) ? `${tileShort(code)}: 방금 울은 패와 같은 패(또는 스지)라 버릴 수 없어요.` : riichiMode ? '이 패를 버리면 텐파이가 아니라 리치할 수 없어요.' : my.riichi ? '리치 후에는 쯔모한 패만 버릴 수 있어요.' : '지금은 버릴 수 없어요.'); return; } setNote(''); if (sel === code || !tapConfirm) send(code); - else setSel(code); + else { + mjSound.lift(); + setSel(code); + } }; const onKey = (e: KeyboardEvent) => { if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; @@ -415,7 +594,7 @@ function MyArea({ v, my, act, pending, players, deadline, tapConfirm }: { v: Mah const selAfter = sel ? my.tenpaiAfter[sel] : undefined; const winNow = my.canTsumo; return ( -
    +
    내 패 @@ -423,14 +602,16 @@ function MyArea({ v, my, act, pending, players, deadline, tapConfirm }: { v: Mah {WIND[me.wind]} {me.isDealer ? ' 친' : ''} - {fmt(me.points)}점 - {my.riichi && 리치} + + 점 + + {my.riichi && 리치} {my.furiten && {beginner ? '후리텐: 론 불가, 쯔모만 가능' : '후리텐'}} {my.autoPilot && 자리 비움 · 아무 패나 누르면 돌아와요}
    {myTurn && }
    - +
    {all.map((code, i) => { const isDrawn = my.drawn === code && i === n - 1; @@ -453,7 +634,12 @@ function MyArea({ v, my, act, pending, players, deadline, tapConfirm }: { v: Mah 텐 )} - + {locked.has(code) && ( 🔒 @@ -643,7 +829,7 @@ function WinnerBlock({ w, v, players }: { w: WinnerView; v: MahjongView; players const limit = LIMIT_KO[w.limit] ?? ''; const yakumanTotal = w.yakuman; return ( -
    +
    🀄 {name}님 {how} @@ -739,8 +925,8 @@ function ResultPanel({ v, players, me, act, pending, deadline }: { v: MahjongVie - {v.seats.map((s) => ( - + {v.seats.map((s, i) => ( + {WIND[s.wind]} {nick(players, s.id)} {s.id === me ? ' (나)' : ''} @@ -782,8 +968,8 @@ function FinalPanel({ v, players, me }: { v: MahjongView; players: Record - {f.ranking.map((r) => ( - + {f.ranking.map((r, i) => ( + {r.rank}위 {nick(players, r.player)} @@ -840,30 +1026,123 @@ function FinalPanel({ v, players, me }: { v: MahjongView; players: Record ({ + hand: handId(v), + phase: v.phase, + disc: v.seats.map((s) => s.discards.length), + dora: v.doraIndicators.length, + call: v.lastCall?.seq ?? -1, + drawn: v.my?.drawn ?? null, + claim: v.my?.claim && !v.my.claim.responded ? `${v.seq}:${v.my.claim.tile}` : null, + canDiscard: !!v.my?.canDiscard, +}); + +type Banner = { key: number; kind: 'ron' | 'tsumo' | 'draw' | 'final'; text: string; sub?: string }; + function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm }: BoardProps) { const [announce, setAnnounce] = useState(''); - const [callout, setCallout] = useState<{ seq: number; text: string } | null>(null); + const [callout, setCallout] = useState<{ seq: number; text: string; call: string } | null>(null); + const [banner, setBanner] = useState(null); + const [dealing, setDealing] = useState(false); const [ref, width, mainH] = useBox(); + const seen = useSeen(v); const mine = isMyTurn(v, me); const prevMine = useRef(false); + const snap = useRef(null); + const bannerSeq = useRef(0); + const showBanner = (b: Omit) => setBanner({ ...b, key: ++bannerSeq.current }); + + // Sounds follow the view (my own clicks too), so nothing plays twice; the first view only sets the baseline. + useEffect(() => { + const prev = snap.current; + const cur = snapOf(v); + snap.current = cur; + if (!prev) return; + const call = cur.call !== prev.call ? v.lastCall : null; + if (call) { + CALL_SOUND[call.call]?.(); + const who = nick(players, v.seats[call.seat]!.id); + setAnnounce(`${who}님 ${CALL_KO[call.call]?.replace('!', '') ?? ''}`); + if (call.call === 'ron' || call.call === 'tsumo') { + const many = (v.result?.winners.length ?? 1) > 1; + showBanner({ kind: call.call, text: many ? `${v.result!.winners.length}명 론!` : CALL_KO[call.call]!, sub: many ? undefined : who }); + } else setCallout({ seq: call.seq, text: `${who} ${CALL_KO[call.call] ?? ''}`, call: call.call }); + } + if (cur.phase === 'finished') { + if (prev.phase === 'finished') return; + const top = v.final?.ranking[0]; + // Players hear the win/lose sound from the room page's result panel; spectators get a fanfare here. + if (!(me && v.final?.ranking.some((r) => r.player === me))) sfx.fanfare(); + if (top) showBanner({ kind: 'final', text: `🏆 ${top.player === me ? '내가' : `${nick(players, top.player)}님`} 1위!`, sub: `${fmt(top.points)}점` }); + return; + } + if (cur.phase === 'handResult') { + if (prev.phase !== 'handResult' && v.result) { + if (v.result.kind === 'agari') mjSound.payout(call ? 950 : 0); + else { + mjSound.ryuukyoku(); + showBanner({ kind: 'draw', text: v.result.kind === 'exhaustive' ? '유국' : '도중유국', sub: v.result.kind === 'abortive' ? ABORT_KO[v.result.abortiveReason ?? ''] : undefined }); + } + } + return; + } + if (cur.phase !== 'playing') return; + const newHand = prev.phase !== 'playing' || prev.hand !== cur.hand; + if (newHand) mjSound.shuffle(); + else { + if (cur.disc.some((n, i) => n > (prev.disc[i] ?? 0))) mjSound.discard(); + if (cur.dora > prev.dora) mjSound.flip(150); + if (cur.drawn && cur.drawn !== prev.drawn) mjSound.draw(); + } + if (cur.claim && cur.claim !== prev.claim) mjSound.prompt(!!v.my?.claim?.ron); + // My turn to discard (not right after my own call — that already made its sound). + else if (cur.canDiscard && !prev.canDiscard && !(call && call.seat === v.my?.seat)) sounds.myTurn(); + }, [v]); // eslint-disable-line react-hooks/exhaustive-deps + + // A new hand dealt while watching: my tiles fly in (not on the first view). + const hand = handId(v); + const firstHand = useRef(hand); + useEffect(() => { + if (v.phase !== 'playing' || hand === firstHand.current) return; + firstHand.current = hand; + setDealing(true); + }, [hand, v.phase]); + useEffect(() => { + if (!dealing) return; + const t = setTimeout(() => setDealing(false), 900); + return () => clearTimeout(t); + }, [dealing]); + + useEffect(() => { + if (!banner) return; + const t = setTimeout(() => setBanner((b) => (b && b.key === banner.key ? null : b)), 1700); + return () => clearTimeout(t); + }, [banner]); + useEffect(() => { if (mine && !prevMine.current) { haptic(40); - sounds.myTurn(); if (v.my?.claim) setAnnounce(v.my.claim.ron ? '론할 수 있어요!' : '울 수 있어요. 고르거나 패스해 주세요.'); else if (v.phase === 'playing') setAnnounce(v.my?.canTsumo ? '내 차례예요. 쯔모할 수 있어요!' : '내 차례예요.'); } prevMine.current = mine; }, [mine]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { - const c = v.lastCall; - if (!c) return; - const text = `${nick(players, v.seats[c.seat]!.id)} ${CALL_KO[c.call] ?? ''}`; - setCallout({ seq: c.seq, text }); - setAnnounce(`${nick(players, v.seats[c.seat]!.id)}님 ${CALL_KO[c.call]?.replace('!', '') ?? ''}`); - const t = setTimeout(() => setCallout((x) => (x && x.seq === c.seq ? null : x)), 1300); + if (!callout) return; + const t = setTimeout(() => setCallout((x) => (x && x.seq === callout.seq ? null : x)), 1300); return () => clearTimeout(t); - }, [v.lastCall?.seq]); // eslint-disable-line react-hooks/exhaustive-deps + }, [callout]); useEffect(() => { if (v.claimOn && v.claimOn.source === 'discard' && v.claimOn.from !== v.my?.seat) setAnnounce(`${nick(players, v.seats[v.claimOn.from]!.id)}님이 ${eulReul(tileName(v.claimOn.tile))} 버렸어요.`); }, [v.claimOn?.tile, v.claimOn?.from]); // eslint-disable-line react-hooks/exhaustive-deps @@ -881,7 +1160,7 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm
      {others.map((s) => ( - + ))}
    0 ? mainH - 12 : undefined } : undefined}> @@ -889,11 +1168,19 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm {v.phase === 'finished' && } {showTable && (
    - {callout.text} : null} /> +
    {callout.text} : null} seen={seen} /> )} - {v.phase === 'playing' && v.my && } + {v.phase === 'playing' && v.my && } + {banner && ( +
    + + {banner.text} + {banner.sub && {banner.sub}} + +
    + )}

    {announce}

    @@ -962,7 +1249,7 @@ function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProp )} - {fmt(s.points)} + ))} diff --git a/apps/web/src/games/marble/events.test.ts b/apps/web/src/games/marble/events.test.ts new file mode 100644 index 0000000..9d2b8ff --- /dev/null +++ b/apps/web/src/games/marble/events.test.ts @@ -0,0 +1,46 @@ +import { expect, test } from 'bun:test'; +import { movePath, newEvents, toSegments, type GameEvent } from './events'; + +const ev = (type: string, extra: Record = {}): GameEvent => ({ type, ...extra }) as GameEvent; + +test('부루마불 화면: 새 기록만 골라내기(60개 창이 밀려도)', () => { + const old = Array.from({ length: 60 }, (_, i) => ev('turn', { player: 'A', round: i })); + expect(newEvents(old, old)).toEqual([]); + expect(newEvents(old, [...old])).toEqual([]); + const added = [ev('rolled', { player: 'A', dice: [1, 2] }), ev('moved', { player: 'A', from: 0, to: 3, kind: 'roll' })]; + expect(newEvents(old, [...old.slice(2), ...added])).toEqual(added); + expect(newEvents(old.slice(0, 5), [...old.slice(0, 5), ...added])).toEqual(added); + expect(newEvents([], added)).toEqual(added); + // Replay jumping back / unrelated log: no match, stay quiet. + expect(newEvents(old.slice(10, 20), old.slice(0, 5))).toBeNull(); +}); + +test('부루마불 화면: 말이 지나가는 칸', () => { + expect(movePath(ev('moved', { from: 37, to: 2, kind: 'roll' }))).toEqual([37, 38, 39, 0, 1, 2]); + expect(movePath(ev('moved', { from: 2, to: 39, kind: 'back' }))).toEqual([2, 1, 0, 39]); + expect(movePath(ev('moved', { from: 30, to: 5, kind: 'space' }))).toEqual([30, 5]); + expect(movePath(ev('moved', { from: 0, to: 0, kind: 'card', passedStart: true }))).toHaveLength(41); +}); + +test('부루마불 화면: 굴림 → 이동 → 도착 처리 순서로 나누기', () => { + const segs = toSegments( + [ + ev('rolled', { player: 'A' }), + ev('moved', { player: 'A', from: 38, to: 3, kind: 'roll', passedStart: true }), + ev('salary', { player: 'A' }), + ev('tollPaid', { from: 'A', to: 'B' }), + ev('turn', { player: 'B' }), + ev('rolled', { player: 'B' }), + ev('toIsland', { player: 'B', why: 'doubles' }), + ], + new Map([ + ['A', 38], + ['B', 7], + ]), + ); + expect(segs.map((s) => [s.player, s.path, s.walk, s.salary, s.start.map((e) => e.type), s.after.map((e) => e.type)])).toEqual([ + [null, [], false, false, [], ['rolled']], + ['A', [38, 39, 0, 1, 2, 3], true, true, [], ['salary', 'tollPaid', 'turn', 'rolled']], + ['B', [7, 10], false, false, ['toIsland'], []], + ]); +}); diff --git a/apps/web/src/games/marble/events.ts b/apps/web/src/games/marble/events.ts new file mode 100644 index 0000000..81cae60 --- /dev/null +++ b/apps/web/src/games/marble/events.ts @@ -0,0 +1,86 @@ +/** 부루마불 화면: what happened since the last view (log diff) and how the tokens should walk it (docs/games/marble.md §9.1). */ +import type { MarbleView } from '@bg/games/marble'; + +export type GameEvent = MarbleView['log'][number]; + +const ISLAND = 10; + +/** + * Events added since `prev`. The log is a sliding window (the engine keeps the last 60), so the new log is a suffix of + * the old one plus the new events. Returns null when the two don't line up (reconnect, replay jumping back): the + * caller then stays quiet instead of replaying old events. + */ +export function newEvents(prev: readonly GameEvent[], next: readonly GameEvent[]): GameEvent[] | null { + if (prev === next) return []; + if (!prev.length) return next.slice(); + const a = prev.map((e) => JSON.stringify(e)); + const b = next.map((e) => JSON.stringify(e)); + for (let k = Math.min(a.length, b.length); k > 0; k--) { + let same = true; + for (let j = 0; j < k && same; j++) same = a[a.length - k + j] === b[j]; + if (same) return next.slice(k); + } + return null; +} + +/** Squares a token passes through for one `moved` event, starting square first. Space travel / warps jump (2 squares). */ +export function movePath(e: GameEvent): number[] { + const from = e.from as number; + const to = e.to as number; + if (e.kind === 'space' || e.kind === 'warp') return [from, to]; + const back = e.kind === 'back'; + let n = back ? (from - to + 40) % 40 : (to - from + 40) % 40; + if (n === 0 && e.passedStart) n = 40; // "출발로" from 출발: a full lap + const path = [from]; + for (let i = 1; i <= n; i++) path.push((((back ? from - i : from + i) % 40) + 40) % 40); + return path; +} + +/** + * One piece of the replay queue: a token move (walk square by square, or jump) with the events to play when it starts + * and when it lands; or (player null) just events. + */ +export interface Seg { + player: string | null; + path: number[]; + /** Square by square (dice, cards) rather than a jump (space travel, island). */ + walk: boolean; + /** The walk passes or reaches 출발 (salary coin on that square). */ + salary: boolean; + start: GameEvent[]; + after: GameEvent[]; +} + +const blank = (): Seg => ({ player: null, path: [], walk: false, salary: false, start: [], after: [] }); + +/** + * Splits new events into queue pieces: a new piece at every move (and at "sent to the island", which has no `moved` + * event), and right after a roll so what the dice caused waits until they stop. `posBefore`: squares in the last view. + */ +export function toSegments(added: readonly GameEvent[], posBefore: ReadonlyMap): Seg[] { + const pos = new Map(posBefore); + const out: Seg[] = []; + let cur = blank(); + const push = (s: Seg) => { + if (s.player || s.start.length || s.after.length) out.push(s); + }; + for (const e of added) { + const id = typeof e.player === 'string' ? e.player : null; + if (e.type === 'moved' && id) { + push(cur); + const walk = e.kind !== 'space' && e.kind !== 'warp'; + cur = { player: id, path: movePath(e), walk, salary: walk && !!e.passedStart, start: [], after: [] }; + pos.set(id, e.to as number); + } else if (e.type === 'toIsland' && id && pos.has(id) && pos.get(id) !== ISLAND) { + push(cur); + cur = { player: id, path: [pos.get(id)!, ISLAND], walk: false, salary: false, start: [e], after: [] }; + pos.set(id, ISLAND); + } else if (e.type === 'rolled') { + cur.after.push(e); + push(cur); + cur = blank(); + } else cur.after.push(e); + } + push(cur); + return out; +} diff --git a/apps/web/src/games/marble/index.tsx b/apps/web/src/games/marble/index.tsx index d01a825..9a5f19d 100644 --- a/apps/web/src/games/marble/index.tsx +++ b/apps/web/src/games/marble/index.tsx @@ -1,12 +1,13 @@ /** 부루마불 화면 (docs/games/marble.md §9). Board, dice, tokens and buildings are drawn here (SVG/CSS only). */ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import type { MarbleOptions, MarbleOwnedView, MarblePlayerView, MarbleView } from '@bg/games/marble'; import { CARDS, SPACES, type CardId, type Level } from '@bg/games/marble/board'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar, ConfirmSheet, Sheet } 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 { newEvents, toSegments, type Seg } from './events'; import { helpNow } from './help'; import { quickStart } from './quick'; @@ -150,8 +151,19 @@ const CSS = ` .mb-prompt .btn { min-height: 44px; padding: 6px 8px; font-size: .95rem; } .mb-roll { min-height: 48px; font-size: 1rem; } } +/* Sounds & motion (§9.1): flying token, current-player ring, big-moment banner, new land / building pop. */ +.mb-fly { transform-box: fill-box; transform-origin: center; animation: mb-fly .34s cubic-bezier(.3, 1.5, .5, 1) both; } +@keyframes mb-fly { from { transform: translateY(-26px) scale(.3); opacity: 0; } } +.mb-ring { animation: mb-pulse 1.1s ease-in-out infinite; pointer-events: none; } +.mb-svg .anim-pop { transform-box: fill-box; transform-origin: center; } +.mb-banner-wrap { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; pointer-events: none; z-index: 3; } +.mb-banner { padding: 10px 24px; border-radius: 18px; font-weight: 900; font-size: 2.1rem; letter-spacing: -.02em; white-space: nowrap; + background: var(--surface); color: var(--primary); border: 3px solid currentColor; box-shadow: 0 12px 34px rgba(0,0,0,.32); } +.mb-banner.good { color: var(--warning); } +.mb-banner.bad { color: var(--danger); } +@media (max-width: 640px) { .mb-banner { font-size: 1.35rem; padding: 6px 14px; border-radius: 12px; } } @media (prefers-reduced-motion: reduce) { - .mb-cell.pick .mb-pick, .mb-trail, .mb-hop, .mb-die.rolling, .mb-card, .mb-pop { animation: none; } + .mb-cell.pick .mb-pick, .mb-trail, .mb-hop, .mb-die.rolling, .mb-card, .mb-pop, .mb-fly, .mb-ring { animation: none; } } `; @@ -287,12 +299,60 @@ function DieFace({ value }: { value: number | null }) { // ---------------------------------------------------------------- board -interface Anim { - seq: number; - player: string; - path: number[]; - i: number; -} +// ---------------------------------------------------------------- sounds (synthesized; docs/games/marble.md §9.1) + +const ROLL_MS = 600; +type Timer = ReturnType; +const fx = { + /** Token hopping onto the next square. */ + step: (i: number) => { + tone(i % 2 ? 620 : 540, 40, 'triangle', 0.08); + noise(28, 0.05, 0, 'lowpass', 1500); + }, + /** Token landing on its square. */ + land: () => { + tone(300, 90, 'triangle', 0.14); + noise(60, 0.08, 0, 'lowpass', 700); + }, + /** Land bought: a stamp, then a coin. */ + buy: () => { + noise(70, 0.16, 0, 'lowpass', 600); + tone(170, 120, 'sine', 0.16); + tone(1318, 70, 'square', 0.05, 120); + tone(1976, 160, 'square', 0.05, 190); + }, + /** Building: two hammer knocks and a small chime. */ + build: () => { + for (const d of [0, 140]) { + noise(45, 0.14, d, 'bandpass', 1300, 1.5); + tone(260, 50, 'triangle', 0.1, d); + } + tone(523, 90, 'triangle', 0.1, 300); + tone(784, 150, 'triangle', 0.1, 380); + }, + /** Toll: coins counted out, then the register bell. */ + toll: () => { + for (let i = 0; i < 3; i++) sfx.chip(i * 70); + tone(2093, 220, 'triangle', 0.07, 230); + }, + /** Washed up on the island: a wave and a falling whistle. */ + island: () => { + noise(420, 0.08, 0, 'lowpass', 700); + tone(560, 460, 'sine', 0.1, 80, { slideTo: 200 }); + }, + /** One more turn stuck on the island: a small wave. */ + wave: () => { + noise(380, 0.06, 0, 'lowpass', 600); + tone(392, 200, 'sine', 0.07, 100, { slideTo: 330 }); + }, + /** Space travel lift-off: rumble and a rising whine. */ + rocket: () => { + noise(650, 0.08, 0, 'lowpass', 500); + tone(220, 700, 'sawtooth', 0.035, 0, { slideTo: 1500, attack: 60 }); + }, +}; + +const posMap = (v: MarbleView) => new Map(v.players.map((p) => [p.id, p.pos])); function cellLabel(pos: number, v: MarbleView, players: Record, me: string | null): string { const sp = SPACES[pos]!; @@ -312,72 +372,264 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps(null); - const [anim, setAnim] = useState(null); - const [rolling, setRolling] = useState(false); + const [rolling, setRolling] = useState(null); const [card, setCard] = useState<{ id: CardId; player: string; seq: number } | null>(null); + const [banner, setBanner] = useState<{ text: string; kind: 'good' | 'bad' | 'info'; k: number } | null>(null); const [announce, setAnnounce] = useState(''); - const seen = useRef({ roll: v.lastRoll?.seq ?? 0, move: v.lastMove?.seq ?? 0, card: v.lastCard?.seq ?? 0, current: v.current }); + const [, rerender] = useState(0); + const seen = useRef({ roll: v.lastRoll?.seq ?? 0, card: v.lastCard?.seq ?? 0, current: v.current, log: v.log, pos: posMap(v), k: 0 }); + const live = useRef({ me, players }); + live.current = { me, players }; + /** Replay queue: tokens walk the new moves one square at a time (only the drawing; texts and buttons follow the view). */ + const walker = useRef({ q: [] as Seg[], cur: null as { seg: Seg; i: number; k: number } | null, timer: null as Timer | null, hold: 0, dead: false }); + const timers = useRef(new Set()); const cellRefs = useRef<(SVGGElement | null)[]>([]); const spaceMode = !!my?.space; const who = (id: string) => (id === me ? '내가' : `${nick(players, id)}님이`); - // Dice roll: tumble + screen-reader text. + const later = (fn: () => void, ms: number) => { + const t = setTimeout(() => { + timers.current.delete(t); + fn(); + }, ms); + timers.current.add(t); + }; useEffect(() => { - const r = v.lastRoll; - if (!r || r.seq === seen.current.roll) return; - seen.current.roll = r.seq; - setCard(null); // a new roll replaces an old card on the center - setAnnounce(`${who(r.player)} ${r.dice[0]}, ${r.dice[1]}을 굴렸어요${r.double ? '. 더블!' : ''}`); - sounds.stone(); - if (reducedMotion()) return; - setRolling(true); - const t = setTimeout(() => setRolling(false), 600); - return () => clearTimeout(t); - }, [v.lastRoll?.seq]); // eslint-disable-line react-hooks/exhaustive-deps + const w = walker.current; + w.dead = false; + return () => { + w.dead = true; + if (w.timer) clearTimeout(w.timer); + w.timer = null; + w.q = []; + w.cur = null; + for (const t of timers.current) clearTimeout(t); + timers.current.clear(); + }; + }, []); - // Token walks along the path (forward / back); jumps for warps and space travel. - useEffect(() => { - const m = v.lastMove; - if (!m || m.seq === seen.current.move) return; - seen.current.move = m.seq; - if (reducedMotion() || m.kind === 'warp' || m.kind === 'space') return; - const path: number[] = []; - if (m.kind === 'back') for (let p = m.from; p !== m.to; ) path.push((p = (p + 39) % 40)); - else for (let p = m.from; p !== m.to; ) path.push((p = (p + 1) % 40)); - if (path.length) setAnim({ seq: m.seq, player: m.player, path: [m.from, ...path], i: 0 }); - }, [v.lastMove?.seq]); // eslint-disable-line react-hooks/exhaustive-deps + const showBanner = (text: string, kind: 'good' | 'bad' | 'info') => { + const k = ++seen.current.k; + setBanner({ text, kind, k }); + later(() => setBanner((b) => (b && b.k === k ? null : b)), 1700); + }; - useEffect(() => { - if (!anim) return; - if (anim.i >= anim.path.length - 1) { - const t = setTimeout(() => setAnim(null), 100); - return () => clearTimeout(t); + /** Sound (and banner / card) for one event; `walked`: its token just walked there (the salary coin already rang). */ + const play = (e: GameEvent, walked = false) => { + const { me: m, players: ps } = live.current; + const id = typeof e.player === 'string' ? e.player : ''; + switch (e.type) { + case 'salary': + if (!walked) sfx.coin(); + break; + case 'bought': + fx.buy(); + break; + case 'built': + fx.build(); + break; + case 'takeover': + fx.buy(); + sfx.capture(); + break; + case 'tollPaid': + if (e.waived) sfx.good(); + else fx.toll(); + break; + case 'paid': + case 'fundPaid': + sfx.chips(3); + break; + case 'cardGain': + case 'sold': + sfx.coin(); + break; + case 'fundReceived': + if ((e.amount as number) > 0) sfx.collect(); + break; + case 'cardDrawn': { + sfx.cardFlip(); + const k = ++seen.current.k; + setCard({ id: e.cardId as CardId, player: id, seq: k }); + later(() => setCard((x) => (x && x.seq === k ? null : x)), 3200); + break; + } + case 'toIsland': + fx.island(); + showBanner('🏝️ 무인도!', 'bad'); + break; + case 'islandStay': + fx.wave(); + break; + case 'escaped': + sfx.good(); + break; + case 'spaceWait': + sfx.pop(); + break; + case 'spaceTravel': + fx.rocket(); + showBanner('🚀 우주여행!', 'info'); + break; + case 'debt': + sounds.warn(); + break; + case 'cannotAfford': + case 'conceded': + sfx.bad(); + break; + case 'bankrupt': + sfx.alarm(); + showBanner(id === m ? '💸 파산했어요' : `💸 ${nick(ps, id)}님 파산!`, 'bad'); + break; + case 'monopoly': + sfx.fanfare(); + showBanner(id === m ? '👑 독점 달성!' : `👑 ${nick(ps, id)}님 독점!`, 'good'); + break; + case 'tradeProposed': + sfx.select(); + break; + case 'tradeResolved': + if (e.accepted) sfx.good(); + else sfx.bad(); + break; } - const step = Math.max(45, Math.min(130, 1100 / anim.path.length)); - const t = setTimeout(() => setAnim((a) => (a && a.seq === anim.seq ? { ...a, i: a.i + 1 } : a)), step); - return () => clearTimeout(t); - }, [anim]); + }; + const playAll = (list: GameEvent[], walked = false) => list.forEach((e, j) => (j ? later(() => play(e, walked), j * 150) : play(e, walked))); - // Card reveal. + const stepMs = (seg: Seg) => (walker.current.q.length > 1 ? 55 : Math.max(55, Math.min(130, 1500 / Math.max(1, seg.path.length - 1)))); + const pump = () => { + const w = walker.current; + if (w.dead || w.timer) return; + for (;;) { + const seg = w.q[0]; + if (!seg) { + if (w.cur) { + w.cur = null; + rerender((x) => x + 1); + } + return; + } + const wait = w.hold - Date.now(); + if (wait > 0) { + w.timer = setTimeout(() => { + w.timer = null; + pump(); + }, wait); + return; + } + w.q.shift(); + playAll(seg.start); + if (!seg.player || seg.path.length < 2) { + playAll(seg.after, seg.walk); + continue; + } + w.cur = { seg, i: 0, k: ++seen.current.k }; + rerender((x) => x + 1); + w.timer = setTimeout(step, seg.walk ? stepMs(seg) : 160); + return; + } + }; + const step = () => { + const w = walker.current; + w.timer = null; + const c = w.cur; + if (!c || w.dead) return; + const { seg } = c; + const i = c.i + 1; + const last = i >= seg.path.length - 1; + w.cur = { ...c, i }; + if (seg.walk) { + if (seg.salary && seg.path[i] === 0) sfx.coin(); + else if (last) fx.land(); + else fx.step(i); + } + rerender((x) => x + 1); + w.timer = setTimeout( + last + ? () => { + w.timer = null; + w.cur = null; + playAll(seg.after, seg.walk); + rerender((x) => x + 1); + pump(); + } + : step, + last ? (seg.walk ? 90 : 260) : stepMs(seg), + ); + }; + + // New events (mine, the others', the computer's) → dice, token walks, sounds, banners. The view the board opens with + // (first render, reconnect, watching, replay start) is only recorded, never replayed. + useLayoutEffect(() => { + const s = seen.current; + const added = newEvents(s.log, v.log); + const before = s.pos; + s.log = v.log; + s.pos = posMap(v); + const rm = reducedMotion(); + const r = v.lastRoll; + if (r && r.seq !== s.roll) { + s.roll = r.seq; + setCard(null); // a new roll replaces an old card on the center + setAnnounce(`${who(r.player)} ${r.dice[0]}, ${r.dice[1]}을 굴렸어요${r.double ? '. 더블!' : ''}`); + sfx.dice(); + if (!rm) { + const seq = r.seq; + setRolling(seq); + later(() => setRolling((x) => (x === seq ? null : x)), ROLL_MS); + walker.current.hold = Date.now() + ROLL_MS; + } + const thirdDouble = added?.some((e) => e.type === 'toIsland' && e.why === 'doubles'); + if (r.double && !thirdDouble) + later(() => { + sfx.good(); + showBanner('🎲 더블!', 'good'); + }, rm ? 0 : ROLL_MS); + } + if (!added?.length) return; + if (rm) { + playAll(added); + return; + } + const w = walker.current; + w.q.push(...toSegments(added, before)); + if (w.q.length > 8) w.q.splice(0, w.q.length - 8); // far behind (a burst of moves): skip the oldest drawings + rerender((x) => x + 1); + pump(); + }, [v.log]); // eslint-disable-line react-hooks/exhaustive-deps + + // Card text for screen readers (the card itself shows up when the token gets there). useEffect(() => { const c = v.lastCard; if (!c || c.seq === seen.current.card) return; seen.current.card = c.seq; - setCard({ id: c.id, player: c.player, seq: c.seq }); setAnnounce(`${who(c.player)} 행운카드를 뽑았어요: ${CARDS[c.id].name}. ${CARDS[c.id].text}`); - const t = setTimeout(() => setCard((x) => (x && x.seq === c.seq ? null : x)), 3200); - return () => clearTimeout(t); }, [v.lastCard?.seq]); // eslint-disable-line react-hooks/exhaustive-deps - // My-turn cue. + // My-turn cue (the room screen rings it when the tab is hidden). useEffect(() => { if (v.current !== seen.current.current && v.current === me && v.phase !== 'finished') { haptic(40); - sounds.myTurn(); + if (document.visibilityState !== 'hidden') sounds.myTurn(); } seen.current.current = v.current; }, [v.current]); // eslint-disable-line react-hooks/exhaustive-deps + // Newly bought land / new building: pop in once (not on the first render). + const ownSeen = useRef(new Map(v.owned.map((o) => [o.pos, o]))); + const [fresh, setFresh] = useState>({}); + useLayoutEffect(() => { + const upd: Record = {}; + for (const o of v.owned) { + const was = ownSeen.current.get(o.pos); + if (!was || was.owner !== o.owner) upd[o.pos] = { claim: o.owner }; + else if (o.level > was.level) upd[o.pos] = { level: o.level }; + } + ownSeen.current = new Map(v.owned.map((o) => [o.pos, o])); + if (Object.keys(upd).length) setFresh((f) => ({ ...f, ...upd })); + }, [v.owned]); + const moveCell = (to: number) => { const n = (to + 40) % 40; setFocus(n); @@ -406,16 +658,18 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps v.players.find((p) => p.id === id)?.seat ?? 0; - const trail = anim ? new Set(anim.path.slice(1, anim.i + 1)) : null; + const walk = walker.current.cur; + const trail = walk && walk.seg.walk ? new Set(walk.seg.path.slice(1, walk.i + 1)) : null; const band = compact ? 28 : 22; - // Tokens: the moving one is drawn at its animation spot. + // Tokens: a walking one at its walk square, one still waiting in the queue where its walk starts. + const shownPos = (p: MarblePlayerView) => { + if (walk && walk.seg.player === p.id) return walk.seg.path[walk.i]!; + return walker.current.q.find((s) => s.player === p.id && s.path.length)?.path[0] ?? p.pos; + }; const tokens: { p: MarblePlayerView; pos: number; idx: number; n: number }[] = []; const alive = v.players.filter((p) => p.alive); - for (const p of alive) { - const pos = anim && anim.player === p.id ? anim.path[anim.i]! : p.pos; - tokens.push({ p, pos, idx: 0, n: 0 }); - } + for (const p of alive) tokens.push({ p, pos: shownPos(p), idx: 0, n: 0 }); for (const t of tokens) { const same = tokens.filter((x) => x.pos === t.pos); t.n = same.length; @@ -463,7 +717,9 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps {a.band && sp.group && } {a.band && sp.kind === 'tour' && } - {ownerColor && } + {ownerColor && ( + + )} {o && o.level > 0 && a.band && ( {Array.from({ length: o.level }, (_, k) => { @@ -471,7 +727,11 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps; + return ( + + + + ); })} )} @@ -495,7 +755,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps )} - {trail?.has(pos) && } + {trail?.has(pos) && } {(pick || pos === decisionPos) && ( )} @@ -505,17 +765,26 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps { const [x, y] = tokenSpot(pos, idx, n, compact); - const moving = anim && anim.player === p.id; + const moving = walk && walk.seg.player === p.id && walk.i > 0 ? walk : null; + const r = compact ? 15 : 12; return ( - - + + {v.current === p.id && v.phase !== 'finished' && } + ); })}
    -
    setCard(null)} /> +
    setCard(null)} />
    + {banner && ( +
    +
    + {banner.text} +
    +
    + )}

    {announce} diff --git a/apps/web/src/games/rummikub/index.tsx b/apps/web/src/games/rummikub/index.tsx index daac81c..180014b 100644 --- a/apps/web/src/games/rummikub/index.tsx +++ b/apps/web/src/games/rummikub/index.tsx @@ -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, id: string): PublicUser => /** Colour + shape mark so colours never have to be told apart by hue alone (§9). */ const MARK: Record = { 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 | null, (v: T, ms: number) => void] { + const [val, setVal] = useState(null); + const timer = useRef | 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 ( + + {children} + + ); +} + 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 ( - + {body} ); } return ( - ); @@ -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(''); + // 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>(); + const [shake, setShake] = useTimed(); + 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; table: Set } | 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 (

    - + -
    +
    {showingDraft && !mine ? `${curName}님이 고민 중인 배치` : mine && my?.changed ? '바닥(확정 전)' : '바닥'} {thinking && !showingDraft ? ` · ${curName}님이 생각 중…` : ''} - 남은 타일 {v.poolCount}장 + + 남은 타일 {v.poolCount}장 +
    {mine && my && !my.melded && (
    @@ -346,7 +493,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr )} {d.tileIds.map((id) => ( - toggle(id) : undefined} /> + toggle(id) : undefined} /> ))} {mine && sel.length > 0 && ( - {selFromSets ? ( @@ -445,11 +592,23 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr ))}
    -
    +
    {rack.length === 0 && {my.rack.length ? '모두 바닥에 놓았어요.' : '타일이 없어요.'}} - {rack.map((id) => ( - toggle(id) : undefined} /> - ))} + {rack.map((id) => { + const k = fly ? fly.ids.indexOf(id) : -1; + return ( + = 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} + /> + ); + })}
    )} @@ -457,6 +616,11 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr

    {announce}

    + {banner && ( +
    + {banner.text} +
    + )} {confirm === 'draw' && ( ; deadline: number | null }) { +function Players({ v, me, players, deadline, shake }: { v: RummikubView; me: string | null; players: Record; deadline: number | null; shake: string | null }) { return (
    {v.seats.map((s) => { @@ -490,7 +654,7 @@ function Players({ v, me, players, deadline }: { v: RummikubView; me: string | n
    @@ -499,7 +663,7 @@ function Players({ v, me, players, deadline }: { v: RummikubView; me: string | n {s.id === me && (나)} - {s.tiles}장 + {s.tiles}장 {!s.melded && s.inRound && ( diff --git a/apps/web/src/games/yacht/index.tsx b/apps/web/src/games/yacht/index.tsx index c45b6e0..d008600 100644 --- a/apps/web/src/games/yacht/index.tsx +++ b/apps/web/src/games/yacht/index.tsx @@ -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, id: string) => players[id]?.n const userOf = (players: Record, 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 ( + + {children} + + ); +} + 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(v.held); const [anim, setAnim] = useState(null); const [flick, setFlick] = useState(null); - const [flash, setFlash] = useState(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>(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(''); // 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} 라운드`} {v.current && ( - + {curName} 차례 @@ -280,7 +355,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro })}
    {myTurn ? ( - ) : ( @@ -289,15 +364,18 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro

    )} {myTurn && v.rollsUsed > 0 && v.rollsUsed < 3 &&

    남길 주사위를 누르면 고정돼요. 점수표의 칸을 누르면 기록해요.

    } - {v.lastScore && } + {v.lastScore && }

    {announce}

    {flash && ( -
    - {flash} +
    4 ? ' sub' : ''}`} aria-hidden> +
    + {flash.text} + {flash.sub && {flash.sub}} +
    )} {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 }) { return ( -

    +

    방금: {e.player === me ? '나' : nick(players, e.player)} @@ -359,7 +437,7 @@ function ScoreSheet({ if (val !== undefined) { const fresh = ls && ls.player === p && ls.category === c; return ( - + {val} ); @@ -443,7 +521,7 @@ function ScoreSheet({ {sumRow('보너스 +35', (s) => (s.upperBonus ? `+${s.upperBonus}` : {`${Math.max(0, v.upperBonusThreshold - s.upper)} 남음`}))} {lower.map(row)} {yz && sumRow('요트 보너스', (s) => (s.yahtzeeBonus ? `+${s.yahtzeeBonus}` : '-'))} - {sumRow('총점', (s) => s.total, 'yt-total')} + {sumRow('총점', (s) => {s.total}, 'yt-total')}

    @@ -463,7 +541,11 @@ function YachtSide({ view: v, me, players, act, deadline }: BoardProps +
    {i + 1} @@ -478,7 +560,7 @@ function YachtSide({ view: v, me, players, act, deadline }: BoardProps
    - {sh.total} + {sh.total} {turn && v.phase === 'playing' && }
    @@ -572,7 +654,7 @@ function Options({ value: o, onChange }: OptionsProps) { )} - set({ turnSeconds })} /> + set({ turnSeconds })} /> 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(' · '); }