병합: wt2/g3-tiles

This commit is contained in:
EJClaw
2026-10-13 13:37:59 +09:00
23 changed files with 1780 additions and 320 deletions

View File

@@ -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,10 +20,64 @@ 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;
return v.phase === 'guess' ? v.options.turnSeconds * 1000 : 10_000;
return v.phase === 'guess' ? (v.options.turnSeconds ?? 30) * 1000 : 10_000;
}
/** Seats starting with the one after `me` (clockwise); spectators see everyone. */
@@ -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>
@@ -864,7 +1025,12 @@ function Options({ value: o, onChange }: OptionsProps<DavinciOptions>) {
<Seg label="시작 타일 수" value={o.startTiles} options={[['auto', '자동(2·3명 4개, 4명 3개)'], [3, '3개'], [4, '4개'], [5, '5개']]} onChange={(startTiles) => set({ startTiles })} />
</Field>
<Field label="추리 제한 시간">
<Seg label="추리 제한 시간" value={o.turnSeconds} options={[[20, '20초'], [30, '30초'], [45, '45초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Seg
label="추리 제한 시간"
value={o.turnSeconds === null ? 'none' : String(o.turnSeconds)}
options={[['20', '20초'], ['30', '30초'], ['45', '45초'], ['60', '60초'], ['none', '무제한']]}
onChange={(k) => set({ turnSeconds: k === 'none' ? null : (Number(k) as 20 | 30 | 45 | 60) })}
/>
</Field>
<Field label="가능한 숫자 후보 표시(초보 도움)">
<Seg label="후보 표시" value={o.deductionHelper} options={[[false, '끄기'], [true, '켜기']]} onChange={(deductionHelper) => set({ deductionHelper })} />
@@ -894,7 +1060,7 @@ function optionsSummary(o: DavinciOptions): string {
o.jokers ? '조커 사용' : '조커 없음',
o.startTiles === 'auto' ? '시작 타일 자동' : `시작 타일 ${o.startTiles}개`,
o.chooseColors ? '색 골라 가져오기' : '무작위로 가져오기',
`추리 ${o.turnSeconds}초`,
o.turnSeconds === null ? '시간 무제한' : `추리 ${o.turnSeconds}초`,
...(o.tieOrder === 'white-left' ? ['같은 숫자는 흰색 먼저'] : []),
...(o.deductionHelper ? ['후보 표시'] : []),
].join(' · ');
@@ -942,7 +1108,10 @@ function Rules({ options }: { options?: DavinciOptions }) {
이미 공개된 같은 색·같은 숫자를 말하는 것처럼 말이 안 되는 추리도 할 수는 있어요(화면에서 알려 줘요). 오른쪽 <strong>추리 기록</strong>에서 누가 어떤 숫자를 말했는지 다시 볼 수 있어요.
</p>
<p className="muted">
시간 안에 추리하지 않으면 공개된 정보로 가장 가능성 있는 작은 숫자를 자동으로 말해요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 결과 화면에는 각자 맞힌 횟수와 추리 횟수가 나와요.
{o?.turnSeconds === null
? '시간 제한이 없어서 천천히 생각해도 돼요. 연결이 끊긴 채로 오래 지나면 공개된 정보로 가장 가능성 있는 작은 숫자를 자동으로 말해요.'
: '시간 안에 추리하지 않으면 공개된 정보로 가장 가능성 있는 작은 숫자를 자동으로 말해요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요.'}{' '}
결과 화면에는 각자 맞힌 횟수와 추리 횟수가 나와요.
</p>
</div>
);

View File

@@ -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(' · ');
}

View File

@@ -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>
))}
@@ -1065,8 +1352,8 @@ function Options({ value: o, onChange }: OptionsProps<MahjongOptions>) {
<Field label="대국 길이" help="동풍전 약 25분, 반장전 약 50분">
<Seg label="대국 길이" value={o.length} options={[['tonpuu', '동풍전'], ['hanchan', '반장전']]} onChange={(length) => set({ length })} />
</Field>
<Field label="타패 제한 시간">
<Seg label="타패 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
<Field label="타패 제한 시간" help={o.turnSeconds === 0 ? '무제한이면 울기·론 응답도 시간 없이 기다려요.' : undefined}>
<Seg label="타패 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [0, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
<Field label="초보 모드 허용" help="켜면 각자 대기패·역 힌트를 켜고 끌 수 있어요.">
<Seg label="초보 모드 허용" value={o.beginnerMode} options={onOff} onChange={(beginnerMode) => set({ beginnerMode })} />
@@ -1138,12 +1425,16 @@ function Options({ value: o, onChange }: OptionsProps<MahjongOptions>) {
<Field label="연풍패 머리 부수">
<Seg label="연풍패 머리 부수" value={o.renpuuPairFu} options={[[2, '2부'], [4, '4부']]} onChange={(renpuuPairFu) => set({ renpuuPairFu })} />
</Field>
<Field label="울기·론 응답 시간">
<Seg label="울기·론 응답 시간" value={o.claimSeconds} options={[[5, '5초'], [8, '8초'], [12, '12초'], [20, '20초']]} onChange={(claimSeconds) => set({ claimSeconds })} />
</Field>
<Field label="개인 예비 시간" help="타패 시간을 넘기면 깎이고, 매 국 5초씩 다시 채워져요.">
<Seg label="개인 예비 시간" value={o.timeBankSeconds} options={[[0, '없음'], [30, '30초'], [60, '60초'], [120, '120초']]} onChange={(timeBankSeconds) => set({ timeBankSeconds })} />
</Field>
{o.turnSeconds !== 0 && (
<>
<Field label="울기·론 응답 시간">
<Seg label="울기·론 응답 시간" value={o.claimSeconds} options={[[5, '5초'], [8, '8초'], [12, '12초'], [20, '20초']]} onChange={(claimSeconds) => set({ claimSeconds })} />
</Field>
<Field label="개인 예비 시간" help="타패 시간을 넘기면 깎이고, 매 국 5초씩 다시 채워져요.">
<Seg label="개인 예비 시간" value={o.timeBankSeconds} options={[[0, '없음'], [30, '30초'], [60, '60초'], [120, '120초']]} onChange={(timeBankSeconds) => set({ timeBankSeconds })} />
</Field>
</>
)}
<Field label="(3인) 쯔모 지불">
<Seg label="3인 쯔모 지불" value={o.sanmaTsumo} options={[['tsumoLoss', '쯔모손'], ['northBisection', '북가 몫 반씩']]} onChange={(sanmaTsumo) => set({ sanmaTsumo })} />
</Field>
@@ -1165,7 +1456,7 @@ function optionsSummary(o: MahjongOptions): string {
if (o.kuitan) parts.push('쿠이탕');
if (o.doubleRon === 'headBump') parts.push('머리튀기');
if (o.beginnerMode) parts.push('초보 모드');
parts.push(`${o.turnSeconds}초`);
parts.push(o.turnSeconds === 0 ? '시간 무제한' : `${o.turnSeconds}초`);
return parts.join(' · ');
}

View 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'], []],
]);
});

