루미큐브·다빈치 코드·마작·라스베가스·부루마불·요트 다이스 소리·애니메이션: 상대·컴퓨터 행동도 화면 변화로 한 번만 울림(처음 들어올 때·재접속은 조용), 타일 놓기·뒤집기, 주사위 굴림, 말 한 칸씩 이동, 점수 통 튀기, 큰 순간 배너
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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>(): [T | null, (v: T, ms: number) => void] {
|
||||
const [val, setVal] = useState<T | null>(null);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => () => clearTimeout(timer.current), []);
|
||||
const set = useCallback((v: T, ms: number) => {
|
||||
clearTimeout(timer.current);
|
||||
setVal(v);
|
||||
timer.current = setTimeout(() => setVal(null), ms);
|
||||
}, []);
|
||||
return [val, set];
|
||||
}
|
||||
|
||||
/** Wraps a number that bumps (anim-bump) whenever it changes after the first render. */
|
||||
function Bump({ value, children }: { value: number; children: React.ReactNode }) {
|
||||
const prev = useRef(value);
|
||||
const n = useRef(0);
|
||||
if (prev.current !== value) {
|
||||
prev.current = value;
|
||||
n.current += 1;
|
||||
}
|
||||
return (
|
||||
<span key={n.current} className={n.current ? 'dv-bump anim-bump' : 'dv-bump'}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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, PublicUser>): 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 (
|
||||
<span className={cls} aria-hidden>
|
||||
<span key={fx?.s ?? 0} className={cls} aria-hidden style={fx ? ({ '--anim-delay': `${fx.d}ms`, '--from-y': '-60px', '--from-x': '0px' } as CSSProperties) : undefined}>
|
||||
{known ? faceOf(n) : <span className="q">?</span>}
|
||||
</span>
|
||||
);
|
||||
@@ -161,6 +229,8 @@ function tileLabel(t: DavinciTileView, pos: number, mine: boolean): string {
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
const NO_FX = new Map<string, Fx>();
|
||||
|
||||
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<Sel | null>(null);
|
||||
const [val, setVal] = useState<TileValue | null>(null);
|
||||
const [fx, setFx] = useState<Map<string, Fx>>(new Map());
|
||||
const [fx, setFx] = useTimed<Map<string, Fx>>();
|
||||
const [pendFx, setPendFx] = useTimed<Fx>();
|
||||
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<string, boolean[]> } | 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<string, Fx>();
|
||||
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
|
||||
<style>{CSS}</style>
|
||||
<div className="dv-opps">
|
||||
{opponentsOf(v, me).map((p) => (
|
||||
<PlayerRow key={p} id={p} view={v} me={me} players={players} deadline={deadline} fx={fx} canPick={canGuess && !!v.alive[p]} sel={sel} onPick={pick} />
|
||||
<PlayerRow key={p} id={p} view={v} me={me} players={players} deadline={deadline} fx={fx ?? NO_FX} canPick={canGuess && !!v.alive[p]} sel={sel} onPick={pick} />
|
||||
))}
|
||||
</div>
|
||||
<div className="dv-mid">
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} />
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} pendFx={pendFx} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} val={val} setVal={setVal} onCancel={() => (setSel(null), setVal(null))} />
|
||||
</div>
|
||||
{amPlayer && <MyRow view={v} me={me!} players={players} act={act} pending={pending} myTurn={myTurn} deadline={deadline} fx={fx} />}
|
||||
{amPlayer && <MyRow view={v} me={me!} players={players} act={act} pending={pending} myTurn={myTurn} deadline={deadline} fx={fx ?? NO_FX} />}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner && (
|
||||
<div key={banner.s} className="dv-banner anim-banner" aria-hidden>
|
||||
{banner.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -271,7 +408,12 @@ function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view:
|
||||
{v.alive[id] && (v.idle[id] ?? 0) >= 3 && <span className="dv-badge">자리 비움</span>}
|
||||
{v.phase === 'chooseStart' && v.alive[id] && <span className={`dv-badge${choosing ? '' : ' ok'}`}>{choosing ? '고르는 중' : '다 골랐어요'}</span>}
|
||||
<span className="small muted" style={{ marginLeft: 'auto' }}>
|
||||
{v.phase !== 'chooseStart' && `숨은 타일 ${hiddenLeft(row)}개 · `}맞힘 {st.correct}/{st.guesses}
|
||||
{v.phase !== 'chooseStart' && (
|
||||
<>
|
||||
숨은 타일 <Bump value={hiddenLeft(row)}>{hiddenLeft(row)}</Bump>개 ·{' '}
|
||||
</>
|
||||
)}
|
||||
맞힘 <Bump value={st.correct}>{st.correct}</Bump>/{st.guesses}
|
||||
</span>
|
||||
{(isTurn || choosing) && <TurnTimer deadline={deadline} totalMs={totalMsOf(v)} mine={id === me} size={30} />}
|
||||
</div>
|
||||
@@ -303,7 +445,7 @@ function PlayerRow({
|
||||
const isTurn = v.phase !== 'finished' && v.phase !== 'chooseStart' && v.current === id;
|
||||
const name = nick(players, id);
|
||||
return (
|
||||
<section className={`dv-player${isTurn ? ' turn' : ''}${v.alive[id] || v.phase === 'finished' ? '' : ' out'}`} aria-label={`${name}님 타일`}>
|
||||
<section className={`dv-player${isTurn ? ' turn anim-glow' : ''}${v.alive[id] || v.phase === 'finished' ? '' : ' out'}`} aria-label={`${name}님 타일`}>
|
||||
<PlayerHead id={id} view={v} me={me} players={players} deadline={deadline} />
|
||||
<div className="dv-row" role="group" aria-label={`${name}님 타일 줄`}>
|
||||
{row.length === 0 && <span className="small muted">{v.phase === 'chooseStart' ? '시작 타일을 기다리는 중이에요' : '타일이 없어요'}</span>}
|
||||
@@ -363,7 +505,7 @@ function MyRow({
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<section className={`dv-player dv-me${isTurn ? ' turn' : ''}${v.alive[me] || v.phase === 'finished' ? '' : ' out'}`} aria-label="내 타일">
|
||||
<section className={`dv-player dv-me${isTurn ? ' turn anim-glow' : ''}${v.alive[me] || v.phase === 'finished' ? '' : ' out'}`} aria-label="내 타일">
|
||||
<PlayerHead id={me} view={v} me={me} players={players} deadline={deadline} />
|
||||
<div className="dv-row" role="group" aria-label="내 타일 줄">
|
||||
{row.length === 0 && <span className="small muted">{v.phase === 'chooseStart' ? '시작 타일 색을 고르면 여기에 놓여요' : '타일이 없어요'}</span>}
|
||||
@@ -403,7 +545,23 @@ function MyRow({
|
||||
);
|
||||
}
|
||||
|
||||
function Center({ view: v, me, players, act, pending, myTurn }: { view: DavinciView; me: string | null; players: Record<string, PublicUser>; 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<string, PublicUser>;
|
||||
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
|
||||
)}
|
||||
</span>
|
||||
<span>
|
||||
{COLOR_SHORT[c]} {v.pool[c]}개
|
||||
{COLOR_SHORT[c]} <Bump value={v.pool[c]}>{v.pool[c]}</Bump>개
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
@@ -444,13 +602,13 @@ function Center({ view: v, me, players, act, pending, myTurn }: { view: DavinciV
|
||||
<button type="button" className={`dv-pile${drawing ? ' can' : ''}`} disabled={!drawing} aria-label={`타일 가져오기, ${total}개 남음`} onClick={() => act({ type: 'draw' })}>
|
||||
<span>타일 가져오기</span>
|
||||
<span className="small">
|
||||
남은 타일 {total}개 (검정 {v.pool.black} · 흰색 {v.pool.white})
|
||||
남은 타일 <Bump value={total}>{total}</Bump>개 (검정 {v.pool.black} · 흰색 {v.pool.white})
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
{v.pending ? (
|
||||
<div className="dv-pending">
|
||||
<Tile color={v.pending.color} n={v.pending.n} revealed={false} mine={v.current === me} />
|
||||
<Tile color={v.pending.color} n={v.pending.n} revealed={false} mine={v.current === me} fx={pendFx ?? undefined} />
|
||||
<span>
|
||||
{v.current === me ? '내가 가져온 타일' : `${nick(players, v.current)}님이 가져온 타일`}
|
||||
<br />
|
||||
@@ -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}
|
||||
</button>
|
||||
|
||||
@@ -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<string, PublicUser>, 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 (
|
||||
<span key={r.current.n} className={r.current.n ? 'anim-bump' : undefined} style={{ display: 'inline-block' }}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const vars = (o: Record<string, string>) => 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 (
|
||||
<span className={`lv-bill hidden${small ? ' sm' : ''}`} aria-label="금액 비공개 지폐">
|
||||
<span className={`lv-bill hidden${extra}`} style={style} aria-label="금액 비공개 지폐">
|
||||
?
|
||||
</span>
|
||||
);
|
||||
const [bg, fg] = BILL[note] ?? ['#eee', '#111'];
|
||||
return (
|
||||
<span className={`lv-bill${small ? ' sm' : ''}`} style={{ background: bg, color: fg }} aria-label={`지폐 ${note}점`}>
|
||||
<span className={`lv-bill${extra}`} style={{ ...style, background: bg, color: fg }} aria-label={`지폐 ${note}점`}>
|
||||
{note}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Dot({ color }: { color: string }) {
|
||||
return <span className="lv-dot" style={{ background: color }} aria-hidden />;
|
||||
function Dot({ color, anim, style }: { color: string; anim?: string; style?: CSSProperties }) {
|
||||
return <span className={`lv-dot${anim ? ` ${anim}` : ''}`} style={{ ...style, background: color }} aria-hidden />;
|
||||
}
|
||||
|
||||
function OwnerChip({ v, players, owner, me }: { v: LasVegasView; players: Record<string, PublicUser>; owner: string; me: string | null }) {
|
||||
@@ -209,11 +275,15 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
const [rolling, setRolling] = useState(false);
|
||||
const [flick, setFlick] = useState<number[] | null>(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<number | null>(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<LasVeg
|
||||
const who = v.current === me ? '내가' : `${nick(players, v.current ?? '')}님이`;
|
||||
const all = [...v.lastRoll.own, ...v.lastRoll.neutral].sort((a, b) => 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<LasVeg
|
||||
const end = setTimeout(() => {
|
||||
setRolling(false);
|
||||
setFlick(null);
|
||||
sounds.stone();
|
||||
}, ROLL_MS);
|
||||
return () => {
|
||||
clearInterval(t);
|
||||
@@ -248,39 +315,94 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
};
|
||||
}, [rolling]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Turn changes: placement flash, round settlement and my-turn cue.
|
||||
// Anyone's placement, round settlement and my-turn cue, found by comparing with the previous view.
|
||||
useEffect(() => {
|
||||
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<LasVeg
|
||||
<div className="card lv-head">
|
||||
<strong>{v.phase === 'finished' ? '게임 끝' : `${v.round} / ${v.rounds} 라운드`}</strong>
|
||||
{v.current && (
|
||||
<span className="row small" style={{ gap: 6, flexWrap: 'nowrap', minWidth: 0 }}>
|
||||
<span key={v.turnSeq} className="row small anim-slide-up" style={{ gap: 6, flexWrap: 'nowrap', minWidth: 0 }}>
|
||||
<Dot color={seatColor(v, v.current)} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{curName} 차례</span>
|
||||
</span>
|
||||
@@ -335,7 +457,8 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
const label = `${c.value}번 카지노. 지폐 ${c.notes.length ? c.notes.map((n) => `${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 = (
|
||||
<>
|
||||
<div className="lv-ctop">
|
||||
@@ -344,22 +467,45 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
<span className="lv-cname">번 카지노</span>
|
||||
</div>
|
||||
<div className="lv-bills">
|
||||
{c.notes.length ? c.notes.map((n, i) => <Bill key={i} note={n} />) : <span className="lv-nobill">지폐 없음</span>}
|
||||
{c.notes.length ? (
|
||||
c.notes.map((n, i) =>
|
||||
dealt === v.round ? (
|
||||
<Bill key={`d${dealt}-${i}`} note={n} anim="anim-deal" style={vars({ '--anim-delay': `${200 + ci * 70 + i * 50}ms`, '--from-y': '-50px' })} />
|
||||
) : (
|
||||
<Bill key={i} note={n} />
|
||||
),
|
||||
)
|
||||
) : (
|
||||
<span className="lv-nobill">지폐 없음</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="lv-stacks">
|
||||
{owners.map(([o, n]) => (
|
||||
<div key={o} className="lv-stack" title={nick(players, o)}>
|
||||
<span className="lv-pips">
|
||||
{Array.from({ length: Math.min(n!, 8) }, (_, i) => (
|
||||
<Dot key={i} color={seatColor(v, o)} />
|
||||
))}
|
||||
</span>
|
||||
<span>{n! > 8 ? `${n}` : ''}</span>
|
||||
<span className="muted" style={{ fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{initial(players, o)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{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 (
|
||||
<div key={o} className="lv-stack" title={nick(players, o)}>
|
||||
<span className="lv-pips">
|
||||
{Array.from({ length: shown }, (_, i) =>
|
||||
i >= shown - fresh ? (
|
||||
<Dot
|
||||
key={`p${drop!.key}-${i}`}
|
||||
color={seatColor(v, o)}
|
||||
anim="anim-deal"
|
||||
style={vars({ '--anim-delay': `${(i - (shown - fresh)) * 55}ms`, '--from-y': '90px' })}
|
||||
/>
|
||||
) : (
|
||||
<Dot key={i} color={seatColor(v, o)} />
|
||||
),
|
||||
)}
|
||||
</span>
|
||||
<span>{n! > 8 ? `${n}` : ''}</span>
|
||||
<span className="muted" style={{ fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{initial(players, o)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{ch && isSel && (
|
||||
<div className="lv-stack" style={{ opacity: 0.85 }}>
|
||||
<span className="lv-pips">
|
||||
@@ -450,7 +596,7 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
)}
|
||||
</>
|
||||
) : myTurn ? (
|
||||
<button className="btn btn-primary btn-block lv-roll" disabled={pending} onClick={roll}>
|
||||
<button className={`btn btn-primary btn-block lv-roll${pending ? '' : ' anim-glow'}`} disabled={pending} onClick={roll}>
|
||||
🎲 주사위 굴리기 ({(hand?.own ?? 0) + (hand?.neutral ?? 0)}개)
|
||||
</button>
|
||||
) : (
|
||||
@@ -484,6 +630,14 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner && (
|
||||
<div className="lv-banner" aria-hidden>
|
||||
<div key={banner.key} className="anim-banner">
|
||||
{banner.text}
|
||||
{banner.sub && <small>{banner.sub}</small>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -501,12 +655,12 @@ function Settlement({
|
||||
me: string | null;
|
||||
players: Record<string, PublicUser>;
|
||||
}) {
|
||||
const fresh = v.phase !== 'finished' && round === v.round - 1;
|
||||
const fresh = round === v.roundResults[v.roundResults.length - 1]?.round;
|
||||
return (
|
||||
<section className={`card lv-settle${fresh ? ' lv-fresh' : ''}`} aria-label={`${round}라운드 정산`}>
|
||||
<h3>{round}라운드 정산</h3>
|
||||
{payouts.map((p) => (
|
||||
<div key={p.casino} className="lv-prow">
|
||||
{payouts.map((p, row) => (
|
||||
<div key={p.casino} className="lv-prow" style={vars({ '--anim-delay': `${row * 90}ms` })}>
|
||||
<strong>{p.casino}번</strong>
|
||||
<div className="lv-pbody">
|
||||
{p.removedTies.length > 0 && (
|
||||
@@ -518,7 +672,7 @@ function Settlement({
|
||||
</span>
|
||||
)}
|
||||
{p.awards.map((a, i) => (
|
||||
<span key={a.key ?? `${a.owner}-${i}`} className="lv-chip">
|
||||
<span key={a.key ?? `${a.owner}-${i}`} className="lv-chip" style={vars({ '--anim-delay': `${row * 90 + 150 + i * 70}ms` })}>
|
||||
<OwnerChip v={v} players={players} owner={a.owner} me={me} />
|
||||
<Bill note={a.note} small />
|
||||
{a.note === null && <span className="muted">1장</span>}
|
||||
@@ -592,7 +746,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
return (
|
||||
<div
|
||||
key={p}
|
||||
className="row"
|
||||
className={`row${turn && playing ? ' anim-glow' : ''}`}
|
||||
style={{ gap: 10, flexWrap: 'nowrap', padding: '4px 6px', borderRadius: 10, border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}
|
||||
>
|
||||
<span aria-label={`${COLOR_NAMES[i]} 주사위`} role="img">
|
||||
@@ -617,8 +771,12 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}
|
||||
aria-label={`${nick(players, p)} 지폐 ${m.count}장${m.total !== null ? `, ${m.total}점` : ''}`}
|
||||
>
|
||||
<strong style={{ fontSize: '1.2rem' }}>{m.total !== null ? `${m.total}점` : '?'}</strong>
|
||||
<div className="small muted">{m.count}장</div>
|
||||
<strong style={{ fontSize: '1.2rem' }}>
|
||||
<Bump value={m.total}>{m.total !== null ? `${m.total}점` : '?'}</Bump>
|
||||
</strong>
|
||||
<div className="small muted">
|
||||
<Bump value={m.count}>{m.count}장</Bump>
|
||||
</div>
|
||||
</span>
|
||||
{turn && playing && <TurnTimer deadline={deadline} totalMs={total} mine={p === me} size={40} />}
|
||||
</div>
|
||||
@@ -633,9 +791,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
{mine.count}장 · {mine.total ?? 0}점
|
||||
</span>
|
||||
</div>
|
||||
<div className="lv-bills">
|
||||
{mine.notes && mine.notes.length ? mine.notes.map((n, i) => <Bill key={i} note={n} small />) : <span className="lv-nobill">아직 없어요</span>}
|
||||
</div>
|
||||
<MyBills notes={mine.notes ?? []} />
|
||||
{v.options.hideMoney && playing && (
|
||||
<p className="small muted" style={{ margin: 0 }}>
|
||||
다른 사람에게는 장 수만 보여요.
|
||||
@@ -662,6 +818,39 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
);
|
||||
}
|
||||
|
||||
/** My bills; the ones just received fly in (my own amounts are always visible to me). */
|
||||
function MyBills({ notes }: { notes: number[] }) {
|
||||
const sig = notes.join(',');
|
||||
const r = useRef({ sig, fresh: [] as boolean[], n: 0 });
|
||||
if (r.current.sig !== sig) {
|
||||
const left = r.current.sig ? r.current.sig.split(',').map(Number) : [];
|
||||
const fresh = notes.map((x) => {
|
||||
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 (
|
||||
<div className="lv-bills">
|
||||
{notes.length ? (
|
||||
notes.map((note, i) =>
|
||||
fresh[i] ? (
|
||||
<Bill key={`f${n}-${i}`} note={note} small anim="anim-deal" style={vars({ '--anim-delay': `${400 + k++ * 90}ms`, '--from-y': '-40px' })} />
|
||||
) : (
|
||||
<Bill key={i} note={note} small />
|
||||
),
|
||||
)
|
||||
) : (
|
||||
<span className="lv-nobill">아직 없어요</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 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(' · ');
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string, () => 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<Seen>(() => ({
|
||||
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 (
|
||||
<span key={value} className={moved.current ? 'anim-bump' : undefined} style={{ display: 'inline-block' }}>
|
||||
{children ?? fmt(value)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<span className="mj-meld" role="img" aria-label={meldLabel(m)}>
|
||||
<span className={`mj-meld${fresh ? ' anim-pop' : ''}`} role="img" aria-label={meldLabel(m)}>
|
||||
{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<SeatView, 'melds' | 'kita'>; w: number }) {
|
||||
/** `seen`: how many melds / 북 were already there when the screen opened (later ones pop in). */
|
||||
function Melds({ s, w, seen }: { s: Pick<SeatView, 'melds' | 'kita'>; w: number; seen?: [number, number] }) {
|
||||
if (s.melds.length === 0 && s.kita.length === 0) return null;
|
||||
const [m0, k0] = seen ?? [Infinity, Infinity];
|
||||
return (
|
||||
<div className="mj-melds">
|
||||
{s.melds.map((m, i) => (
|
||||
<Meld key={i} m={m} w={w} />
|
||||
<Meld key={i} m={m} w={w} fresh={i >= m0} />
|
||||
))}
|
||||
{s.kita.length > 0 && (
|
||||
<span className="mj-meld" role="img" aria-label={`북 뽑기 ${s.kita.length}장`}>
|
||||
{s.kita.map((t) => (
|
||||
<Tile key={t} code={t} w={w} />
|
||||
{s.kita.map((t, i) => (
|
||||
<Tile key={t} code={t} w={w} className={i >= k0 ? 'anim-pop' : undefined} />
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
@@ -211,6 +360,8 @@ function Melds({ s, w }: { s: Pick<SeatView, 'melds' | 'kita'>; 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<string, PublicUser>, 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<string, PublicUs
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
function SeatChip({ v, s, players, me, deadline, w }: { v: MahjongView; s: SeatView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; w: number }) {
|
||||
function SeatChip({ v, s, players, me, deadline, w, seen }: { v: MahjongView; s: SeatView; players: Record<string, PublicUser>; 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 (
|
||||
<li className={`mj-seat${turn ? ' turn' : ''}${s.left ? ' gone' : ''}`} aria-label={seatLabel(v, s, players, me)}>
|
||||
<li className={`mj-seat${turn ? ' turn anim-glow' : ''}${s.left ? ' gone' : ''}`} aria-label={seatLabel(v, s, players, me)}>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }} aria-hidden>
|
||||
<Avatar user={u} size={22} />
|
||||
<span className="nm">{u.nickname}</span>
|
||||
@@ -239,8 +390,10 @@ function SeatChip({ v, s, players, me, deadline, w }: { v: MahjongView; s: SeatV
|
||||
{WIND[s.wind]}
|
||||
{s.isDealer ? ' 친' : ''}
|
||||
</span>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>{fmt(s.points)}</strong>
|
||||
{s.riichi && <span className="mj-badge mj-b-riichi">리치</span>}
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
<Bump value={s.points} />
|
||||
</strong>
|
||||
{s.riichi && <span className={`mj-badge mj-b-riichi${seen?.riichi[s.seat] ? '' : ' anim-pop'}`}>리치</span>}
|
||||
{(s.away || s.left) && <span className="mj-badge mj-b-away">{s.left ? '나감' : '자리 비움'}</span>}
|
||||
{v.phase === 'playing' && (
|
||||
<span className="mj-back-count" title="손패 장수">
|
||||
@@ -249,14 +402,15 @@ function SeatChip({ v, s, players, me, deadline, w }: { v: MahjongView; s: SeatV
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Melds s={s} w={w} />
|
||||
<Melds s={s} w={w} seen={meldSeen(seen, s.seat)} />
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 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<string, PublicUser>; width: number; callout: ReactNode }) {
|
||||
function Table({ v, players, width, callout, seen }: { v: MahjongView; players: Record<string, PublicUser>; 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 (
|
||||
<div className="mj-cell" style={style} role="group" aria-label={`${nick(players, s.id)}님 버림패 ${s.discards.length}장`}>
|
||||
<div className={`mj-pond${turn ? ' turn' : ''}`} style={{ width: W, height: H, transform: `translate(-50%, -50%) rotate(${ROT[pos]}deg)` }}>
|
||||
<Pond discards={s.discards} tw={tw} lastIndex={lastIndex} />
|
||||
<Pond discards={s.discards} tw={tw} lastIndex={lastIndex} fromIndex={seen ? (seen.disc[s.seat] ?? 0) : 0} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -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 (
|
||||
<span key={pos} className={`mj-edge ${['b', 'r', 't', 'l'][pos]}${turn ? ' turn' : ''}`} aria-hidden>
|
||||
{WIND[s.wind]} {fmt(s.points)}
|
||||
{s.riichi && <i className="stick" />}
|
||||
{WIND[s.wind]} <Bump value={s.points} />
|
||||
{s.riichi && <i className={`stick${seen?.riichi[s.seat] ? '' : ' new'}`} />}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
@@ -334,12 +488,12 @@ function Table({ v, players, width, callout }: { v: MahjongView; players: Record
|
||||
<div className="mj-center" style={{ width: W, height: W }}>
|
||||
<span className="rl">{roundLabel(v).split(' ')[0]}</span>
|
||||
<span className="sub">
|
||||
{v.honba}본장 · 공탁 {v.riichiPool / 1000}개
|
||||
{v.honba}본장 · 공탁 <Bump value={v.riichiPool / 1000} />개
|
||||
</span>
|
||||
<span className="sub">남은 패 {v.wallCount}</span>
|
||||
<div className="mj-dora" title="도라 표시패">
|
||||
{v.doraIndicators.map((t) => (
|
||||
<Tile key={t} code={t} w={dw} />
|
||||
{v.doraIndicators.map((t, i) => (
|
||||
<Tile key={t} code={t} w={dw} className={i >= (seen?.dora ?? 0) ? 'anim-flip' : undefined} style={{ '--anim-delay': '120ms' } as CSSProperties} />
|
||||
))}
|
||||
{Array.from({ length: Math.max(0, 5 - v.doraIndicators.length) }, (_, i) => (
|
||||
<Tile key={`b${i}`} code={null} w={dw} />
|
||||
@@ -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<string, PublicUser>; 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<string, PublicUser>;
|
||||
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<string | null>(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<HTMLDivElement>) => {
|
||||
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 (
|
||||
<div className="mj-panel mj-me" aria-label="내 패">
|
||||
<div className={`mj-panel mj-me${myTurn ? ' anim-glow' : ''}`} aria-label="내 패">
|
||||
<div className="mj-myhead">
|
||||
<div className="row" style={{ gap: 6 }}>
|
||||
<strong>내 패</strong>
|
||||
@@ -423,14 +602,16 @@ function MyArea({ v, my, act, pending, players, deadline, tapConfirm }: { v: Mah
|
||||
{WIND[me.wind]}
|
||||
{me.isDealer ? ' 친' : ''}
|
||||
</span>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>{fmt(me.points)}점</strong>
|
||||
{my.riichi && <span className="mj-badge mj-b-riichi">리치</span>}
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
<Bump value={me.points} />점
|
||||
</strong>
|
||||
{my.riichi && <span className={`mj-badge mj-b-riichi${seen?.riichi[my.seat] ? '' : ' anim-pop'}`}>리치</span>}
|
||||
{my.furiten && <span className="mj-badge mj-b-furiten">{beginner ? '후리텐: 론 불가, 쯔모만 가능' : '후리텐'}</span>}
|
||||
{my.autoPilot && <span className="mj-badge mj-b-away">자리 비움 · 아무 패나 누르면 돌아와요</span>}
|
||||
</div>
|
||||
{myTurn && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine size={36} />}
|
||||
</div>
|
||||
<Melds s={me} w={meldW} />
|
||||
<Melds s={me} w={meldW} seen={meldSeen(seen, my.seat)} />
|
||||
<div ref={ref} className="mj-hand" role="group" aria-label="내 손패. 좌우 방향키로 고르고 Enter로 고른 뒤 한 번 더 누르면 버려요" onKeyDown={onKey}>
|
||||
{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
|
||||
텐
|
||||
</span>
|
||||
)}
|
||||
<Tile code={code} w={tw} />
|
||||
<Tile
|
||||
code={code}
|
||||
w={tw}
|
||||
className={isDrawn ? 'mj-drawn' : dealing ? 'anim-deal' : undefined}
|
||||
style={dealing ? ({ '--anim-delay': `${i * 30}ms`, '--from-y': '-70px' } as CSSProperties) : undefined}
|
||||
/>
|
||||
{locked.has(code) && (
|
||||
<span className="lock" aria-hidden>
|
||||
🔒
|
||||
@@ -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 (
|
||||
<div className="mj-panel win">
|
||||
<div className="mj-panel win anim-slide-up">
|
||||
<strong style={{ fontSize: '1.1rem' }}>
|
||||
🀄 {name}님 {how}
|
||||
</strong>
|
||||
@@ -739,8 +925,8 @@ function ResultPanel({ v, players, me, act, pending, deadline }: { v: MahjongVie
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{v.seats.map((s) => (
|
||||
<tr key={s.seat}>
|
||||
{v.seats.map((s, i) => (
|
||||
<tr key={s.seat} className="anim-slide-up" style={{ '--anim-delay': `${250 + i * 90}ms` } as CSSProperties}>
|
||||
<td>
|
||||
{WIND[s.wind]} {nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
@@ -782,8 +968,8 @@ function FinalPanel({ v, players, me }: { v: MahjongView; players: Record<string
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{f.ranking.map((r) => (
|
||||
<tr key={r.player}>
|
||||
{f.ranking.map((r, i) => (
|
||||
<tr key={r.player} className="anim-slide-up" style={{ '--anim-delay': `${i * 110}ms` } as CSSProperties}>
|
||||
<td>{r.rank}위</td>
|
||||
<td>
|
||||
{nick(players, r.player)}
|
||||
@@ -840,30 +1026,123 @@ function FinalPanel({ v, players, me }: { v: MahjongView; players: Record<string
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
/** Public facts compared between views to play sounds (only what everyone can see, plus my own hand/prompt). */
|
||||
interface Snap {
|
||||
hand: number;
|
||||
phase: MahjongView['phase'];
|
||||
disc: number[];
|
||||
dora: number;
|
||||
call: number;
|
||||
drawn: string | null;
|
||||
claim: string | null;
|
||||
canDiscard: boolean;
|
||||
}
|
||||
const snapOf = (v: MahjongView): Snap => ({
|
||||
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<MahjongView>) {
|
||||
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<Banner | null>(null);
|
||||
const [dealing, setDealing] = useState(false);
|
||||
const [ref, width, mainH] = useBox<HTMLDivElement>();
|
||||
const seen = useSeen(v);
|
||||
const mine = isMyTurn(v, me);
|
||||
const prevMine = useRef(false);
|
||||
const snap = useRef<Snap | null>(null);
|
||||
const bannerSeq = useRef(0);
|
||||
const showBanner = (b: Omit<Banner, 'key'>) => 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
|
||||
<style>{CSS}</style>
|
||||
<ul className="mj-opps" aria-label="다른 사람">
|
||||
{others.map((s) => (
|
||||
<SeatChip key={s.seat} v={v} s={s} players={players} me={me} deadline={deadline} w={phone ? 13 : 18} />
|
||||
<SeatChip key={s.seat} v={v} s={s} players={players} me={me} deadline={deadline} w={phone ? 13 : 18} seen={seen} />
|
||||
))}
|
||||
</ul>
|
||||
<div className="mj-main" style={wide ? { width: tableWidth, maxHeight: mainH > 0 ? mainH - 12 : undefined } : undefined}>
|
||||
@@ -889,11 +1168,19 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
{v.phase === 'finished' && <FinalPanel v={v} players={players} me={me} />}
|
||||
{showTable && (
|
||||
<div className="mj-table-wrap">
|
||||
<Table v={v} players={players} width={tableWidth} callout={callout ? <span key={callout.seq} className="mj-callout">{callout.text}</span> : null} />
|
||||
<Table v={v} players={players} width={tableWidth} callout={callout ? <span key={callout.seq} className={`mj-callout c-${callout.call}`}>{callout.text}</span> : null} seen={seen} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{v.phase === 'playing' && v.my && <MyArea v={v} my={v.my} act={act} pending={pending} players={players} deadline={deadline} tapConfirm={tapConfirm} />}
|
||||
{v.phase === 'playing' && v.my && <MyArea v={v} my={v.my} act={act} pending={pending} players={players} deadline={deadline} tapConfirm={tapConfirm} seen={seen} dealing={dealing} />}
|
||||
{banner && (
|
||||
<div key={banner.key} className={`mj-banner ${banner.kind}`} aria-hidden>
|
||||
<span className="anim-banner">
|
||||
{banner.text}
|
||||
{banner.sub && <small>{banner.sub}</small>}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -962,7 +1249,7 @@ function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProp
|
||||
</span>
|
||||
)}
|
||||
<strong aria-hidden style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{fmt(s.points)}
|
||||
<Bump value={s.points} />
|
||||
</strong>
|
||||
</li>
|
||||
))}
|
||||
|
||||
46
apps/web/src/games/marble/events.test.ts
Normal file
46
apps/web/src/games/marble/events.test.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { movePath, newEvents, toSegments, type GameEvent } from './events';
|
||||
|
||||
const ev = (type: string, extra: Record<string, unknown> = {}): 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'], []],
|
||||
]);
|
||||
});
|
||||
86
apps/web/src/games/marble/events.ts
Normal file
86
apps/web/src/games/marble/events.ts
Normal file
@@ -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<string, number>): 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;
|
||||
}
|
||||
@@ -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<typeof setTimeout>;
|
||||
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<string, PublicUser>, me: string | null): string {
|
||||
const sp = SPACES[pos]!;
|
||||
@@ -312,72 +372,264 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
const my = v.my;
|
||||
const [focus, setFocus] = useState(0);
|
||||
const [info, setInfo] = useState<number | null>(null);
|
||||
const [anim, setAnim] = useState<Anim | null>(null);
|
||||
const [rolling, setRolling] = useState(false);
|
||||
const [rolling, setRolling] = useState<number | null>(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<Timer>());
|
||||
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<Record<number, { claim?: string; level?: number }>>({});
|
||||
useLayoutEffect(() => {
|
||||
const upd: Record<number, { claim?: string; level?: number }> = {};
|
||||
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<MarbleVi
|
||||
return m;
|
||||
}, [v.owned]);
|
||||
const seatOf = (id: string) => 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<MarbleVi
|
||||
<rect x={c.x} y={c.y} width={c.w} height={c.h} style={{ fill: ownerColor ? `color-mix(in srgb, ${ownerColor} 20%, var(--surface))` : 'var(--surface)' }} stroke="var(--border)" strokeWidth={2} />
|
||||
{a.band && sp.group && <rect x={a.band.x} y={a.band.y} width={a.band.w} height={a.band.h} fill={GROUP_COLORS[sp.group]} />}
|
||||
{a.band && sp.kind === 'tour' && <rect x={a.band.x} y={a.band.y} width={a.band.w} height={a.band.h} fill="#64748b" />}
|
||||
{ownerColor && <rect x={c.x + 4} y={c.y + 4} width={c.w - 8} height={c.h - 8} fill="none" stroke={ownerColor} strokeWidth={6} rx={4} />}
|
||||
{ownerColor && (
|
||||
<rect key={o!.owner} className={fresh[pos]?.claim === o!.owner ? 'anim-pop' : undefined} x={c.x + 4} y={c.y + 4} width={c.w - 8} height={c.h - 8} fill="none" stroke={ownerColor} strokeWidth={6} rx={4} />
|
||||
)}
|
||||
{o && o.level > 0 && a.band && (
|
||||
<g>
|
||||
{Array.from({ length: o.level }, (_, k) => {
|
||||
@@ -471,7 +727,11 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
const step = (horiz ? a.band!.w : a.band!.h) / (o.level + 1);
|
||||
const x = horiz ? a.band!.x + step * (k + 1) : a.band!.x + a.band!.w / 2;
|
||||
const y = horiz ? a.band!.y + a.band!.h / 2 : a.band!.y + step * (k + 1);
|
||||
return <BuildingIcon key={k} level={(k + 1) as Level} x={x} y={y} s={band * 0.85} />;
|
||||
return (
|
||||
<g key={k} className={fresh[pos]?.level === k + 1 ? 'anim-pop' : undefined}>
|
||||
<BuildingIcon level={(k + 1) as Level} x={x} y={y} s={band * 0.85} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
)}
|
||||
@@ -495,7 +755,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
{o ? `통행료 ${P(o.toll)}` : P(sp.price!)}
|
||||
</text>
|
||||
)}
|
||||
{trail?.has(pos) && <rect className="mb-trail" x={c.x} y={c.y} width={c.w} height={c.h} fill="var(--focus)" opacity={0} key={`t${anim!.seq}-${pos}`} />}
|
||||
{trail?.has(pos) && <rect className="mb-trail" x={c.x} y={c.y} width={c.w} height={c.h} fill="var(--focus)" opacity={0} key={`t${walk!.k}-${pos}`} />}
|
||||
{(pick || pos === decisionPos) && (
|
||||
<rect className={pick ? 'mb-pick' : undefined} x={c.x + 3} y={c.y + 3} width={c.w - 6} height={c.h - 6} fill="none" stroke="var(--focus)" strokeWidth={6} rx={6} />
|
||||
)}
|
||||
@@ -505,17 +765,26 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
})}
|
||||
{tokens.map(({ p, pos, idx, n }) => {
|
||||
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 (
|
||||
<g key={p.id + (moving ? `-${anim!.i}` : '')} className={moving ? 'mb-hop' : undefined} aria-hidden>
|
||||
<Token seat={p.seat} x={x} y={y} r={compact ? 15 : 12} />
|
||||
<g key={p.id + (moving ? `-${moving.k}-${moving.i}` : '')} className={moving ? (moving.seg.walk ? 'mb-hop' : 'mb-fly') : undefined} aria-hidden>
|
||||
{v.current === p.id && v.phase !== 'finished' && <circle className="mb-ring" cx={x} cy={y} r={r * 1.75} fill="none" stroke={SEAT_COLORS[p.seat]} strokeWidth={4} />}
|
||||
<Token seat={p.seat} x={x} y={y} r={r} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
<div className="mb-center">
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} rolling={rolling} card={card} onCardClose={() => setCard(null)} />
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} rolling={rolling !== null} card={card} onCardClose={() => setCard(null)} />
|
||||
</div>
|
||||
{banner && (
|
||||
<div className="mb-banner-wrap" aria-hidden>
|
||||
<div key={banner.k} className={`mb-banner anim-banner ${banner.kind}`}>
|
||||
{banner.text}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/** 루미큐브 화면 (docs/games/rummikub.md §9). Tap a tile to pick it up, then tap where it goes. */
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
|
||||
// Pure tile/set helpers only (no zod): keeps this lazy chunk small.
|
||||
import { findMeld, normalizeSet, pickDisjoint, setProblem, sortTiles, tileLabel, tileOf, type DraftSet, type JokerAs, type TileColor } from '@bg/games/rummikub/rules';
|
||||
import type { LogEntry, RummikubOptions, RummikubView } from '@bg/games/rummikub';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -17,8 +17,67 @@ const userOf = (players: Record<string, PublicUser>, id: string): PublicUser =>
|
||||
/** Colour + shape mark so colours never have to be told apart by hue alone (§9). */
|
||||
const MARK: Record<TileColor, string> = { K: '●', R: '♥', B: '◆', O: '★' };
|
||||
|
||||
/** Plastic-tile sounds (synthesized; the site volume is applied by feedback.ts). */
|
||||
const snd = {
|
||||
/** Tile picked up: a light tick. */
|
||||
pick: () => {
|
||||
noise(22, 0.07, 0, 'highpass', 5200);
|
||||
tone(2300, 26, 'triangle', 0.05);
|
||||
},
|
||||
/** Tile put down on the table / rack: short hard "딱". */
|
||||
place: (delay = 0) => {
|
||||
noise(32, 0.16, delay, 'bandpass', 3300, 2.4);
|
||||
tone(1550, 28, 'triangle', 0.07, delay);
|
||||
tone(430, 45, 'sine', 0.06, delay + 4);
|
||||
},
|
||||
/** Several tiles laid down one after another. */
|
||||
places: (n: number) => {
|
||||
for (let i = 0; i < Math.max(1, Math.min(n, 5)); i++) snd.place(i * 85);
|
||||
},
|
||||
/** A tile drawn from the face-down pool: slide, then onto the rack. */
|
||||
draw: (delay = 0) => {
|
||||
noise(130, 0.07, delay, 'bandpass', 1300, 0.7);
|
||||
snd.place(delay + 140);
|
||||
},
|
||||
/** Somebody else moving tiles while thinking (quiet). */
|
||||
shuffleQuiet: () => noise(28, 0.06, 0, 'bandpass', 3000, 2),
|
||||
};
|
||||
|
||||
/** A value that shows for `ms` and then clears itself (timer cleaned up on unmount). */
|
||||
function useTimed<T>(): [T | null, (v: T, ms: number) => void] {
|
||||
const [val, setVal] = useState<T | null>(null);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => () => clearTimeout(timer.current), []);
|
||||
const set = useCallback((v: T, ms: number) => {
|
||||
clearTimeout(timer.current);
|
||||
setVal(v);
|
||||
timer.current = setTimeout(() => setVal(null), ms);
|
||||
}, []);
|
||||
return [val, set];
|
||||
}
|
||||
|
||||
/** Wraps a number that bumps (anim-bump) whenever it changes after the first render. */
|
||||
function Bump({ value, children }: { value: number; children: React.ReactNode }) {
|
||||
const prev = useRef(value);
|
||||
const n = useRef(0);
|
||||
if (prev.current !== value) {
|
||||
prev.current = value;
|
||||
n.current += 1;
|
||||
}
|
||||
return (
|
||||
<span key={n.current} className={n.current ? 'rk-bump anim-bump' : 'rk-bump'}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.rk-root { width: 100%; align-self: stretch; flex: 1; min-height: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.rk-root { position: relative; width: 100%; align-self: stretch; flex: 1; min-height: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.rk-bump { display: inline-block; }
|
||||
.rk-banner { position: fixed; z-index: 40; top: 34%; left: 0; right: 0; margin: 0 auto; width: max-content; max-width: 92vw; text-align: center;
|
||||
padding: 12px 26px; border-radius: 18px; font-size: clamp(1.4rem, 5vw, 2.2rem); font-weight: 900; letter-spacing: -.01em;
|
||||
background: linear-gradient(#fffdf7, #f1e7cf); color: #111827; border: 2px solid #c9b98f; box-shadow: 0 4px 0 #b5a172, 0 12px 30px rgba(0,0,0,.35); }
|
||||
.rk-banner.big { background: linear-gradient(#fde68a, #f59e0b); border-color: #b45309; box-shadow: 0 4px 0 #92400e, 0 12px 30px rgba(0,0,0,.35); }
|
||||
.rk-players { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.rk-player { display: flex; align-items: center; gap: 6px; background: var(--surface); color: var(--text); border: 3px solid transparent;
|
||||
border-radius: 12px; padding: 4px 10px 4px 6px; box-shadow: var(--shadow); font-size: .9rem; min-height: 44px; }
|
||||
@@ -89,6 +148,7 @@ button.rk-tile:disabled { cursor: default; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.rk-tile { transition: none; }
|
||||
.rk-banner { display: none; }
|
||||
.rk-set.changed { animation: none; box-shadow: 0 0 0 3px #fde047; }
|
||||
}
|
||||
`;
|
||||
@@ -116,12 +176,15 @@ interface TileProps {
|
||||
selected?: boolean;
|
||||
hint?: boolean;
|
||||
fresh?: boolean;
|
||||
/** Extra animation class (anim-deal / anim-pop) and its CSS variables. */
|
||||
anim?: string;
|
||||
style?: CSSProperties;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
function Tile({ id, size = 'md', as, selected, hint, fresh, onClick }: TileProps) {
|
||||
function Tile({ id, size = 'md', as, selected, hint, fresh, anim, style, onClick }: TileProps) {
|
||||
const t = tileOf(id);
|
||||
const cls = `rk-tile${size !== 'md' ? ` ${size}` : ''}${hint ? ' hint' : ''}${fresh ? ' fresh' : ''}`;
|
||||
const cls = `rk-tile${size !== 'md' ? ` ${size}` : ''}${hint ? ' hint' : ''}${fresh ? ' fresh' : ''}${anim ? ` ${anim}` : ''}`;
|
||||
const body =
|
||||
t.kind === 'joker' ? (
|
||||
<>
|
||||
@@ -140,13 +203,13 @@ function Tile({ id, size = 'md', as, selected, hint, fresh, onClick }: TileProps
|
||||
const dataC = t.kind === 'num' ? t.color : undefined;
|
||||
if (!onClick) {
|
||||
return (
|
||||
<span className={cls} data-c={dataC} role="img" aria-label={label}>
|
||||
<span className={cls} data-c={dataC} role="img" aria-label={label} style={style}>
|
||||
{body}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<button type="button" className={cls} data-c={dataC} aria-pressed={!!selected} aria-label={label} onClick={onClick}>
|
||||
<button type="button" className={cls} data-c={dataC} aria-pressed={!!selected} aria-label={label} onClick={onClick} style={style}>
|
||||
{body}
|
||||
</button>
|
||||
);
|
||||
@@ -194,6 +257,14 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const wasMine = useRef(false);
|
||||
const lastLog = useRef<string>('');
|
||||
// Animations: tiles flying onto my rack, tiles newly on the table, a shaking area, a big banner.
|
||||
const [fly, setFly] = useTimed<{ ids: string[]; gap: number }>();
|
||||
const [pop, setPop] = useTimed<Set<string>>();
|
||||
const [shake, setShake] = useTimed<string>();
|
||||
const [banner, setBanner] = useTimed<{ text: string; big: boolean; seq: number }>();
|
||||
const bannerSeq = useRef(0);
|
||||
const showBanner = (text: string, big = false) => setBanner({ text, big, seq: ++bannerSeq.current }, 1700);
|
||||
const snap = useRef<{ log: string; gameNo: number; phase: string; turnNo: number; edits: number; melded: Record<string, boolean>; table: Set<string> } | null>(null);
|
||||
|
||||
const serverSets: DraftSet[] = useMemo(
|
||||
() => (v.draft ? v.draft.map((d) => (d.as ? { tileIds: d.tileIds, as: d.as } : { tileIds: d.tileIds })) : v.table.map((t) => ({ tileIds: t.tileIds, as: t.kind }))),
|
||||
@@ -231,6 +302,67 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
if (e.by !== me) setAnnounce(logText(e, players, me));
|
||||
}, [v.log]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Sounds + animations for what everybody did, from view changes only (the first view is just recorded).
|
||||
useEffect(() => {
|
||||
const e = v.log[v.log.length - 1];
|
||||
const now = {
|
||||
log: e ? `${v.match.gameNo}-${e.turn}-${e.kind}-${e.by}` : '',
|
||||
gameNo: v.match.gameNo,
|
||||
phase: v.phase,
|
||||
turnNo: v.turnNo,
|
||||
edits: v.draftEdits,
|
||||
melded: Object.fromEntries(v.seats.map((s) => [s.id, s.melded])),
|
||||
table: new Set(v.table.flatMap((t) => t.tileIds)),
|
||||
};
|
||||
const prev = snap.current;
|
||||
snap.current = now;
|
||||
if (!prev) return;
|
||||
// A new round: tiles shuffled and dealt onto my rack.
|
||||
if (now.gameNo !== prev.gameNo) {
|
||||
if (v.phase === 'playing') {
|
||||
sfx.shuffle();
|
||||
sfx.deal(6, 70);
|
||||
if (v.my) setFly({ ids: v.my.rack, gap: 35 }, 1400);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (e && now.log !== prev.log) {
|
||||
const mineMove = e.by === me;
|
||||
const name = nick(players, e.by);
|
||||
if (e.kind === 'commit' || e.kind === 'timeoutCommit') {
|
||||
snd.places(e.count);
|
||||
const added = [...now.table].filter((id) => !prev.table.has(id));
|
||||
if (!mineMove && added.length) setPop(new Set(added), 900);
|
||||
const firstMeld = !prev.melded[e.by] && now.melded[e.by];
|
||||
if (mineMove || firstMeld) sfx.good();
|
||||
if (firstMeld && !(v.phase !== 'playing' && v.round?.endReason === 'rackEmpty')) showBanner(mineMove ? '첫 등록 성공!' : `${name}님 첫 등록!`);
|
||||
} else if (e.kind === 'draw' || e.kind === 'timeoutDraw') {
|
||||
snd.draw();
|
||||
if (mineMove && v.my?.lastDrawn.length) setFly({ ids: v.my.lastDrawn, gap: 90 }, 900);
|
||||
} else if (e.kind === 'penalty') {
|
||||
sfx.bad();
|
||||
for (let i = 0; i < Math.min(e.count, 3); i++) snd.draw(250 + i * 160);
|
||||
setShake(mineMove ? 'rack' : `p:${e.by}`, 500);
|
||||
if (mineMove) {
|
||||
haptic([60, 40, 60]);
|
||||
if (v.my?.lastDrawn.length) setFly({ ids: v.my.lastDrawn, gap: 120 }, 1100);
|
||||
showBanner(`벌칙! ${e.count}장 가져오기`);
|
||||
}
|
||||
} else if (e.kind === 'pass') {
|
||||
sfx.whoosh();
|
||||
}
|
||||
} else if (v.current && v.current !== me && now.turnNo === prev.turnNo && now.edits > prev.edits) {
|
||||
// Somebody else is moving tiles around in their turn.
|
||||
snd.shuffleQuiet();
|
||||
}
|
||||
// The round is over: "다 냈다!" (the match result sound itself is played by the room page).
|
||||
if (prev.phase === 'playing' && v.phase !== 'playing' && v.round?.endReason === 'rackEmpty') {
|
||||
const w = v.round.winners;
|
||||
showBanner(w.includes(me ?? '') ? '다 냈다!' : `${w.map((p) => nick(players, p)).join(', ')}님 다 냈다!`, true);
|
||||
if (v.phase === 'roundEnd') sfx.fanfare();
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Drop selected tiles that disappeared (e.g. after undo on the server).
|
||||
useEffect(() => {
|
||||
setSel((s) => (s.every((id) => inSets.has(id) || rack.includes(id)) ? s : s.filter((id) => inSets.has(id) || rack.includes(id))));
|
||||
@@ -245,6 +377,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
if (!mine) return;
|
||||
setHintIds([]);
|
||||
setMsg('');
|
||||
snd.pick();
|
||||
setSel((s) => (s.includes(id) ? s.filter((x) => x !== id) : [...s, id]));
|
||||
};
|
||||
|
||||
@@ -258,6 +391,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
else setMsg('');
|
||||
const next = moveTiles(sets, sel, target, onTable0);
|
||||
if (!next) return;
|
||||
snd.place();
|
||||
setSel([]);
|
||||
send(next);
|
||||
};
|
||||
@@ -278,6 +412,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
setMsg(my?.melded ? '받침대 타일만으로 바로 만들 수 있는 묶음이 없어요. 바닥 묶음에 붙여 보거나 한 장 가져오세요.' : `받침대 타일만으로 ${v.options.initialMeldPoints}점을 만들기 어려워요. 한 장 가져오세요.`);
|
||||
return;
|
||||
}
|
||||
snd.pick();
|
||||
setHintIds(found.flat());
|
||||
setSel(found[0]!);
|
||||
setMsg(found.length > 1 ? `보라색 타일로 묶음 ${found.length}개를 만들 수 있어요. 첫 묶음을 골라 두었어요. "새 묶음"을 눌러 보세요.` : '보라색 타일로 묶음을 만들 수 있어요. 골라 두었으니 "새 묶음"을 눌러 보세요.');
|
||||
@@ -288,8 +423,18 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
setConfirm('commit');
|
||||
return;
|
||||
}
|
||||
// The server refuses this commit (nothing changes in the view), so the "틀렸어요" feedback is local.
|
||||
if (my?.check && !my.check.ok && (v.options.invalidCommitPenalty === 'reject' || !my.check.fromRack)) {
|
||||
sfx.bad();
|
||||
haptic(80);
|
||||
setShake('table', 500);
|
||||
}
|
||||
act({ type: 'commit', turn: v.turnNo });
|
||||
};
|
||||
const undoLike = (type: 'undoDraft' | 'resetDraft') => {
|
||||
sfx.whoosh();
|
||||
act({ type });
|
||||
};
|
||||
const draw = () => {
|
||||
if (my?.changed) setConfirm('draw');
|
||||
else act({ type: v.poolCount ? 'draw' : 'pass' });
|
||||
@@ -305,15 +450,17 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
return (
|
||||
<div className="rk-root">
|
||||
<style>{CSS}</style>
|
||||
<Players v={v} me={me} players={players} deadline={deadline} />
|
||||
<Players v={v} me={me} players={players} deadline={deadline} shake={shake} />
|
||||
|
||||
<section className="rk-table" aria-label="바닥">
|
||||
<section className={`rk-table${shake === 'table' ? ' anim-shake' : ''}`} aria-label="바닥">
|
||||
<div className="rk-table-head">
|
||||
<span>
|
||||
{showingDraft && !mine ? `${curName}님이 고민 중인 배치` : mine && my?.changed ? '바닥(확정 전)' : '바닥'}
|
||||
{thinking && !showingDraft ? ` · ${curName}님이 생각 중…` : ''}
|
||||
</span>
|
||||
<span aria-label={`남은 타일 ${v.poolCount}장`}>남은 타일 {v.poolCount}장</span>
|
||||
<span aria-label={`남은 타일 ${v.poolCount}장`}>
|
||||
남은 타일 <Bump value={v.poolCount}>{v.poolCount}</Bump>장
|
||||
</span>
|
||||
</div>
|
||||
{mine && my && !my.melded && (
|
||||
<div className="rk-meld">
|
||||
@@ -346,7 +493,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
</button>
|
||||
)}
|
||||
{d.tileIds.map((id) => (
|
||||
<Tile key={id} id={id} size="sm" as={jokerAs[id]} selected={sel.includes(id)} onClick={mine ? () => toggle(id) : undefined} />
|
||||
<Tile key={id} id={id} size="sm" as={jokerAs[id]} selected={sel.includes(id)} anim={pop?.has(id) ? 'anim-pop' : undefined} onClick={mine ? () => toggle(id) : undefined} />
|
||||
))}
|
||||
{mine && sel.length > 0 && (
|
||||
<button type="button" className="rk-slot" aria-label={`묶음 ${i + 1} 뒤에 놓기`} onClick={() => move({ set: i, at: 'end' })}>
|
||||
@@ -385,10 +532,10 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
: '타일을 눌러 고른 뒤 놓을 곳을 누르세요.')}
|
||||
</p>
|
||||
<div className="rk-bar" role="group" aria-label="내 차례 행동">
|
||||
<button type="button" className="btn btn-secondary" disabled={!my?.canUndo || pending} onClick={() => act({ type: 'undoDraft' })}>
|
||||
<button type="button" className="btn btn-secondary" disabled={!my?.canUndo || pending} onClick={() => undoLike('undoDraft')}>
|
||||
되돌리기
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" disabled={!my?.changed || pending} onClick={() => act({ type: 'resetDraft' })}>
|
||||
<button type="button" className="btn btn-secondary" disabled={!my?.changed || pending} onClick={() => undoLike('resetDraft')}>
|
||||
처음으로
|
||||
</button>
|
||||
{selFromSets ? (
|
||||
@@ -445,11 +592,23 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rk-rack" role="group" aria-label="내 받침대">
|
||||
<div className={`rk-rack${shake === 'rack' ? ' anim-shake' : ''}`} role="group" aria-label="내 받침대">
|
||||
{rack.length === 0 && <span className="rk-rack-empty">{my.rack.length ? '모두 바닥에 놓았어요.' : '타일이 없어요.'}</span>}
|
||||
{rack.map((id) => (
|
||||
<Tile key={id} id={id} selected={sel.includes(id)} hint={hintIds.includes(id)} fresh={fresh.has(id)} onClick={mine ? () => toggle(id) : undefined} />
|
||||
))}
|
||||
{rack.map((id) => {
|
||||
const k = fly ? fly.ids.indexOf(id) : -1;
|
||||
return (
|
||||
<Tile
|
||||
key={id}
|
||||
id={id}
|
||||
selected={sel.includes(id)}
|
||||
hint={hintIds.includes(id)}
|
||||
fresh={fresh.has(id)}
|
||||
anim={k >= 0 ? 'anim-deal' : undefined}
|
||||
style={k >= 0 ? ({ '--from-y': '-140px', '--from-x': '0px', '--anim-delay': `${k * fly!.gap}ms` } as CSSProperties) : undefined}
|
||||
onClick={mine ? () => toggle(id) : undefined}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -457,6 +616,11 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner && (
|
||||
<div key={banner.seq} className={`rk-banner anim-banner${banner.big ? ' big' : ''}`} aria-hidden>
|
||||
{banner.text}
|
||||
</div>
|
||||
)}
|
||||
{confirm === 'draw' && (
|
||||
<ConfirmSheet
|
||||
title="놓은 타일을 되돌리고 한 장 가져올까요?"
|
||||
@@ -480,7 +644,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
);
|
||||
}
|
||||
|
||||
function Players({ v, me, players, deadline }: { v: RummikubView; me: string | null; players: Record<string, PublicUser>; deadline: number | null }) {
|
||||
function Players({ v, me, players, deadline, shake }: { v: RummikubView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; shake: string | null }) {
|
||||
return (
|
||||
<div className="rk-players" role="list" aria-label="참가자">
|
||||
{v.seats.map((s) => {
|
||||
@@ -490,7 +654,7 @@ function Players({ v, me, players, deadline }: { v: RummikubView; me: string | n
|
||||
<div
|
||||
key={s.id}
|
||||
role="listitem"
|
||||
className={`rk-player${turn ? ' turn' : ''}${s.left || !s.inRound ? ' gone' : ''}`}
|
||||
className={`rk-player${turn ? ' turn' : ''}${s.left || !s.inRound ? ' gone' : ''}${shake === `p:${s.id}` ? ' anim-shake' : turn && v.phase === 'playing' ? ' anim-glow' : ''}`}
|
||||
aria-label={`${u.nickname}${s.id === me ? '(나)' : ''}, 타일 ${s.tiles}장, ${s.melded ? '첫 등록 함' : '첫 등록 전'}${turn ? ', 지금 차례' : ''}${s.left ? ', 나감' : s.away ? ', 자리 비움' : ''}`}
|
||||
>
|
||||
<Avatar user={u} size={26} />
|
||||
@@ -499,7 +663,7 @@ function Players({ v, me, players, deadline }: { v: RummikubView; me: string | n
|
||||
{s.id === me && <span className="muted"> (나)</span>}
|
||||
</span>
|
||||
<span className="rk-count" title="받침대 타일 수">
|
||||
{s.tiles}장
|
||||
<Bump value={s.tiles}>{s.tiles}</Bump>장
|
||||
</span>
|
||||
{!s.melded && s.inRound && (
|
||||
<span className="rk-badge" style={{ background: 'var(--surface-2)', color: 'var(--text-sub)' }}>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/** 요트 다이스 화면 (docs/games/yacht.md §9). */
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import type { Category, ScoreEntry, YachtOptions, YachtSheetView, YachtView } from '@bg/games/yacht';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -33,6 +33,52 @@ const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.n
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
// ---------------------------------------------------------------- sounds (docs/games/yacht.md §9 소리·움직임)
|
||||
|
||||
/** Dice rattled in the cup, then each rolled die clacking down as the tumble animation ends. */
|
||||
function rollSound(n: number, animated: boolean) {
|
||||
if (!animated) return sfx.dice();
|
||||
for (let i = 0; i < 7; i++) noise(30, 0.1, i * 50, 'bandpass', 1600 + (i % 3) * 350, 3);
|
||||
const land = ROLL_MS - 110;
|
||||
for (let i = 0; i < Math.min(n, 5); i++) {
|
||||
noise(45, 0.13, land + i * 28, 'lowpass', 1100);
|
||||
tone(680 + i * 70, 30, 'triangle', 0.05, land + i * 28);
|
||||
}
|
||||
}
|
||||
/** Die set aside (lower knock) or put back in the cup (lighter tick). */
|
||||
function holdSound(on: boolean) {
|
||||
if (on) {
|
||||
tone(520, 45, 'triangle', 0.13);
|
||||
noise(25, 0.06, 0, 'lowpass', 1800);
|
||||
} else tone(780, 40, 'triangle', 0.1);
|
||||
}
|
||||
/** Pencil scribble on the score sheet. */
|
||||
function writeSound() {
|
||||
for (let i = 0; i < 3; i++) noise(45, 0.07, i * 55, 'highpass', 3500 + i * 300);
|
||||
tone(990, 70, 'triangle', 0.08, 170);
|
||||
}
|
||||
/** A zero crossed into a box. */
|
||||
function zeroSound() {
|
||||
noise(160, 0.07, 0, 'lowpass', 500);
|
||||
tone(260, 180, 'triangle', 0.08, 0, { slideTo: 180 });
|
||||
}
|
||||
/** "Your turn" chime (the room page already plays one when the tab is hidden). */
|
||||
function turnCue(delay: number) {
|
||||
tone(660, 120, 'sine', 0.13, delay);
|
||||
tone(880, 160, 'sine', 0.13, delay + 120);
|
||||
}
|
||||
|
||||
/** Wraps a number that should bump when it changes (not on the first render). */
|
||||
function Bump({ value, children }: { value: number; children: ReactNode }) {
|
||||
const r = useRef({ v: value, n: 0 });
|
||||
if (r.current.v !== value) r.current = { v: value, n: r.current.n + 1 };
|
||||
return (
|
||||
<span key={r.current.n} className={r.current.n ? 'anim-bump' : undefined} style={{ display: 'inline-block' }}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.yt-wrap { width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 12px; }
|
||||
.yt-tray { display: flex; flex-direction: column; gap: 12px; align-items: stretch; }
|
||||
@@ -50,9 +96,11 @@ const CSS = `
|
||||
@keyframes yt-tumble { 0% { transform: translateY(-18px) rotate(-30deg) scale(.9); } 40% { transform: translateY(4px) rotate(200deg); }
|
||||
70% { transform: translateY(-6px) rotate(330deg); } 100% { transform: translateY(0) rotate(360deg); } }
|
||||
.yt-die.rolling { animation: yt-tumble ${ROLL_MS}ms ease-out both; }
|
||||
@keyframes yt-pop { 0% { transform: translate(-50%, -50%) scale(.4); opacity: 0; } 60% { transform: translate(-50%, -50%) scale(1.15); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); } }
|
||||
.yt-flash { position: fixed; left: 50%; top: 40%; transform: translate(-50%, -50%); z-index: 30; pointer-events: none; font-size: 4rem; font-weight: 900;
|
||||
color: #fde047; text-shadow: 0 4px 12px rgba(0,0,0,.55), 0 0 2px #854d0e; animation: yt-pop .5s ease-out both; white-space: nowrap; }
|
||||
.yt-flash { position: fixed; inset: 0; z-index: 30; pointer-events: none; display: flex; align-items: center; justify-content: center; padding-bottom: 18vh; }
|
||||
.yt-flash > div { font-size: clamp(2.4rem, 10vw, 4rem); font-weight: 900; line-height: 1.1; text-align: center; white-space: nowrap;
|
||||
color: #fde047; text-shadow: 0 4px 12px rgba(0,0,0,.55), 0 0 2px #854d0e; }
|
||||
.yt-flash small { display: block; font-size: .4em; color: #fff; }
|
||||
.yt-flash.sub > div { font-size: clamp(1.8rem, 7vw, 2.8rem); }
|
||||
.yt-roll { min-height: 64px; font-size: 1.2rem; }
|
||||
.yt-sheet { padding: 0; overflow: auto; }
|
||||
.yt-table { border-collapse: separate; border-spacing: 0; width: 100%; font-variant-numeric: tabular-nums; }
|
||||
@@ -75,8 +123,9 @@ const CSS = `
|
||||
.yt-cell:hover:not(:disabled) { border-color: var(--primary); color: var(--text); }
|
||||
.yt-cell:disabled { cursor: not-allowed; opacity: .35; }
|
||||
.yt-cell:focus-visible { outline: 3px solid var(--focus); outline-offset: 1px; }
|
||||
@keyframes yt-new { from { background: #fde68a; } to { background: transparent; } }
|
||||
.yt-new { animation: yt-new 1.6s ease-out; border-radius: 6px; }
|
||||
@keyframes yt-new { from { background: #fde68a; color: #1c1e21; } to { background: transparent; } }
|
||||
.yt-new { display: inline-block; min-width: 2em; animation: yt-new 1.6s ease-out, anim-bump .35s ease; border-radius: 6px; }
|
||||
.yt-new.zero { animation: yt-new 1.6s ease-out, anim-shake .4s ease; }
|
||||
.yt-bar { height: 8px; border-radius: 4px; background: var(--surface-2); overflow: hidden; }
|
||||
.yt-bar > span { display: block; height: 100%; background: var(--success); transition: width .3s; }
|
||||
.yt-pname { display: inline-block; max-width: 72px; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom; }
|
||||
@@ -89,7 +138,7 @@ const CSS = `
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.yt-die, .yt-die.held { transition: none; }
|
||||
.yt-die.rolling, .yt-flash, .yt-new { animation: none; }
|
||||
.yt-die.rolling, .yt-new, .yt-flash .anim-banner { animation: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -144,11 +193,15 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
const [held, setHeld] = useState<boolean[]>(v.held);
|
||||
const [anim, setAnim] = useState<RollAnim | null>(null);
|
||||
const [flick, setFlick] = useState<number[] | null>(null);
|
||||
const [flash, setFlash] = useState<string | null>(null);
|
||||
const [flash, setFlash] = useState<{ text: string; sub?: string; key: number } | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [confirm, setConfirm] = useState<{ category: Category; points: number } | null>(null);
|
||||
const prevRoll = useRef(v.rollSeq);
|
||||
const prevTurn = useRef(v.turnSeq);
|
||||
const prevCurrent = useRef(v.current);
|
||||
const prevScore = useRef(v.lastScore ? `${v.lastScore.player}:${v.lastScore.category}` : '');
|
||||
const prevUpper = useRef<Record<string, number>>(Object.fromEntries(Object.entries(v.sheets).map(([p, sh]) => [p, sh.upperBonus])));
|
||||
const prevHold = useRef({ seq: `${v.turnSeq}:${v.rollSeq}`, held: v.held.join() });
|
||||
const pointer = useRef<string>('');
|
||||
|
||||
// Server holds win once our own pending action is answered (optimistic taps in between).
|
||||
@@ -156,7 +209,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
if (!pending) setHeld(v.held);
|
||||
}, [v.held, v.turnSeq, v.rollSeq, pending]);
|
||||
|
||||
// Roll animation, yacht flash and screen-reader text when a new roll arrives.
|
||||
// Roll animation, sound, yacht flash and screen-reader text when a new roll arrives (anyone's roll).
|
||||
useLayoutEffect(() => {
|
||||
if (v.rollSeq <= prevRoll.current || !v.dice) {
|
||||
prevRoll.current = v.rollSeq;
|
||||
@@ -165,25 +218,33 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
prevRoll.current = v.rollSeq;
|
||||
const who = v.current === me ? '내가' : `${nick(players, v.current ?? '')}님이`;
|
||||
setAnnounce(`${who} 굴렸어요: ${v.dice.join(', ')}`);
|
||||
const mask = v.rollsUsed === 1 ? [true, true, true, true, true] : v.held.map((h) => !h);
|
||||
const animated = !reducedMotion();
|
||||
rollSound(mask.filter(Boolean).length, animated);
|
||||
if (v.dice.every((d) => d === v.dice![0])) {
|
||||
setFlash('요트!');
|
||||
setFlash({ text: '요트!', sub: v.current === me ? undefined : nick(players, v.current ?? ''), key: v.rollSeq });
|
||||
sfx.fanfare();
|
||||
haptic([80, 40, 80]);
|
||||
}
|
||||
if (reducedMotion()) {
|
||||
sounds.stone();
|
||||
return;
|
||||
}
|
||||
const mask = v.rollsUsed === 1 ? [true, true, true, true, true] : v.held.map((h) => !h);
|
||||
setAnim({ key: v.rollSeq, mask });
|
||||
if (animated) setAnim({ key: v.rollSeq, mask });
|
||||
}, [v.rollSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Someone else (re)holding dice: the same knock I hear on my own taps.
|
||||
useEffect(() => {
|
||||
const seq = `${v.turnSeq}:${v.rollSeq}`;
|
||||
const h = v.held.join();
|
||||
const p = prevHold.current;
|
||||
prevHold.current = { seq, held: h };
|
||||
if (p.seq !== seq || p.held === h || v.current === me) return;
|
||||
holdSound(v.held.filter(Boolean).length >= p.held.split(',').filter((x) => x === 'true').length);
|
||||
}, [v.held, v.turnSeq, v.rollSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!anim) return;
|
||||
const t = setInterval(() => setFlick([0, 1, 2, 3, 4].map(() => 1 + Math.floor(Math.random() * 6))), 70);
|
||||
const end = setTimeout(() => {
|
||||
setAnim(null);
|
||||
setFlick(null);
|
||||
sounds.stone();
|
||||
}, ROLL_MS);
|
||||
return () => {
|
||||
clearInterval(t);
|
||||
@@ -193,24 +254,37 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
|
||||
useEffect(() => {
|
||||
if (!flash) return;
|
||||
const t = setTimeout(() => setFlash(null), 1500);
|
||||
const t = setTimeout(() => setFlash(null), 1600);
|
||||
return () => clearTimeout(t);
|
||||
}, [flash]);
|
||||
|
||||
// Score announcement + my-turn cue on turn changes.
|
||||
// Score sound/banner/announcement + my-turn cue on turn changes (anyone's score).
|
||||
useEffect(() => {
|
||||
if (v.turnSeq === prevTurn.current) return;
|
||||
prevTurn.current = v.turnSeq;
|
||||
setConfirm(null);
|
||||
const ls = v.lastScore;
|
||||
if (ls) {
|
||||
const key = ls ? `${ls.player}:${ls.category}` : '';
|
||||
if (ls && key !== prevScore.current) {
|
||||
const who = ls.player === me ? '내가' : `${nick(players, ls.player)}님이`;
|
||||
setAnnounce(`${who} ${catName(ls.category, v.options.scoring)}에 ${ls.points}점을 기록했어요${ls.bonus ? ` (요트 보너스 +${ls.bonus})` : ''}${ls.auto ? ' (시간 초과로 자동 기록)' : ''}.`);
|
||||
const big = ls.bonus > 0 || (ls.points > 0 && (ls.category === 'yacht' || ls.category === 'largeStraight'));
|
||||
if (ls.points === 0 && !ls.bonus) zeroSound();
|
||||
else writeSound();
|
||||
if (big) sfx.good();
|
||||
const gotUpper = (v.sheets[ls.player]?.upperBonus ?? 0) > 0 && !(prevUpper.current[ls.player] ?? 0);
|
||||
if (gotUpper) {
|
||||
sfx.collect();
|
||||
setFlash({ text: '상단 보너스 +35', sub: ls.player === me ? undefined : nick(players, ls.player), key: v.turnSeq });
|
||||
} else if (ls.bonus) setFlash({ text: `요트 보너스 +${ls.bonus}`, sub: ls.player === me ? undefined : nick(players, ls.player), key: v.turnSeq });
|
||||
}
|
||||
if (v.phase === 'playing' && v.current === me) {
|
||||
haptic(40);
|
||||
if (document.visibilityState === 'hidden') sounds.myTurn();
|
||||
}
|
||||
prevScore.current = key;
|
||||
prevUpper.current = Object.fromEntries(Object.entries(v.sheets).map(([p, sh]) => [p, sh.upperBonus]));
|
||||
const mineNow = v.phase === 'playing' && v.current === me;
|
||||
if (mineNow) haptic(40);
|
||||
// Only when the turn comes back from someone else; a hidden tab gets the room page's chime instead.
|
||||
if (mineNow && prevCurrent.current !== me && document.visibilityState === 'visible') turnCue(350);
|
||||
prevCurrent.current = v.current;
|
||||
}, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const canRoll = myTurn && !pending && v.rollsUsed < 3 && !(v.rollsUsed > 0 && held.every(Boolean));
|
||||
@@ -219,6 +293,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
const toggle = (i: number) => {
|
||||
if (!canHold) return;
|
||||
const next = held.map((h, j) => (j === i ? !h : h));
|
||||
holdSound(next[i]!);
|
||||
setHeld(next);
|
||||
act({ type: 'hold', held: next });
|
||||
};
|
||||
@@ -248,7 +323,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
{v.phase === 'finished' ? '게임 끝' : `${v.round} / ${v.totalRounds} 라운드`}
|
||||
</strong>
|
||||
{v.current && (
|
||||
<span className="row small" style={{ gap: 6, flexWrap: 'nowrap', minWidth: 0 }}>
|
||||
<span key={v.turnSeq} className="row small anim-slide-up" style={{ gap: 6, flexWrap: 'nowrap', minWidth: 0 }}>
|
||||
<Avatar user={userOf(players, v.current)} size={24} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{curName} 차례</span>
|
||||
<span className="badge" aria-label={`굴린 횟수 ${v.rollsUsed}번`}>
|
||||
@@ -280,7 +355,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
})}
|
||||
</div>
|
||||
{myTurn ? (
|
||||
<button className="btn btn-primary btn-block yt-roll" disabled={!canRoll} onClick={roll}>
|
||||
<button className={`btn btn-primary btn-block yt-roll${canRoll ? ' anim-glow' : ''}`} disabled={!canRoll} onClick={roll}>
|
||||
{rollLabel}
|
||||
</button>
|
||||
) : (
|
||||
@@ -289,15 +364,18 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
</p>
|
||||
)}
|
||||
{myTurn && v.rollsUsed > 0 && v.rollsUsed < 3 && <p className="muted small" style={{ textAlign: 'center' }}>남길 주사위를 누르면 고정돼요. 점수표의 칸을 누르면 기록해요.</p>}
|
||||
{v.lastScore && <LastScore entry={v.lastScore} view={v} me={me} players={players} />}
|
||||
{v.lastScore && <LastScore key={`${v.lastScore.player}:${v.lastScore.category}`} entry={v.lastScore} view={v} me={me} players={players} />}
|
||||
</section>
|
||||
<ScoreSheet view={v} me={me} players={players} myTurn={myTurn} pending={pending} onScore={score} pointer={pointer} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{flash && (
|
||||
<div className="yt-flash" aria-hidden>
|
||||
{flash}
|
||||
<div className={`yt-flash${flash.text.length > 4 ? ' sub' : ''}`} aria-hidden>
|
||||
<div key={flash.key} className="anim-banner">
|
||||
{flash.text}
|
||||
{flash.sub && <small>{flash.sub}</small>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{confirm && (
|
||||
@@ -315,7 +393,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
|
||||
function LastScore({ entry: e, view: v, me, players }: { entry: ScoreEntry; view: YachtView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
return (
|
||||
<p className="small row" style={{ justifyContent: 'center', gap: 6 }}>
|
||||
<p className="small row anim-slide-up" style={{ justifyContent: 'center', gap: 6 }}>
|
||||
<span className="muted">방금:</span>
|
||||
<strong>{e.player === me ? '나' : nick(players, e.player)}</strong>
|
||||
<DiceRow dice={e.dice} size={20} />
|
||||
@@ -359,7 +437,7 @@ function ScoreSheet({
|
||||
if (val !== undefined) {
|
||||
const fresh = ls && ls.player === p && ls.category === c;
|
||||
return (
|
||||
<span key={fresh ? `n${v.turnSeq}` : 'f'} className={`yt-filled${fresh ? ' yt-new' : ''}`}>
|
||||
<span key={fresh ? `n${v.turnSeq}` : 'f'} className={`yt-filled${fresh ? ` yt-new${val === 0 ? ' zero' : ''}` : ''}`}>
|
||||
{val}
|
||||
</span>
|
||||
);
|
||||
@@ -443,7 +521,7 @@ function ScoreSheet({
|
||||
{sumRow('보너스 +35', (s) => (s.upperBonus ? `+${s.upperBonus}` : <span className="muted small">{`${Math.max(0, v.upperBonusThreshold - s.upper)} 남음`}</span>))}
|
||||
{lower.map(row)}
|
||||
{yz && sumRow('요트 보너스', (s) => (s.yahtzeeBonus ? `+${s.yahtzeeBonus}` : '-'))}
|
||||
{sumRow('총점', (s) => s.total, 'yt-total')}
|
||||
{sumRow('총점', (s) => <Bump value={s.total}>{s.total}</Bump>, 'yt-total')}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
@@ -463,7 +541,11 @@ function YachtSide({ view: v, me, players, act, deadline }: BoardProps<YachtView
|
||||
const sh = v.sheets[p]!;
|
||||
const turn = v.current === p;
|
||||
return (
|
||||
<div key={p} className="row" style={{ gap: 10, flexWrap: 'nowrap', padding: '4px 6px', borderRadius: 10, border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}>
|
||||
<div
|
||||
key={p}
|
||||
className={`row${turn && v.phase === 'playing' ? ' anim-glow' : ''}`}
|
||||
style={{ gap: 10, flexWrap: 'nowrap', padding: '4px 6px', borderRadius: 10, border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}
|
||||
>
|
||||
<span className="muted small" style={{ width: 16, textAlign: 'right' }}>
|
||||
{i + 1}
|
||||
</span>
|
||||
@@ -478,7 +560,7 @@ function YachtSide({ view: v, me, players, act, deadline }: BoardProps<YachtView
|
||||
</div>
|
||||
</div>
|
||||
<span style={{ fontWeight: 800, fontSize: '1.3rem', fontVariantNumeric: 'tabular-nums' }} aria-label={`${nick(players, p)} 총점 ${sh.total}점`}>
|
||||
{sh.total}
|
||||
<Bump value={sh.total}>{sh.total}</Bump>
|
||||
</span>
|
||||
{turn && v.phase === 'playing' && <TurnTimer deadline={deadline} totalMs={total} mine={p === me} size={40} />}
|
||||
</div>
|
||||
@@ -572,7 +654,7 @@ function Options({ value: o, onChange }: OptionsProps<YachtOptions>) {
|
||||
</Field>
|
||||
)}
|
||||
<Field label="한 차례 제한 시간">
|
||||
<Seg value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [0, '제한 없음']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
<Seg value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [0, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
</Field>
|
||||
<Field label="점수 미리 보기">
|
||||
<Seg value={o.showPreview ? 'on' : 'off'} options={[['on', '빈 칸에 보여 주기'], ['off', '보여 주지 않기']]} onChange={(k) => set({ showPreview: k === 'on' })} />
|
||||
@@ -586,7 +668,7 @@ function optionsSummary(o: YachtOptions): string {
|
||||
o.scoring === 'yacht51' ? '요트 12칸' : '13칸 변형',
|
||||
...(o.scoring === 'yacht51' && !o.fullHouseAllowsYacht ? ['풀 하우스에 요트 불인정'] : []),
|
||||
...(o.scoring === 'yahtzee' ? [o.yahtzeeJoker === 'forced' ? '추가 요트는 정해진 순서' : '추가 요트는 아무 칸'] : []),
|
||||
o.turnSeconds > 0 ? `한 차례 ${o.turnSeconds}초` : '시간 제한 없음',
|
||||
o.turnSeconds > 0 ? `한 차례 ${o.turnSeconds}초` : '시간 무제한',
|
||||
...(o.showPreview ? [] : ['미리 보기 끔']),
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user