View 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;
}

View File

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

View File

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

View File

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

View File

@@ -15,7 +15,7 @@
| `startTiles` | 시작 타일 수 | `auto`(2·3인 4개, 4인 3개) / 3 / 4 / 5 | `auto` |
| `chooseColors` | 타일을 가져올 때 색을 고르게 하기(실물 규칙, 뒷면 색이 보임) | on / off(무작위) | on |
| `emptyPoolPenalty` | 더미가 비었을 때 틀리면 | `reveal-own`(자기 숨은 타일 1개 공개) / `none`(벌칙 없음) | `reveal-own` |
| `turnSeconds` | 추리 제한 시간 | 20 / 30 / 45 / 60 | 30 |
| `turnSeconds` | 추리 제한 시간 | 20 / 30 / 45 / 60 / null(무제한) | 30 |
| `deductionHelper` | 공개 정보로 가능한 숫자 후보 표시(초보 도움) | on / off | off |
## 3. 구성물
@@ -147,6 +147,7 @@ interface DavinciState {
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- 마감: `chooseStart` 15초, `draw` 10초, `guess` `turnSeconds`, `afterCorrect` 10초, `placeJoker`/`revealOwn` 10초.
- `turnSeconds = null`(무제한)이면 모든 단계에 마감이 없고 타이머도 안 보인다. 연결이 끊기면 방의 유예 시간 뒤 서버가 `timeout`을 보내 아래 자동 행동을 하는 처리는 그대로이고, 연속 3턴 자동으로 둔 사람에게는 무제한이어도 5초 마감이 붙는다(다시 직접 두면 풀림).
- `onTimeout`
- `chooseStart`: 가능한 한 반반(홀수면 검정 하나 더).
- `draw`: 더 많이 남은 색(같으면 검정).
@@ -183,6 +184,17 @@ interface GameResult {
- 초보 도움말: "규칙 보기"에 정렬 규칙 그림(작은 수 왼쪽, 같은 숫자면 검정 왼쪽)을 넣는다. `deductionHelper`를 켜면 숫자 패드에서 불가능한 숫자를 흐리게 표시한다(누를 수는 있음).
- 추리 기록 패널: "민수 → 영희 3번째 타일 = 7 (틀림)" 목록을 둔다. 노년층의 기억 부담을 줄인다.
### 9.1 소리·움직임
소리는 모두 화면 안에서 합성한다. 상대·컴퓨터의 행동은 화면 정보(추리 기록, 줄의 타일 수·공개 여부, 가져온 타일, 탈락 순서)가 바뀔 때 울리고, 처음 들어왔을 때·다시 접속했을 때는 울리지 않는다. 숨은 정보(남의 조커 위치 등)는 소리로도 드러나지 않는다.
- 시작 타일 색 고르기: 누가 고를 때마다 "딸깍". 다 고르면 나눠 주는 소리와 함께 모든 줄의 타일이 차례로 날아온다(anim-deal).
- 더미에서 가져오기(누구든): 미끄러지는 소리, 가져온 타일이 위에서 날아온다.
- 추리 맞힘: 타일이 뒤집혀 공개되며(뒤집기 + 초록 반짝임) 성공음. 내 타일이 맞혀졌으면 성공음 대신 아쉬운 내림음.
- 추리 틀림: 실패음 + 고른 타일이 흔들리고(anim-shake) 빨갛게 반짝인다. 이어서 가져온 타일이 뒤집혀 공개된 채로 줄에 들어간다.
- 멈추기·조커 넣기: 타일이 줄에 끼워지는 "딸깍"(위에서 내려와 자리 잡음). 보이는 조커면 반짝이는 소리가 더해진다.
- 더미가 빈 뒤 틀려서 내 타일 공개, 나간 사람 타일 공개: 뒤집기.
- 탈락: 배너("○○님 탈락!") + 내림음(게임이 끝나는 탈락이면 승리·패배음은 방 화면이 낸다). 게임이 끝나면 숨어 있던 타일이 차례로 뒤집힌다.
- 내 차례: 기존 차례 알림음. 지금 차례인 사람 줄은 은은하게 빛난다(anim-glow). 남은 타일 수·숨은 타일 수·맞힌 수가 바뀌면 숫자가 통 튄다(anim-bump).
## 10. 테스트 체크리스트
- [ ] 셋업: 2·3인은 각 4개, 4인은 각 3개. 시작 타일에 조커가 없다(`jokers=on`이어도). 같은 시드면 같은 분배가 나온다.
- [ ] `chooseStart`: 3인이 모두 "흰4"를 고르면 12개로 충분해 성공한다. 4인이 모두 "검3"을 고르는데 검정 12개면 성공하고, 이후 사람은 검정 0개만 남는다. 남은 수를 넘는 선택은 거부된다.

View File

@@ -120,7 +120,7 @@ interface LasVegasState {
- 라운드 간 더미는 다시 섞지 않는다(원작대로 돌려받은 지폐는 맨 아래).
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- `deadline`: `phase` 진입 시 `now + turnSeconds`(굴리기와 놓기 각각).
- `deadline`: `phase` 진입 시 `now + turnSeconds`(굴리기와 놓기 각각). `turnSeconds = null`(무제한)이면 `null`(시간 초과 없음, 연결 끊김 처리는 그대로).
- `onTimeout`:
- `roll` → `ROLL`.
- `place` → 결정적 선택: 나온 눈 중 (1) 해당 눈 주사위(own+neutral) 수가 가장 많은 것, (2) 동률이면 그 카지노 최고 지폐가 큰 것, (3) 그래도 같으면 작은 숫자.
@@ -145,6 +145,15 @@ interface LasVegasResult {
- 초보자 도움말: "같은 숫자는 한꺼번에", "개수가 같으면 둘 다 꽝" 두 문장을 첫 판에 크게 안내.
- 지폐는 실제 화폐와 다른 디자인(알록달록한 놀이용 지폐)으로, "만 달러" 대신 "포인트" 표기 옵션(UI 설정).
### 9.1 소리·움직임
소리는 모두 화면 안에서 합성한다. 다른 사람·컴퓨터의 행동도 화면 정보(굴림 번호, 차례 번호, 정산 기록)가 바뀔 때 똑같이 울리고, 처음 들어왔을 때·다시 접속했을 때는 울리지 않는다. 금액 비공개(`hideMoney`)면 소리·배너도 남의 금액을 드러내지 않는다(장 수만).
- 굴리기(누구든): 주사위 흔드는 소리 뒤, 구르는 움직임이 끝날 때 굴린 개수만큼 "딸깍"(최대 6번).
- 놓기(누구든): 놓은 개수만큼 "톡". 놓인 주사위 점이 카지노로 날아들고(anim-deal), 카지노가 커졌다 돌아온다. 그 카지노에서 동점이 생기면 경고음 + 카지노가 흔들린다.
- 정산: 동점 무효가 있으면 무너지는 소리, 받은 지폐 장수만큼 지폐 소리, 내가 받았으면 짤랑. 배너("○라운드 정산" + 내가 받은 점수). 정산 표의 동점 무효는 튀어나와 흔들리고, 받은 지폐는 차례로 날아든다. 다음 라운드 지폐가 카지노에 차례로 깔린다.
- 내 지폐: 새로 받은 지폐만 날아든다. 점수·장 수가 바뀌면 숫자가 통 튄다(anim-bump).
- 내 차례: 다른 사람에게서 차례가 넘어올 때 짧은 알림음(탭이 숨어 있으면 방 화면이 알림). 굴리기 버튼과 지금 차례인 사람 줄이 은은하게 빛난다(anim-glow).
## 10. 테스트 체크리스트
- [ ] 셋업: 지폐 54장 구성(6·8·8·6·6·5·5·5·5), 각 카지노 합 ≥ 5, 그리고 마지막 한 장을 빼면 5 미만(필요 이상으로 놓지 않음).
- [ ] `PLACE`는 그 눈의 주사위를 모두 옮긴다(일부만 불가). 나오지 않은 눈 거부.

View File

@@ -34,7 +34,7 @@
| `sanmaTsumo` | 산마 쯔모 지불 방식 | `tsumoLoss`(쯔모손: 없는 북가 몫 소멸) / `northBisection`(북가 몫을 둘이 반씩) | `tsumoLoss` |
| `sanmaHonba` | 산마 본장 1개당 점수 합계 | 200 / 300 / 1000 | 200 |
| `sanmaNotenPool` | 산마 유국 텐파이료 총액 | 2000 / 3000 | 2000 |
| `turnSeconds` | 타패 기본 제한 시간(초) | 5~60 | 15 |
| `turnSeconds` | 타패 기본 제한 시간(초). 0 = 무제한(타패·울기·론 응답 모두 마감 없음, 예비 시간 안 씀) | 0, 5~60 | 15 |
| `claimSeconds` | 울기·론 응답 창 시간(초) | 3~20 | 8 |
| `timeBankSeconds` | 개인 예비 시간(대국 전체, 매 국 +5초 충전, 최대값까지) | 0~300 | 60 |
| `beginnerMode` | 초보 모드 허용(개인별로 켜고 끔) | true / false | true |
@@ -505,6 +505,7 @@ interface MahjongState {
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- 차례 타이머: `turnSeconds` 소진 후 개인 `timeBank`를 깎는다. 둘 다 0이면 `onTimeout`.
- `turnSeconds = 0`(무제한): 타패 마감과 응답 창 마감이 없다(응답 창은 응답 가능자가 모두 답할 때까지 기다린다. 최소 지연 400ms는 그대로). 예비 시간은 깎지 않고, 타이머도 안 보인다. 연결이 끊긴 사람은 방의 유예 시간 뒤 서버가 `timeout`을 보내 자동 처리(쯔모기리·패스)하고, `autoPilot`이 되면 무제한이어도 차례 마감 2초가 붙는다. 결과 화면 15초는 차례 시간이 아니라서 그대로다.
- 응답 창: `claimSeconds` 고정, 예비 시간을 쓰지 않는다.
- `deadline(state)`: 현재 단계의 마감 시각(차례 = 시작 + 기본 + 남은 예비, 응답 창 = 창 마감, 결과 화면 = 표시 후 15초).
- `onTimeout(state, player)`:
@@ -544,6 +545,16 @@ interface MahjongResult {
- 규칙 보기: 역 목록(그림 예시), 점수표, 후리텐 설명, 용어집. 대국 중 하단 [?] 버튼으로 연다.
- 결과 화면: 국별 점수 변화 그래프, 최종 순위, 다시 하기.
### 9.1 소리·움직임
소리는 모두 화면 안에서 합성한다(패가 부딪히는 "딱" = 짧은 고음 잡음 + 높은 음). 다른 사람·컴퓨터의 행동도 화면 정보가 바뀔 때 똑같이 울리고(내 행동도 서버 응답으로 울려 두 번 나지 않음), 처음 들어왔을 때·다시 접속했을 때는 울리지 않는다. 숨은 정보(남의 손패·쯔모 패)는 소리로도 드러나지 않는다.
- 새 국: 패 섞는 소리(자라자라), 내 손패가 차례로 날아든다(anim-deal).
- 타패(누구든): "딱". 새로 버린 패는 버린 사람 쪽에서 강으로 던져진다. 쯔모(나): 미끄러지는 소리 + 새 패가 위에서 내려온다.
- 울기·리치·북 뽑기: 종류별 소리 + 판 가운데 말풍선(퐁 빨강, 치 초록, 깡 보라, 북 파랑, 리치 노랑). 새 울음 패·북은 톡 튀어나오고, 리치 막대는 위에서 떨어진다. 도라 표시패가 늘면 뒤집기.
- 론·쯔모: 큰 배너(누가) + 종류별 화음, 이어서 점수 옮기는 짤랑. 점수가 바뀌면 숫자가 통 튄다. 유국·도중유국: 내림음 + 배너.
- 내가 울거나 론할 수 있을 때: 알림음(론이면 더 급한 소리). 버릴 차례가 오면 차례 알림음. 버릴 수 없는 패를 누르면 경고음.
- 게임 끝: 1위 배너. 이기고 지는 소리는 방 화면이 내므로 여기서는 구경하는 사람에게만 팡파르.
## 10. 테스트 체크리스트
- [ ] 셋업: 같은 시드면 같은 좌석·패산·배패가 나온다. 4인 산패 70장, 산마 55장, 왕패 14장.
- [ ] 산마 패 구성: 2m~8m 없음, 108장, 1m 표시 → 9m 도라.

View File

@@ -290,7 +290,7 @@ interface MarbleState {
- 더미는 맨 아래로 돌려 넣으므로 다시 섞지 않는다.
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- `deadline`: 결정이 필요할 때마다 `now + turnSeconds`. 교환 응답은 20초 고정.
- `deadline`: 결정이 필요할 때마다 `now + turnSeconds`. 교환 응답은 20초 고정. `turnSeconds = null`(무제한)이면 교환 응답 말고는 `null`(시간 초과 없음, 연결 끊김 처리는 그대로).
- `onTimeout`(결정적):
- `turnStart`: 무인도면 `ROLL`(돈 쓰지 않음). 우주여행이면 `SPACE_TRAVEL { dest: 0 }`(출발, 월급). 그 외 `ROLL`.
- `decide`: `PASS`(자리 비운 사람의 돈을 마음대로 쓰지 않음).
@@ -318,6 +318,15 @@ interface MarbleResult {
- 애니메이션: 주사위 굴림, 돈이 오가는 숫자 팝업(+20, −100), 파산 시 땅 색이 회색으로.
- 초보자 도움말: 칸 종류별 설명, "더블이면 한 번 더, 3번 연속이면 무인도" 안내. 힌트 옵션: "이 땅을 사면 남은 돈 ○○" 경고(현금이 50 미만이 되면 주황색).
### 9.1 소리·움직임
소리는 모두 화면 안에서 합성한다. 다른 사람·컴퓨터의 행동은 기록(`log`)에 새로 붙은 사건으로 알아내 차례대로 재생하고, 처음 들어왔을 때·다시 접속했을 때·다시 보기에서 뒤로 갈 때는 울리지 않는다(`apps/web/src/games/marble/events.ts`). 돈 표현 규칙(점수·통행료 등, `no-money-wording.test.ts`)은 배너에도 그대로 지킨다.
- 굴리기: 주사위 소리 + 굴러가는 움직임(0.6초). 더블이면 배너("🎲 더블!")와 성공음(세 번째 더블로 무인도에 가면 무인도만).
- 말 이동: 주사위가 멈춘 뒤 한 칸씩 깡충 뛰며 걷고, 칸마다 "톡", 도착하면 "쿵". 지나간 칸은 잠깐 빛난다. 출발을 지나면 그 칸에서 짤랑(월급). 우주여행·순간이동은 걷지 않고 날아간다. 사건이 몰리면(8개 넘게 밀리면) 오래된 그림은 건너뛴다.
- 도착 처리(말이 도착한 뒤): 땅 사기는 도장 + 짤랑, 짓기는 망치 두 번 + 차임, 인수는 도장 + 빼앗는 소리, 통행료는 칩 세는 소리 + 종, 행운카드는 카드 뒤집기 + 가운데 카드, 무인도는 파도 + 배너("🏝️ 무인도!"), 우주여행은 로켓 + 배너, 독점은 팡파르 + 배너, 파산은 경보 + 배너. 기금 받기·카드로 받기는 짤랑, 내기는 칩 소리.
- 새로 산 땅의 테두리와 새 건물은 톡 튀어나온다(anim-pop). 지금 차례인 말 둘레에 고리가 은은하게 빛난다.
- 내 차례: 기존 차례 알림음(탭이 숨어 있으면 방 화면이 알림).
## 10. 테스트 체크리스트
- [ ] 판 데이터: 40칸 구성(도시 24, 관광지 4, 카드 7, 특수 5), 가격표 스냅샷 일치.
- [ ] 월급: 37에서 5칸 → 2 도착, 월급 1회. 0에 정확히 도착해도 1회. 뒤로 3칸 카드로 0을 거꾸로 지나면 월급 없음.

View File

@@ -11,7 +11,7 @@
| 옵션 키 | 설명 | 선택지 | 기본값 |
|---|---|---|---|
| `initialMeldPoints` | 첫 등록에 필요한 최소 점수 | 0(없음) / 20 / 30 / 50 | 30 |
| `turnSeconds` | 턴 제한 시간(공식 1분) | 60 / 90 / 120 / 180 | 60 |
| `turnSeconds` | 턴 제한 시간(공식 1분) | 60 / 90 / 120 / 180 / null(무제한) | 60 |
| `timeoutValidDraft` | 시간 초과 때 초안이 유효한 경우 처리 | `commit`(자동 확정) / `revert`(공식대로 되돌리고 1장 뽑기) | `commit` |
| `invalidTimeoutPenalty` | 시간 초과 때 초안이 무효한 경우 뽑는 장수(공식 3) | 1 / 3 | 3 |
| `invalidCommitPenalty` | "완료"를 눌렀는데 무효일 때 처리 | `reject`(거부만, 계속 수정) / `penalty3`(되돌리고 3장 뽑고 턴 종료) | `reject` |
@@ -246,7 +246,7 @@ function normalizeSet(d: DraftSet, tiles): TableSet | null {
- 그 외 진행 중에는 RNG를 쓰지 않는다(뽑기는 섞인 풀의 앞에서부터).
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- `deadline = turnStartedAt + turnSeconds*1000`.
- `deadline = turnStartedAt + turnSeconds*1000`. `turnSeconds = null`(무제한)이면 차례 마감이 없고 타이머도 안 보인다(`turnMs = 0`). 연결이 끊기면 방의 유예 시간 뒤 서버가 `timeout`을 보내는 처리는 그대로이고, 3번 연속 넘어간 자리 비움 사람에게는 무제한이어도 짧은 마감(3초)이 붙는다. 판 사이 준비 30초는 차례 시간이 아니라서 그대로다.
- `onTimeout(state, p)`는 내부 액션 `timeout`을 돌려준다. `apply`에서 5.7의 규칙대로 처리한다.
- 초안 변경 없음 → 1개 뽑기 또는 넘기기.
- 유효 초안 → `commit` 또는 되돌리고 1개 뽑기.
@@ -289,6 +289,19 @@ interface GameResult {
- 색 구분: 숫자 아래에 색별 모양(검정 ●, 빨강 ♥, 파랑 ◆, 주황 ★)을 넣어 색약 사용자도 구별할 수 있게 한다.
- 초보 도움말: 그룹과 런 그림 예시, 재배치 예시 애니메이션 4종(공식 규칙서의 예와 같은 상황).
### 9.1 소리·움직임
소리는 모두 화면 안에서 합성한다(플라스틱 타일 "딱" 소리 = 짧은 잡음 + 높은 음). 상대·컴퓨터의 행동은 화면 정보가 바뀔 때 울리고, 처음 들어왔을 때·다시 접속했을 때는 울리지 않는다. 내 타일 옮기기처럼 서버에 보이지 않는 조작만 누르는 순간 울린다.
- 타일 고르기: 가벼운 "틱". 바닥·받침대에 놓기: "딱". 되돌리기·처음으로: 휙.
- 확정(누구든): 놓은 장수만큼 "딱딱딱"(최대 5번). 내 확정이면 성공음이 더해진다. 다른 사람이 새로 놓은 타일은 톡 튀어나오고(anim-pop), 바뀐 묶음은 노랗게 반짝인다.
- 첫 등록: 성공음 + 배너("첫 등록 성공!" / "○○님 첫 등록!").
- 틀린 확정(서버가 받아 주지 않을 때): 실패음 + 바닥이 흔들린다(anim-shake).
- 한 장 가져오기(누구든): 미끄러지는 소리 뒤에 "딱". 내가 가져온 타일은 받침대 위쪽에서 날아와 꽂힌다(anim-deal).
- 벌칙(3장 등): 실패음 + 장수만큼 가져오는 소리. 내 벌칙이면 받침대가 흔들리고 배너, 다른 사람이면 그 사람 칸이 흔들린다.
- 넘기기: 휙. 다른 사람이 자기 차례에 타일을 옮기는 중이면 아주 작은 "딱".
- 새 판: 섞는 소리 + 나눠 주는 소리, 받침대 14장이 차례로 날아온다.
- 다 냈다: 큰 배너. 다음 판이 남아 있으면 팡파르(게임 전체가 끝날 때의 승리·패배음은 방 화면이 낸다).
- 내 차례: 기존 차례 알림음. 지금 차례인 사람 칸은 은은하게 빛난다(anim-glow). 남은 타일 수·사람별 타일 수가 바뀌면 숫자가 통 튄다(anim-bump).
## 10. 테스트 체크리스트
- [ ] 셋업: 106타일(숫자 104 + 조커 2), 각자 14개, 풀 크기(2인 78 / 3인 64 / 4인 50). 같은 시드면 같은 결과다.
- [ ] 세트 판정: [빨강12, 빨강13, 빨강1]은 무효. [파랑5, 빨강5, 파랑5]는 무효(색 중복). 5개짜리 그룹은 무효. [빨강1, 빨강2]는 무효(2개).

View File

@@ -13,7 +13,7 @@
| `scoring` | 점수 규칙 | `yacht51`(12칸, 51 수록판), `yahtzee`(13칸, 미국식 변형) | `yacht51` |
| `fullHouseAllowsYacht` | `yacht51`에서 5개가 모두 같은 눈을 풀하우스로 인정할지 | `true`, `false` | `true` |
| `yahtzeeJoker` | `yahtzee`에서 추가 요트(5개 같은 눈) 처리 | `forced`(공식 강제 조커), `free`(자유 선택 조커) | `forced` |
| `turnSeconds` | 한 차례 제한 시간 | 30, 60, 90, `null` | 60 |
| `turnSeconds` | 한 차례 제한 시간(0 = 무제한: 타이머·시간 초과 없음, 연결 끊김 처리는 그대로) | 30, 60, 90, 0 | 60 |
| `showPreview` | 아직 안 채운 칸에 "지금 넣으면 몇 점"을 미리 표시 | `true`, `false` | `true` |
## 3. 구성물
@@ -142,7 +142,7 @@ interface YachtState {
- `ROLL`: 고정되지 않은 주사위마다 `1 + floor(rng() * 6)`, 인덱스 0→4 순서로 호출(리플레이 일관성).
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- `deadline`: 차례 시작 시 `now + turnSeconds`(차례 전체에 대한 시간, 굴릴 때마다 초기화하지 않음).
- `deadline`: 차례 시작 시 `now + turnSeconds`(차례 전체에 대한 시간, 굴릴 때마다 초기화하지 않음). `turnSeconds = 0`(무제한)이면 `null`.
- `onTimeout`:
- `rollsUsed = 0` → `ROLL` (그 다음 즉시 다시 onTimeout이 호출되어 기록).
- `rollsUsed ≥ 1` → `SCORE`: 허용된 빈 칸 중 점수가 가장 높은 칸. 동점이면 6.1/6.2 표의 위쪽 칸 우선. 모든 칸이 0점이면 희생 순서 `ones → yacht → largeStraight → smallStraight → fullHouse → fourKind → threeKind → twos → threes → fours → fives → sixes → choice` 중 첫 빈 칸.
@@ -167,6 +167,16 @@ interface YachtResult {
- 초보자 도움말: "규칙 보기"에 칸별 조건과 예시 그림. 힌트 옵션: 추천 고정(간단한 휴리스틱: 가장 많은 같은 눈 유지)을 연하게 표시.
- 다른 사람 차례에도 주사위와 고정 상태가 실시간으로 보인다(관전 재미).
### 9.1 소리·움직임
소리는 모두 화면 안에서 합성한다. 다른 사람·컴퓨터의 굴림·고정·기록도 화면 정보가 바뀔 때 똑같이 울리고, 처음 들어왔을 때·다시 접속했을 때는 울리지 않는다.
- 굴리기(누구든): 컵 흔드는 소리 뒤, 구르는 움직임이 끝날 때 굴린 주사위 수만큼 "딸깍". 요트(5개 같은 눈)면 팡파르 + 배너("요트!", 남이면 이름).
- 주사위 고정/풀기: 고정은 낮은 "톡", 풀기는 가벼운 "틱". 다른 사람이 고정을 바꿔도 같은 소리.
- 점수 기록: 연필 소리(0점이면 내려가는 소리 + 칸이 흔들림). 요트·큰 스트레이트·요트 보너스는 성공음이 더해진다. 새로 적힌 칸은 노랗게 빛나며 통 튄다.
- 상단 보너스(+35)·요트 보너스: 짤랑 + 배너.
- 총점이 바뀌면 숫자가 통 튄다(anim-bump). "방금:" 줄과 차례 표시는 아래에서 올라온다(anim-slide-up).
- 내 차례: 다른 사람에게서 차례가 넘어올 때 짧은 알림음(탭이 숨어 있으면 방 화면이 알림). 굴리기 버튼과 지금 차례인 사람 줄이 은은하게 빛난다(anim-glow).
## 10. 테스트 체크리스트
- [ ] `yacht51` 점수: [6,6,6,6,2] 각 칸 값이 6.1 예시와 일치. [3,3,5,5,5] 풀 하우스 21. [1,2,3,4,6] 스몰 15, 라지 0. [2,3,4,5,6] 스몰 15, 라지 30.
- [ ] `fullHouseAllowsYacht`: [4,4,4,4,4] 풀 하우스 = 20(true) / 0(false).

View File

@@ -493,6 +493,26 @@ describe('시간 초과·연결 끊김 (§8.5)', () => {
}
});
test('무제한: 어느 단계도 마감이 없고, 연결이 끊겨 자동으로 둔 사람만 5초 마감', () => {
expect(davinci.optionsSchema.parse({ turnSeconds: null }).turnSeconds).toBeNull();
const players = ['A', 'B'];
let s = davinci.setup({ players, options: davinci.optionsSchema.parse({ turnSeconds: null }), rng: SeededRng.fromSeed(seedN(3)), now: 0 });
expect(davinci.deadline!(s)).toBeNull();
const r = SeededRng.fromSeed(seedN(4));
let sawIdle = false;
for (let step = 0; step < 3000 && s.phase.kind !== 'finished'; step++) {
const p = davinci.timeoutPlayers!(s)[0]!;
const idle = s.phase.kind !== 'chooseStart' && s.current === 'A' && (s.idle.A ?? 0) >= 3;
if (idle) sawIdle = true;
expect(davinci.deadline!(s) === null).toBe(!idle);
// A is disconnected (the room fires its timeouts after the grace period); B plays.
const a = p === 'A' ? davinci.onTimeout(s, p) : davinci.legalActions!(s, p)[0]!;
s = davinci.apply(s, p, a, { rng: r, now: step * 1000 }).state;
}
expect(s.phase.kind).toBe('finished');
expect(sawIdle).toBe(true);
});
test('all-AFK game (everyone times out) still ends', () => {
for (let seed = 1; seed <= 20; seed++) {
for (const emptyPoolPenalty of ['reveal-own', 'none'] as const) {

View File

@@ -32,9 +32,9 @@ export const davinciOptionsSchema = z.object({
.default('reveal-own')
.meta({ title: '더미가 빈 뒤 틀렸을 때', labels: { 'reveal-own': '내 숨은 타일 1개 공개', none: '벌칙 없음' } }),
turnSeconds: z
.union([z.literal(20), z.literal(30), z.literal(45), z.literal(60)])
.union([z.literal(20), z.literal(30), z.literal(45), z.literal(60), z.literal(null)])
.default(30)
.meta({ title: '추리 제한 시간', labels: { 20: '20초', 30: '30초', 45: '45초', 60: '60초' } }),
.meta({ title: '추리 제한 시간', labels: { 20: '20초', 30: '30초', 45: '45초', 60: '60초', null: '무제한' } }),
deductionHelper: z.boolean().default(false).meta({ title: '가능한 숫자 후보 표시(초보 도움)' }),
});
export type DavinciOptions = z.infer<typeof davinciOptionsSchema>;
@@ -255,21 +255,23 @@ export function candidatesFor(
function refreshDeadline(s: DavinciState, now: number, phaseChanged: boolean): void {
if (!phaseChanged) return;
s.phaseStartedAt = now;
// 무제한(turnSeconds null): no step has a clock; only an idle (disconnected, auto-played) player keeps the short one.
const unlimited = s.options.turnSeconds === null;
let ms: number | null;
switch (s.phase.kind) {
case 'finished':
ms = null;
break;
case 'chooseStart':
ms = CHOOSE_START_MS;
ms = unlimited ? null : CHOOSE_START_MS;
break;
case 'guess':
ms = s.options.turnSeconds * 1000;
ms = s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000;
break;
default:
ms = SHORT_MS;
ms = unlimited ? null : SHORT_MS;
}
if (ms !== null && s.phase.kind !== 'chooseStart' && (s.idle[s.current] ?? 0) >= IDLE_TURNS) ms = IDLE_MS;
if (s.phase.kind !== 'finished' && s.phase.kind !== 'chooseStart' && (s.idle[s.current] ?? 0) >= IDLE_TURNS) ms = IDLE_MS;
s.deadlineAt = ms === null ? null : now + ms;
}

View File

@@ -409,7 +409,7 @@ function openWindow(s: MahjongState, source: ClaimWindow['source'], tile: TileId
winning,
responses: eligible.map(() => null),
openedAt: ctx.now,
deadline: ctx.now + s.options.claimSeconds * 1000,
deadline: unlimited(s) ? null : ctx.now + s.options.claimSeconds * 1000,
minUntil: ctx.now + MIN_CLAIM_MS,
decided: false,
riichiPending,
@@ -1017,8 +1017,13 @@ function riichiOk(s: MahjongState, seat: Seat, tile: TileId): boolean {
// ---------------------------------------------------------------- timers
function turnLimitMs(s: MahjongState, seat: Seat): number {
return s.autoPilot[seat] ? AUTO_MS : s.options.turnSeconds * 1000 + s.timeBank[seat]!;
/** turnSeconds 0 = 무제한: no discard clock, no time bank, claim windows wait for every answer. */
const unlimited = (s: MahjongState) => s.options.turnSeconds === 0;
/** null = 무제한 (an auto-piloted seat still gets the short clock). */
function turnLimitMs(s: MahjongState, seat: Seat): number | null {
if (s.autoPilot[seat]) return AUTO_MS;
return unlimited(s) ? null : s.options.turnSeconds * 1000 + s.timeBank[seat]!;
}
function deadlineAt(s: MahjongState): number | null {
@@ -1026,7 +1031,10 @@ function deadlineAt(s: MahjongState): number | null {
if (s.phase === 'handResult') return s.resultAt + RESULT_MS;
const h = H(s);
if (h.stage === 'claim') return h.claim!.decided ? h.claim!.minUntil : h.claim!.deadline;
if (h.stage === 'afterDraw' || h.stage === 'afterCall') return h.turnStartedAt + turnLimitMs(s, h.turn);
if (h.stage === 'afterDraw' || h.stage === 'afterCall') {
const ms = turnLimitMs(s, h.turn);
return ms === null ? null : h.turnStartedAt + ms;
}
return null;
}
@@ -1336,7 +1344,7 @@ function buildView(s: MahjongState, viewer: PlayerId | null): MahjongView {
// Eligible players get their own countdown in `my.claim`.
let total = 0;
if (s.phase === 'handResult') total = RESULT_MS;
else if (live && h.stage !== 'claim') total = turnLimitMs(s, h.turn);
else if (live && h.stage !== 'claim') total = turnLimitMs(s, h.turn) ?? 0;
return {
mode: s.mode,
n,
@@ -1454,7 +1462,9 @@ export const mahjong: GameDefinition<MahjongState, MahjongAction, MahjongView, M
const h = s.hand;
// Time bank use for own-turn decisions.
if (h && s.phase === 'playing' && h.turn === seat && (h.stage === 'afterDraw' || h.stage === 'afterCall') && a.type !== 'setPref' && a.type !== 'leave') {
if (a.type === 'timeout') s.timeBank[seat] = s.autoPilot[seat] ? s.timeBank[seat]! : 0;
if (unlimited(s)) {
// No clock, nothing to spend.
} else if (a.type === 'timeout') s.timeBank[seat] = s.autoPilot[seat] ? s.timeBank[seat]! : 0;
else {
const over = now - h.turnStartedAt - s.options.turnSeconds * 1000;
if (over > 0) s.timeBank[seat] = Math.max(0, s.timeBank[seat]! - over);
@@ -1498,7 +1508,7 @@ export const mahjong: GameDefinition<MahjongState, MahjongAction, MahjongView, M
const due = c.decided ? c.minUntil : c.deadline;
// The discarder's timer only runs once the outcome is settled; it closes the window (also early, when the
// server fires it for a disconnected discarder — otherwise that timer would fire again and again).
if (now >= due || (c.decided && seat === c.from)) {
if ((due !== null && now >= due) || (c.decided && seat === c.from)) {
c.eligible.forEach((e, i) => {
if (e && !c.responses[i]) {
c.responses[i] = { type: 'pass' };

View File

@@ -1029,6 +1029,23 @@ describe('시간 초과 §8.5', () => {
expect(s.timeoutsInRow[1]).toBe(1);
expect(s.hand!.turn).toBe(1);
});
test('무제한(turnSeconds 0): 타패·응답 창 마감 없음, 예비 시간 그대로; 연결 끊긴 응답자는 서버 타이머로 패스', () => {
expect(mahjong.optionsSchema.safeParse({ turnSeconds: 0 }).success).toBe(true);
expect(mahjong.optionsSchema.safeParse({ turnSeconds: 3 }).success).toBe(false);
let s = rig(make(4, { turnSeconds: 0 }), { hands: ['*', T2, '*', '*'], drawn: '5m' });
expect(mahjong.deadline!(s)).toBeNull();
expect(view(s, 0).deadlineTotalMs).toBe(0);
s = act(s, 0, { type: 'discard', tile: codeIn(s, 0, '5m') }, 500_000);
expect(s.timeBank[0]).toBe(60_000);
expect(s.hand!.stage).toBe('claim');
expect(claimOf(s, 1)!.ron).toBe(true);
expect(claimOf(s, 1)!.deadline).toBeNull();
expect(mahjong.deadline!(s)).toBeNull();
// B is disconnected: the room fires B's timeout after the grace period → pass.
s = act(s, 1, { type: 'timeout' }, 600_000);
expect(s.hand!.turn).toBe(1);
expect(s.timeoutsInRow[1]).toBe(1);
});
test('예비 시간: 기본 시간을 넘긴 만큼 깎이고, 다음 국에 5초 충전', () => {
let s = rig(make(4), { hands: ['*', '*', '*', '*'], drawn: '5s' });
s = act(s, 0, { type: 'discard', tile: codeIn(s, 0, '5s') }, 25_000);

View File

@@ -46,7 +46,14 @@ export const mahjongOptionsSchema = z.object({
sanmaTsumo: z.enum(['tsumoLoss', 'northBisection']).default('tsumoLoss').meta({ title: '(3인) 쯔모 지불', labels: { tsumoLoss: '쯔모손(북가 몫 없음)', northBisection: '북가 몫을 둘이 반씩' } }),
sanmaHonba: lit(200, 300, 1000).default(200).meta({ title: '(3인) 본장 1개당 점수', labels: { 200: '200점', 300: '300점', 1000: '1,000점' } }),
sanmaNotenPool: lit(2000, 3000).default(2000).meta({ title: '(3인) 유국 텐파이료 합계', labels: { 2000: '2,000점', 3000: '3,000점' } }),
turnSeconds: z.number().int().min(5).max(60).default(15).meta({ title: '타패 제한 시간(초, 5~60)' }),
turnSeconds: z
.number()
.int()
.min(0)
.max(60)
.refine((v) => v === 0 || v >= 5, '5~60초 또는 0(무제한)이어야 해요.')
.default(15)
.meta({ title: '타패 제한 시간(초, 5~60, 0 = 무제한: 울기·론 응답도 기다려요)' }),
claimSeconds: z.number().int().min(3).max(20).default(8).meta({ title: '울기·론 응답 시간(초, 3~20)' }),
timeBankSeconds: z.number().int().min(0).max(300).default(60).meta({ title: '개인 예비 시간(초, 0~300)' }),
beginnerMode: z.boolean().default(true).meta({ title: '초보 모드 허용(대기패·역 힌트)' }),
@@ -118,7 +125,8 @@ export interface ClaimWindow {
winning: boolean[];
responses: (ClaimResponse | null)[];
openedAt: number;
deadline: number;
/** null = 무제한 (waits for every eligible answer). */
deadline: number | null;
/** The window never closes before this (information-leak mitigation, §5.3.2). */
minUntil: number;
/** The outcome is settled; only the minimum delay is left. */
@@ -306,7 +314,7 @@ export interface MyView {
kakan: string[];
canKita: boolean;
canKyuushu: boolean;
claim: { tile: string; source: ClaimWindow['source']; ron: boolean; pon: string[][]; kan: string[][]; chi: string[][]; responded: boolean; deadline: number; totalMs: number } | null;
claim: { tile: string; source: ClaimWindow['source']; ron: boolean; pon: string[][]; kan: string[][]; chi: string[][]; responded: boolean; deadline: number | null; totalMs: number } | null;
riichi: boolean;
furiten: boolean;
/** Current waits (13-tile state), with tiles left from what I can see. */

View File

@@ -926,6 +926,17 @@ describe('시간 초과·연결 끊김 (§8.5)', () => {
expect(s.timeouts.B).toBe(0);
});
test('제한 시간 무제한: 결정마다 마감이 없음(교환 응답은 20초 그대로)', () => {
let s = make({ turnSeconds: null });
expect(s.deadlineAt).toBeNull();
s = roll(s, 1, 2); // A → 3, buy decision
expect(s.phase).toBe('decide');
expect(s.deadlineAt).toBeNull();
s = act(s, 'A', { type: 'PASS' });
expect(curId(s)).toBe('B');
expect(s.deadlineAt).toBeNull();
});
test('onLeave = CONCEDE: 땅은 은행으로, 차례 넘김; 빚 갚는 중이면 그 빚은 먼저 갚음', () => {
let s = make({}, 3);
own(s, 1, 'A');

View File

@@ -20,16 +20,16 @@ import {
export * from './rules';
const lit = <T extends number>(...vals: T[]) =>
const lit = <T extends number | null>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
export const rummikubOptionsSchema = z.object({
initialMeldPoints: lit(0, 20, 30, 50)
.default(30)
.meta({ title: '첫 등록 최소 점수', labels: { 0: '없음', 20: '20점', 30: '30점(공식)', 50: '50점' } }),
turnSeconds: lit(60, 90, 120, 180)
turnSeconds: lit(60, 90, 120, 180, null)
.default(60)
.meta({ title: '한 차례 제한 시간', labels: { 60: '1분(공식)', 90: '1분 30초', 120: '2분', 180: '3분' } }),
.meta({ title: '한 차례 제한 시간', labels: { 60: '1분(공식)', 90: '1분 30초', 120: '2분', 180: '3분', null: '무제한' } }),
timeoutValidDraft: z
.enum(['commit', 'revert'])
.default('commit')
@@ -185,6 +185,7 @@ export interface RummikubView {
current: PlayerId | null;
turnNo: number;
turnStartedAt: number;
/** 0 = 무제한. */
turnMs: number;
poolCount: number;
table: TableSet[];
@@ -215,6 +216,12 @@ export interface RummikubView {
// ---------------------------------------------------------------- helpers
const AWAY_MS = 3000;
/** The current turn's time limit; null = 무제한 (a disconnected, auto-played player still gets the short one). */
function turnLimitMs(s: RummikubState): number | null {
if ((s.timeoutsInRow[s.current] ?? 0) >= 3) return AWAY_MS;
return s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000;
}
const ROUND_END_MS = 30_000;
const HISTORY_MAX = 100;
@@ -712,7 +719,7 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
current: playing ? s.current : null,
turnNo: s.turnNo,
turnStartedAt: s.turnStartedAt,
turnMs: (s.timeoutsInRow[s.current] ?? 0) >= 3 ? AWAY_MS : s.options.turnSeconds * 1000,
turnMs: turnLimitMs(s) ?? 0,
poolCount: s.pool.length,
table: s.table,
lastChanged: s.lastChanged,
@@ -748,7 +755,10 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
},
deadline(s) {
if (s.phase === 'playing') return s.turnStartedAt + ((s.timeoutsInRow[s.current] ?? 0) >= 3 ? AWAY_MS : s.options.turnSeconds * 1000);
if (s.phase === 'playing') {
const ms = turnLimitMs(s);
return ms === null ? null : s.turnStartedAt + ms;
}
if (s.phase === 'roundEnd') return (s.roundEndAt ?? 0) + ROUND_END_MS;
return null;
},

View File

@@ -421,6 +421,22 @@ describe('시간 초과 (§5.7, §8.5)', () => {
s = act(s, p, { type: 'draw' });
expect(s.timeoutsInRow[p]).toBe(0);
});
test('무제한: 차례 마감이 없고(타이머 0), 연결이 끊겨 3번 넘어간 사람만 짧은 마감', () => {
let s = mk({ turnSeconds: null }, ['A', 'B'], 2);
expect(rummikub.deadline!(s)).toBeNull();
expect(rummikub.view(s, null).turnMs).toBe(0);
const p = s.current;
for (let i = 0; i < 3; i++) {
s = act(s, p, { type: 'timeout' });
expect(rummikub.deadline!(s)).toBeNull();
s = act(s, s.current, { type: 'draw' });
}
expect(rummikub.deadline!(s)).toBe(s.turnStartedAt + 3000);
s = act(s, p, { type: 'draw' });
s = act(s, s.current, { type: 'draw' });
expect(rummikub.deadline!(s)).toBeNull();
});
});
// ---------------------------------------------------------------- scoring / end

View File

@@ -32,7 +32,7 @@ export const yachtOptionsSchema = z.object({
.meta({ title: '13칸 변형: 요트가 또 나왔을 때', labels: { forced: '정해진 순서대로 넣기(공식)', free: '아무 칸이나 고르기' } }),
turnSeconds: lit(30, 60, 90, 0)
.default(60)
.meta({ title: '한 차례 제한 시간', labels: { 30: '30초', 60: '60초', 90: '90초', 0: '제한 없음' } }),
.meta({ title: '한 차례 제한 시간', labels: { 30: '30초', 60: '60초', 90: '90초', 0: '무제한' } }),
showPreview: z.boolean().default(true).meta({ title: '빈 칸에 지금 넣을 때 점수 미리 보여 주기' }),
});
export type YachtOptions = z.infer<typeof yachtOptionsSchema>;