병합: wt2/g2-cards
This commit is contained in:
@@ -28,7 +28,7 @@ function practice(options: Record<string, unknown> = {}) {
|
|||||||
room.addBot('A');
|
room.addBot('A');
|
||||||
room.configure('A', { options: { ...(room.config.options as object), ...options } });
|
room.configure('A', { options: { ...(room.config.options as object), ...options } });
|
||||||
expect(room.start('A')).toBeNull();
|
expect(room.start('A')).toBeNull();
|
||||||
return { room, clock, msgs };
|
return { room, clock, msgs, a };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Bots move at once; when the game waits on the person, they play their first legal action (or the clock runs out). */
|
/** Bots move at once; when the game waits on the person, they play their first legal action (or the clock runs out). */
|
||||||
@@ -72,3 +72,19 @@ test('500 points with house rules: the person only times out, the computers stil
|
|||||||
const view = JSON.stringify(GAMES.uno!.view(s, 'A'));
|
const view = JSON.stringify(GAMES.uno!.view(s, 'A'));
|
||||||
for (const bot of s.seats.filter(isBotId)) for (const c of s.hands[bot]!) expect(view).not.toContain(`"${c.id}"`);
|
for (const bot of s.seats.filter(isBotId)) for (const c of s.hands[bot]!) expect(view).not.toContain(`"${c.id}"`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('무제한 time: no clock while the person is here; a dropped connection is still auto-played after the grace time', () => {
|
||||||
|
const { room, clock, a } = practice({ turnSeconds: null });
|
||||||
|
// Let the computers move until the game waits on the person.
|
||||||
|
for (let i = 0; i < 200 && room.bots.dueAt !== null; i++) room.bots.fire();
|
||||||
|
const s = () => room.game!.state as UnoState;
|
||||||
|
expect(GAMES.uno!.activePlayers(s())).toContain('A');
|
||||||
|
expect(room.effectiveDeadline()).toBeNull();
|
||||||
|
const turn = s().turnNo;
|
||||||
|
room.disconnect(a);
|
||||||
|
const d = room.effectiveDeadline();
|
||||||
|
expect(d).not.toBeNull();
|
||||||
|
clock.advance(d! - clock.advance(0) + 1);
|
||||||
|
room.onTimer();
|
||||||
|
expect(s().turnNo !== turn || s().log.some((e) => e.t === 'timeout' && e.p === 'A')).toBe(true);
|
||||||
|
});
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ export function helpNow(v: BangView, me: string | null, players: Record<string,
|
|||||||
if (use.length >= p.needed) {
|
if (use.length >= p.needed) {
|
||||||
const label = use.map((c) => NAME[c.kind as 'bang' | 'missed'] ?? '빗나감!').join(' + ');
|
const label = use.map((c) => NAME[c.kind as 'bang' | 'missed'] ?? '빗나감!').join(' + ');
|
||||||
lines.push(`[${label} 내기]를 누르면 막아요. 막지 않으려면 [맞기 (생명 −1)]를 눌러요.`);
|
lines.push(`[${label} 내기]를 누르면 막아요. 막지 않으려면 [맞기 (생명 −1)]를 눌러요.`);
|
||||||
if (v.options.autoDefend) lines.push('시간 안에 고르지 않으면 막을 카드를 자동으로 내요.');
|
if (v.options.autoDefend) lines.push(v.options.reactionSeconds === null ? '반응 시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 막을 카드를 자동으로 내요.' : '시간 안에 고르지 않으면 막을 카드를 자동으로 내요.');
|
||||||
} else lines.push(`막을 카드가 ${p.options.length > 0 ? '모자라요' : '없어요'}. [맞기 (생명 −1)]를 눌러요.`);
|
} else lines.push(`막을 카드가 ${p.options.length > 0 ? '모자라요' : '없어요'}. [맞기 (생명 −1)]를 눌러요.`);
|
||||||
if (p.canBarrel) lines.push('[술통 판정하기]를 누르면 카드를 한 장 뒤집어 ♥가 나올 때 피해요.');
|
if (p.canBarrel) lines.push('[술통 판정하기]를 누르면 카드를 한 장 뒤집어 ♥가 나올 때 피해요.');
|
||||||
lines.push(life);
|
lines.push(life);
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
/** 뱅! 화면 (docs/games/bang.md §9). */
|
/** 뱅! 화면 (docs/games/bang.md §9). */
|
||||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||||
import type { BangOptions, BangView, Card, CardFace, CardKind, CharacterId, LogEntry, PlayOption, PlayerView, Prompt, Role, Team } from '@bg/games/bang';
|
import type { BangOptions, BangView, Card, CardFace, CardKind, CharacterId, LogEntry, PlayOption, PlayerView, Prompt, Role, Team } from '@bg/games/bang';
|
||||||
import type { PublicUser } from '@bg/shared/lite';
|
import type { PublicUser } from '@bg/shared/lite';
|
||||||
import { Avatar } from '../../components/ui';
|
import { Avatar } from '../../components/ui';
|
||||||
import { TurnTimer } from '../../components/TurnTimer';
|
import { TurnTimer } from '../../components/TurnTimer';
|
||||||
import { haptic, sounds } from '../../lib/feedback';
|
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||||
|
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries, type BannerTone } from '../card-fx';
|
||||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||||
import { helpNow } from './help';
|
import { helpNow } from './help';
|
||||||
import { quickStart } from './quick';
|
import { quickStart } from './quick';
|
||||||
@@ -176,14 +177,91 @@ button.bg-card:focus-visible { outline: 3px solid var(--focus); outline-offset:
|
|||||||
.bg-me { padding: 8px; }
|
.bg-me { padding: 8px; }
|
||||||
}
|
}
|
||||||
@media (prefers-reduced-motion: reduce) { button.bg-card { transition: none; } }
|
@media (prefers-reduced-motion: reduce) { button.bg-card { transition: none; } }
|
||||||
|
.fx-ghost.bg-ghost { background: #fffaf0; border: 2px solid #92400e; box-shadow: 0 3px 8px rgba(0,0,0,.35); display: flex; align-items: center; justify-content: center;
|
||||||
|
font: 900 20px/1 system-ui, sans-serif; color: #1f2937; }
|
||||||
|
.fx-ghost.bg-ghost.blue { border-color: #1d4ed8; }
|
||||||
|
.fx-ghost.bg-ghost.chk { font-size: 14px; }
|
||||||
|
.fx-ghost.bg-ghost.chk.r { color: #dc2626; }
|
||||||
|
.fx-ghost.bg-ghost-back { background: repeating-linear-gradient(45deg, #7c2d12 0 5px, #9a3412 5px 10px); border: 2px solid #fdba74; box-shadow: 0 3px 8px rgba(0,0,0,.35); }
|
||||||
|
.fx-ghost.bg-bullet { background: none; border: 0; box-shadow: none; font-size: 22px; }
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- sounds + motion helpers
|
||||||
|
|
||||||
|
/** 뱅! sounds on top of the shared palette (synthesized; `d` = delay in ms). */
|
||||||
|
const shot = (d = 0) => {
|
||||||
|
noise(110, 0.32, d, 'bandpass', 1700, 0.6);
|
||||||
|
noise(40, 0.18, d, 'highpass', 4500);
|
||||||
|
tone(95, 170, 'sine', 0.26, d, { slideTo: 45 });
|
||||||
|
};
|
||||||
|
const bangSfx = {
|
||||||
|
shot,
|
||||||
|
gatling: (d = 0) => {
|
||||||
|
for (let i = 0; i < 7; i++) {
|
||||||
|
noise(60, 0.22, d + i * 85, 'bandpass', 1600 + (i % 3) * 250, 0.7);
|
||||||
|
tone(90, 80, 'sine', 0.15, d + i * 85, { slideTo: 50 });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/** 빗나감! / 술통: a ricochet whistle. */
|
||||||
|
ricochet: (d = 0) => {
|
||||||
|
noise(30, 0.08, d, 'highpass', 5000);
|
||||||
|
tone(2200, 300, 'sine', 0.07, d + 10, { slideTo: 700 });
|
||||||
|
},
|
||||||
|
hit: (d = 0) => {
|
||||||
|
noise(90, 0.2, d, 'lowpass', 500, 0.8);
|
||||||
|
tone(160, 200, 'sawtooth', 0.07, d, { slideTo: 70 });
|
||||||
|
},
|
||||||
|
/** Glug glug + clink. */
|
||||||
|
beer: (d = 0) => {
|
||||||
|
[0, 110, 220].forEach((x, i) => tone(240 - i * 25, 80, 'sine', 0.14, d + x, { slideTo: 150 }));
|
||||||
|
tone(2600, 140, 'triangle', 0.05, d + 340);
|
||||||
|
tone(3300, 120, 'triangle', 0.04, d + 360);
|
||||||
|
},
|
||||||
|
boom: (d = 0) => {
|
||||||
|
noise(900, 0.42, d, 'lowpass', 380, 0.7);
|
||||||
|
noise(120, 0.22, d, 'bandpass', 1200, 0.5);
|
||||||
|
tone(70, 800, 'sine', 0.3, d, { slideTo: 28 });
|
||||||
|
},
|
||||||
|
/** Jail bars. */
|
||||||
|
clank: (d = 0) => {
|
||||||
|
tone(330, 180, 'square', 0.05, d);
|
||||||
|
tone(495, 220, 'square', 0.04, d + 30);
|
||||||
|
noise(70, 0.14, d, 'bandpass', 4200, 3);
|
||||||
|
},
|
||||||
|
drums: (d = 0) =>
|
||||||
|
[0, 170, 340, 430, 520].forEach((x) => {
|
||||||
|
tone(120, 130, 'sine', 0.26, d + x, { slideTo: 65 });
|
||||||
|
noise(50, 0.08, d + x, 'lowpass', 320);
|
||||||
|
}),
|
||||||
|
duel: (d = 0) => {
|
||||||
|
shot(d);
|
||||||
|
shot(d + 340);
|
||||||
|
},
|
||||||
|
death: (d = 0) => tone(440, 750, 'triangle', 0.12, d, { slideTo: 100 }),
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 판정 card / role badge turning face up (Web Animations, no layout change). */
|
||||||
|
function flip(el: Element | null | undefined, delay = 0): void {
|
||||||
|
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||||
|
(el as HTMLElement).animate([{ transform: 'perspective(500px) rotateX(90deg)', opacity: 0.3 }, { transform: 'perspective(500px) rotateX(0deg)', opacity: 1 }], {
|
||||||
|
duration: 380,
|
||||||
|
delay,
|
||||||
|
easing: 'ease-out',
|
||||||
|
fill: 'backwards',
|
||||||
|
composite: 'add',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const sameFace = (a: CardFace, b: CardFace) => a.kind === b.kind && a.suit === b.suit && a.rank === b.rank;
|
||||||
|
const faceGhost = (f: CardFace) => ({ label: CARD_INFO[f.kind].icon, className: `bg-ghost${BLUE.includes(f.kind) ? ' blue' : ''}` });
|
||||||
|
const BACK_GHOST = { className: 'bg-ghost-back' };
|
||||||
|
|
||||||
// ---------------------------------------------------------------- small parts
|
// ---------------------------------------------------------------- small parts
|
||||||
|
|
||||||
function CardArt({ card, small, label }: { card: CardFace; small?: boolean; label?: boolean }) {
|
function CardArt({ card, small, label, fx }: { card: CardFace; small?: boolean; label?: boolean; fx?: string }) {
|
||||||
const info = CARD_INFO[card.kind];
|
const info = CARD_INFO[card.kind];
|
||||||
return (
|
return (
|
||||||
<span className={`bg-card${small ? ' sm' : ''}`} data-blue={BLUE.includes(card.kind)} aria-hidden={!label} {...(label ? { role: 'img', 'aria-label': faceAria(card) } : {})}>
|
<span className={`bg-card${small ? ' sm' : ''}`} data-fx={fx} data-blue={BLUE.includes(card.kind)} aria-hidden={!label} {...(label ? { role: 'img', 'aria-label': faceAria(card) } : {})}>
|
||||||
<CardFaceInner card={card} info={info} />
|
<CardFaceInner card={card} info={info} />
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
@@ -300,7 +378,7 @@ function Seat({
|
|||||||
) : p.isTurn && !v.reactions.length && !v.winner ? (
|
) : p.isTurn && !v.reactions.length && !v.winner ? (
|
||||||
<TurnTimer deadline={v.turnDeadline} totalMs={v.deadlineTotalMs} mine={p.id === me} size={26} />
|
<TurnTimer deadline={v.turnDeadline} totalMs={v.deadlineTotalMs} mine={p.id === me} size={26} />
|
||||||
) : null;
|
) : null;
|
||||||
const cls = `bg-seat${p.isTurn ? ' turn' : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}`;
|
const cls = `bg-seat${p.isTurn ? ` turn${v.winner ? '' : ' anim-glow'}` : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}`;
|
||||||
const body = (
|
const body = (
|
||||||
<>
|
<>
|
||||||
<span className="bg-row nw">
|
<span className="bg-row nw">
|
||||||
@@ -347,6 +425,7 @@ function Seat({
|
|||||||
style={style}
|
style={style}
|
||||||
data-target="ok"
|
data-target="ok"
|
||||||
data-player={p.id}
|
data-player={p.id}
|
||||||
|
data-fx-seat={p.id}
|
||||||
aria-pressed={mark.selected}
|
aria-pressed={mark.selected}
|
||||||
aria-label={`${seatLabel(p, players, me, shownRole(p, v, me))}. 대상으로 고르기`}
|
aria-label={`${seatLabel(p, players, me, shownRole(p, v, me))}. 대상으로 고르기`}
|
||||||
onClick={() => onPick(p.id)}
|
onClick={() => onPick(p.id)}
|
||||||
@@ -356,7 +435,7 @@ function Seat({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} role="group" aria-label={seatLabel(p, players, me, shownRole(p, v, me)) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} data-fx-seat={p.id} role="group" aria-label={seatLabel(p, players, me, shownRole(p, v, me)) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
||||||
{body}
|
{body}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -379,15 +458,15 @@ function Center({ v, players }: { v: BangView; players: Record<string, PublicUse
|
|||||||
const last = v.log[v.log.length - 1];
|
const last = v.log[v.log.length - 1];
|
||||||
return (
|
return (
|
||||||
<div className="bg-center">
|
<div className="bg-center">
|
||||||
<div className="bg-piles">
|
<div className="bg-piles" data-fx="bang-piles">
|
||||||
<span className="bg-back" role="img" aria-label={`카드 더미 ${v.deckCount}장`}>
|
<span className="bg-back" data-fx="bang-deck" role="img" aria-label={`카드 더미 ${v.deckCount}장`}>
|
||||||
{v.deckCount}
|
{v.deckCount}
|
||||||
</span>
|
</span>
|
||||||
{top ? <CardArt card={top} small label /> : <span className="bg-chip">버린 카드 없음</span>}
|
{top ? <CardArt card={top} small label fx="bang-discard" /> : <span className="bg-chip" data-fx="bang-discard">버린 카드 없음</span>}
|
||||||
</div>
|
</div>
|
||||||
{v.phase !== 'draft' && <span className="bg-chip">{v.round}라운드</span>}
|
{v.phase !== 'draft' && <span className="bg-chip">{v.round}라운드</span>}
|
||||||
{chk && (
|
{chk && (
|
||||||
<span className={`bg-chip ${chk.success ? 'ok' : 'bad'}`} aria-live="polite">
|
<span className={`bg-chip ${chk.success ? 'ok' : 'bad'}`} data-fx="bang-check" aria-live="polite">
|
||||||
{nick(players, chk.player)}님 {PURPOSE[chk.purpose]} 판정: {chk.cards.map((c) => `${SUIT_SYMBOL[c.suit]}${c.rank}`).join(' · ')} → {chk.success ? '성공' : '실패'}
|
{nick(players, chk.player)}님 {PURPOSE[chk.purpose]} 판정: {chk.cards.map((c) => `${SUIT_SYMBOL[c.suit]}${c.rank}`).join(' · ')} → {chk.success ? '성공' : '실패'}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -474,12 +553,14 @@ function HandCards({
|
|||||||
picked,
|
picked,
|
||||||
onTap,
|
onTap,
|
||||||
label,
|
label,
|
||||||
|
fx,
|
||||||
}: {
|
}: {
|
||||||
hand: Card[];
|
hand: Card[];
|
||||||
okOf?: (c: Card) => boolean | undefined;
|
okOf?: (c: Card) => boolean | undefined;
|
||||||
picked: (c: Card) => boolean;
|
picked: (c: Card) => boolean;
|
||||||
onTap: (c: Card) => void;
|
onTap: (c: Card) => void;
|
||||||
label: string;
|
label: string;
|
||||||
|
fx?: string;
|
||||||
}) {
|
}) {
|
||||||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||||||
@@ -490,7 +571,7 @@ function HandCards({
|
|||||||
btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length]?.focus();
|
btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length]?.focus();
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<div className="bg-hand" role="group" aria-label={label} onKeyDown={onKey}>
|
<div className="bg-hand" data-fx={fx} role="group" aria-label={label} onKeyDown={onKey}>
|
||||||
{hand.map((c) => {
|
{hand.map((c) => {
|
||||||
const ok = okOf?.(c);
|
const ok = okOf?.(c);
|
||||||
return (
|
return (
|
||||||
@@ -595,7 +676,7 @@ function MyArea({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="bg-me" aria-label="내 자리">
|
<section className="bg-me" aria-label="내 자리">
|
||||||
<div className="bg-mehead">
|
<div className="bg-mehead" data-fx="bang-me">
|
||||||
<RoleCard role={my.role} hints={hints} always={!!v.winner || !meP?.alive} />
|
<RoleCard role={my.role} hints={hints} always={!!v.winner || !meP?.alive} />
|
||||||
<span className="stack" style={{ gap: 2, flex: '1 1 220px', minWidth: 0 }}>
|
<span className="stack" style={{ gap: 2, flex: '1 1 220px', minWidth: 0 }}>
|
||||||
<strong>
|
<strong>
|
||||||
@@ -619,6 +700,7 @@ function MyArea({
|
|||||||
{prompt?.kind === 'draw' && <DrawPanel prompt={prompt} act={act} pending={pending} players={players} />}
|
{prompt?.kind === 'draw' && <DrawPanel prompt={prompt} act={act} pending={pending} players={players} />}
|
||||||
{meP?.alive && (
|
{meP?.alive && (
|
||||||
<HandCards
|
<HandCards
|
||||||
|
fx="bang-hand"
|
||||||
hand={my.hand}
|
hand={my.hand}
|
||||||
label={`내 카드 ${my.hand.length}장. 좌우 방향키로 고르고 Enter로 눌러요`}
|
label={`내 카드 ${my.hand.length}장. 좌우 방향키로 고르고 Enter로 눌러요`}
|
||||||
okOf={(c) => (discarding || sidMode ? undefined : playing ? !!optOf(c.id)?.ok : undefined)}
|
okOf={(c) => (discarding || sidMode ? undefined : playing ? !!optOf(c.id)?.ok : undefined)}
|
||||||
@@ -974,6 +1056,8 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (last && !mine) setAnnounce(logText(last, players));
|
if (last && !mine) setAnnounce(logText(last, players));
|
||||||
}, [last?.seq, last?.t]); // eslint-disable-line react-hooks/exhaustive-deps
|
}, [last?.seq, last?.t]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
const [banner, showBanner] = useBanner();
|
||||||
|
useBangFx(v, me, players, showBanner);
|
||||||
|
|
||||||
const n = v.players.length;
|
const n = v.players.length;
|
||||||
const myIdx = v.players.findIndex((p) => p.id === me);
|
const myIdx = v.players.findIndex((p) => p.id === me);
|
||||||
@@ -1018,10 +1102,313 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
|||||||
<p className="sr-only" aria-live="polite">
|
<p className="sr-only" aria-live="polite">
|
||||||
{announce}
|
{announce}
|
||||||
</p>
|
</p>
|
||||||
|
{banner}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const TEAM_TONE: Record<Team, BannerTone> = { law: 'blue', outlaws: 'red', renegade: 'gold' };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sounds + motion for every change of the table, mine or anyone else's: the log entries that are new since the last
|
||||||
|
* view (never on the first render, so joining / reloading / a replay jump stays quiet).
|
||||||
|
*/
|
||||||
|
function useBangFx(v: BangView, me: string | null, players: Record<string, PublicUser>, showBanner: (text: string, tone?: BannerTone, sub?: string) => void) {
|
||||||
|
// Entries of one action share `seq`; count repeats (two 판정 cards, Black Jack's two draws) so every key is unique.
|
||||||
|
const keyed = useMemo(() => {
|
||||||
|
const seen = new Map<string, number>();
|
||||||
|
return v.log.map((e) => {
|
||||||
|
const base = `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`;
|
||||||
|
const i = seen.get(base) ?? 0;
|
||||||
|
seen.set(base, i + 1);
|
||||||
|
return { e, k: `${base}-${i}` };
|
||||||
|
});
|
||||||
|
}, [v.log]);
|
||||||
|
/** Last known place of my hand cards: a card I played is gone from the DOM once the view arrives. */
|
||||||
|
const handRects = useRef(new Map<string, { r: DOMRect; f: CardFace }>());
|
||||||
|
/** Where my next new hand cards come from (deck by default) and when. */
|
||||||
|
const handSrc = useRef<{ from: Element | DOMRect | null; at: number } | null>(null);
|
||||||
|
|
||||||
|
const visible = (el: Element | null) => (el && el.getBoundingClientRect().width > 0 ? el : null);
|
||||||
|
/** A player's seat; my own seat is hidden on phones, so my area stands in for it. */
|
||||||
|
const place = (id: string): Element | null => visible(seatEl(id)) ?? (id === me ? fxEl('bang-me') : null);
|
||||||
|
/** Where a card I (or someone) just used came from. */
|
||||||
|
const srcOf = (id: string, f?: CardFace): Element | DOMRect | null => {
|
||||||
|
if (id === me && f) {
|
||||||
|
const hand = new Set(v.my?.hand.map((c) => c.id) ?? []);
|
||||||
|
for (const [cid, x] of handRects.current) {
|
||||||
|
if (hand.has(cid) || !sameFace(x.f, f)) continue;
|
||||||
|
handRects.current.delete(cid);
|
||||||
|
return x.r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return place(id);
|
||||||
|
};
|
||||||
|
const name = (id: string) => `${nick(players, id)}님`;
|
||||||
|
|
||||||
|
useNewEntries(
|
||||||
|
keyed,
|
||||||
|
(x) => x.k,
|
||||||
|
(fresh) => {
|
||||||
|
const deck = fxEl('bang-deck');
|
||||||
|
const pile = fxEl('bang-discard') ?? deck;
|
||||||
|
const piles = fxEl('bang-piles');
|
||||||
|
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
|
||||||
|
const toPile = (from: Element | DOMRect | null, f: CardFace | null, delay: number) => flyGhost(from, pile, { delay, ms: 420, ...(f ? faceGhost(f) : BACK_GHOST) });
|
||||||
|
const toMe = (from: Element | null, at: number) => (handSrc.current = { from, at });
|
||||||
|
const others = (p: string) => v.players.filter((x) => x.alive && x.id !== p).map((x) => x.id);
|
||||||
|
let healed = false;
|
||||||
|
let t = 0;
|
||||||
|
for (const { e } of fresh) {
|
||||||
|
const at = Math.min(t, 3000);
|
||||||
|
switch (e.t) {
|
||||||
|
case 'play': {
|
||||||
|
const k = e.as ?? e.card.kind;
|
||||||
|
toPile(srcOf(e.p, e.card), e.card, at);
|
||||||
|
later(at, sfx.cardPlay);
|
||||||
|
if (k === 'bang' && e.target) {
|
||||||
|
const tg = e.target;
|
||||||
|
flyGhost(place(e.p), place(tg), { kind: 'coin', label: '💥', className: 'bg-bullet', ms: 260, delay: at + 100 });
|
||||||
|
bangSfx.shot(at + 100);
|
||||||
|
later(at + 340, () => bump(place(tg), 'shake'));
|
||||||
|
if (tg === me) later(at, () => showBanner('뱅!', 'red', `${name(e.p)}이 쐈어요`));
|
||||||
|
t += 450;
|
||||||
|
} else if (k === 'gatling') {
|
||||||
|
bangSfx.gatling(at + 80);
|
||||||
|
later(at, () => showBanner('개틀링!', 'red', name(e.p)));
|
||||||
|
others(e.p).forEach((id, i) => later(at + 200 + i * 85, () => bump(place(id), 'shake')));
|
||||||
|
t += 750;
|
||||||
|
} else if (k === 'indians') {
|
||||||
|
bangSfx.drums(at + 60);
|
||||||
|
later(at, () => showBanner('인디언!', 'gold', name(e.p)));
|
||||||
|
others(e.p).forEach((id, i) => later(at + 150 + i * 90, () => bump(place(id))));
|
||||||
|
t += 650;
|
||||||
|
} else if (k === 'duel') {
|
||||||
|
bangSfx.duel(at + 80);
|
||||||
|
if (e.target && (e.p === me || e.target === me)) later(at, () => showBanner('결투!', 'dark', `${name(e.p)} vs ${name(e.target!)}`));
|
||||||
|
if (e.target) later(at + 120, () => bump(place(e.target!)));
|
||||||
|
t += 650;
|
||||||
|
} else if (k === 'generalStore') {
|
||||||
|
later(at + 100, sfx.shuffle);
|
||||||
|
t += 300;
|
||||||
|
} else if (k === 'panic' || k === 'catBalou') {
|
||||||
|
later(at + 100, sfx.whoosh);
|
||||||
|
t += 250;
|
||||||
|
} else t += 200;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'equip': {
|
||||||
|
const to = e.target ?? e.p;
|
||||||
|
flyGhost(srcOf(e.p, e.card), place(to), { delay: at, ms: 420, ...faceGhost(e.card) });
|
||||||
|
later(at, sfx.cardPlay);
|
||||||
|
if (e.card.kind === 'jail') {
|
||||||
|
bangSfx.clank(at + 400);
|
||||||
|
later(at + 400, () => bump(place(to), 'shake'));
|
||||||
|
} else later(at + 400, () => bump(place(to)));
|
||||||
|
if (e.replaced) toPile(place(to), e.replaced, at + 300);
|
||||||
|
t += 400;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'check': {
|
||||||
|
e.cards.forEach((c, i) => {
|
||||||
|
flyGhost(deck, pile, { delay: at + i * 220, ms: 380, label: `${SUIT_SYMBOL[c.suit]}${c.rank}`, className: `bg-ghost chk${sr(c) === 'r' ? ' r' : ''}` });
|
||||||
|
later(at + i * 220, sfx.cardFlip);
|
||||||
|
});
|
||||||
|
const end = at + 300 + (e.cards.length - 1) * 220;
|
||||||
|
flip(fxEl('bang-check'), end);
|
||||||
|
later(end + 80, e.success ? sfx.good : sfx.bad);
|
||||||
|
t += 450 + (e.cards.length - 1) * 220;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'dynamite':
|
||||||
|
if (e.exploded) {
|
||||||
|
bangSfx.boom(at);
|
||||||
|
later(at, () => {
|
||||||
|
showBanner('펑!', 'dark', `${name(e.p)} 앞에서 다이너마이트가 터졌어요`);
|
||||||
|
bump(place(e.p), 'shake');
|
||||||
|
});
|
||||||
|
t += 700;
|
||||||
|
} else if (e.to) {
|
||||||
|
flyGhost(place(e.p), place(e.to), { delay: at, ms: 420, label: '🧨', className: 'bg-ghost blue' });
|
||||||
|
later(at, sfx.whoosh);
|
||||||
|
t += 400;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'jail':
|
||||||
|
flyGhost(place(e.p), pile, { delay: at + 200, ms: 400, label: '🔒', className: 'bg-ghost blue' });
|
||||||
|
if (e.escaped) {
|
||||||
|
later(at, () => {
|
||||||
|
sfx.good();
|
||||||
|
bump(place(e.p));
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
bangSfx.clank(at);
|
||||||
|
later(at, () => bump(place(e.p), 'shake'));
|
||||||
|
if (e.p === me) later(at, () => showBanner('감옥!', 'dark', '이번 턴을 쉬어요'));
|
||||||
|
}
|
||||||
|
t += 450;
|
||||||
|
break;
|
||||||
|
case 'missed':
|
||||||
|
e.cards.forEach((c, i) => toPile(srcOf(e.p, c), c, at + i * 80));
|
||||||
|
bangSfx.ricochet(at);
|
||||||
|
later(at, () => bump(place(e.p)));
|
||||||
|
t += 350;
|
||||||
|
break;
|
||||||
|
case 'barrelSave':
|
||||||
|
bangSfx.ricochet(at);
|
||||||
|
later(at, () => bump(place(e.p)));
|
||||||
|
t += 300;
|
||||||
|
break;
|
||||||
|
case 'respond':
|
||||||
|
e.cards.forEach((c) => toPile(srcOf(e.p, c), c, at));
|
||||||
|
if (e.why === 'duel') bangSfx.shot(at + 80);
|
||||||
|
else later(at, sfx.cardPlay);
|
||||||
|
t += 350;
|
||||||
|
break;
|
||||||
|
case 'hit':
|
||||||
|
bangSfx.hit(at);
|
||||||
|
later(at, () => {
|
||||||
|
bump(place(e.p), 'shake');
|
||||||
|
if (e.p === me) haptic([40, 40, 40]);
|
||||||
|
});
|
||||||
|
t += 350;
|
||||||
|
break;
|
||||||
|
case 'heal':
|
||||||
|
e.cards?.forEach((c) => toPile(srcOf(e.p, c), c, at));
|
||||||
|
if (!healed) bangSfx.beer(at);
|
||||||
|
healed = healed || e.why === 'saloon';
|
||||||
|
later(at + 200, () => bump(place(e.p)));
|
||||||
|
t += e.why === 'saloon' ? 60 : 400;
|
||||||
|
break;
|
||||||
|
case 'draw': {
|
||||||
|
const n = Math.min(e.n, 6);
|
||||||
|
if (e.p === me) toMe(deck, at);
|
||||||
|
else flyGhost(deck, place(e.p), { count: n, gap: 80, delay: at, ...BACK_GHOST });
|
||||||
|
later(at, () => sfx.draw(Math.min(n, 4)));
|
||||||
|
t += 120 + 80 * Math.min(n, 4);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'blackJack':
|
||||||
|
later(at, sfx.cardFlip);
|
||||||
|
if (e.extra) later(at + 150, () => {
|
||||||
|
sfx.good();
|
||||||
|
bump(place(e.p));
|
||||||
|
});
|
||||||
|
t += 250;
|
||||||
|
break;
|
||||||
|
case 'pedro':
|
||||||
|
if (e.p === me) toMe(pile, at);
|
||||||
|
else flyGhost(pile, place(e.p), { delay: at, ms: 420, ...faceGhost(e.card) });
|
||||||
|
later(at, () => sfx.cardDeal());
|
||||||
|
t += 250;
|
||||||
|
break;
|
||||||
|
case 'take':
|
||||||
|
if (e.p === me) toMe(place(e.from), at);
|
||||||
|
else flyGhost(place(e.from), place(e.p), { delay: at, ms: 420, ...(e.equip ? faceGhost(e.equip) : e.card ? faceGhost(e.card) : BACK_GHOST) });
|
||||||
|
later(at, sfx.whoosh);
|
||||||
|
t += 300;
|
||||||
|
break;
|
||||||
|
case 'discarded':
|
||||||
|
toPile(place(e.p), e.card, at);
|
||||||
|
later(at, () => {
|
||||||
|
sfx.whoosh();
|
||||||
|
bump(place(e.p), 'shake');
|
||||||
|
});
|
||||||
|
t += 300;
|
||||||
|
break;
|
||||||
|
case 'limit':
|
||||||
|
e.cards.forEach((c, i) => toPile(srcOf(e.p, c), c, at + i * 70));
|
||||||
|
later(at, () => sfx.deal(Math.min(e.cards.length, 4)));
|
||||||
|
t += 250;
|
||||||
|
break;
|
||||||
|
case 'store':
|
||||||
|
if (e.p === me) toMe(piles, at);
|
||||||
|
else flyGhost(piles, place(e.p), { delay: at, ms: 420, ...faceGhost(e.card) });
|
||||||
|
later(at, () => sfx.cardDeal());
|
||||||
|
t += 250;
|
||||||
|
break;
|
||||||
|
case 'storeOpen':
|
||||||
|
later(at, () => sfx.deal(Math.min(e.cards.length, 7)));
|
||||||
|
later(at, () => bump(piles));
|
||||||
|
t += 300;
|
||||||
|
break;
|
||||||
|
case 'dead': {
|
||||||
|
const role = ROLE_INFO[e.role];
|
||||||
|
bangSfx.death(at);
|
||||||
|
later(at, () => {
|
||||||
|
showBanner(e.left ? `${name(e.p)} 탈락` : `${name(e.p)} 쓰러짐`, 'dark', `${role.icon} ${role.name}였어요`);
|
||||||
|
bump(place(e.p), 'shake');
|
||||||
|
});
|
||||||
|
flip(place(e.p)?.querySelector('.bg-role'), at + 200);
|
||||||
|
t += 900;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'reward':
|
||||||
|
later(at, sfx.collect);
|
||||||
|
t += 150;
|
||||||
|
break;
|
||||||
|
case 'penalty':
|
||||||
|
toPile(place(e.p), null, at);
|
||||||
|
later(at, sfx.bad);
|
||||||
|
t += 250;
|
||||||
|
break;
|
||||||
|
case 'vulture':
|
||||||
|
if (e.p === me) toMe(place(e.from), at);
|
||||||
|
else flyGhost(place(e.from), place(e.p), { count: Math.min(e.n, 6), gap: 70, delay: at, ...BACK_GHOST });
|
||||||
|
later(at, sfx.collect);
|
||||||
|
t += 350;
|
||||||
|
break;
|
||||||
|
case 'character':
|
||||||
|
later(at, sfx.select);
|
||||||
|
break;
|
||||||
|
case 'turn':
|
||||||
|
later(at, () => bump(place(e.p)));
|
||||||
|
t += 100;
|
||||||
|
break;
|
||||||
|
case 'timeout':
|
||||||
|
later(at, sfx.tick);
|
||||||
|
break;
|
||||||
|
case 'reshuffle':
|
||||||
|
later(at, () => {
|
||||||
|
sfx.shuffle();
|
||||||
|
bump(deck, 'shake');
|
||||||
|
});
|
||||||
|
t += 300;
|
||||||
|
break;
|
||||||
|
case 'end':
|
||||||
|
// The room already plays the win / lose sound.
|
||||||
|
later(at + 300, () => showBanner(`${TEAM_KO[e.winner]} 승리!`, TEAM_TONE[e.winner]));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
30,
|
||||||
|
);
|
||||||
|
|
||||||
|
// New cards in my hand fly in from wherever they came from (deck, discard pile, another seat, the store).
|
||||||
|
useNewEntries(
|
||||||
|
v.my?.hand,
|
||||||
|
(c) => c.id,
|
||||||
|
(fresh) => {
|
||||||
|
const src = handSrc.current ?? { from: fxEl('bang-deck'), at: 0 };
|
||||||
|
fresh.forEach((c, i) =>
|
||||||
|
flyFrom(document.querySelector(`[data-fx="bang-hand"] [data-id="${cssEsc(c.id)}"]`), src.from, { delay: Math.min(src.at, 3000) + i * 70, rotate: 8 }),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
20,
|
||||||
|
);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
handSrc.current = null;
|
||||||
|
const m = new Map<string, { r: DOMRect; f: CardFace }>();
|
||||||
|
for (const c of v.my?.hand ?? []) {
|
||||||
|
const el = document.querySelector(`[data-fx="bang-hand"] [data-id="${cssEsc(c.id)}"]`);
|
||||||
|
if (el) m.set(c.id, { r: el.getBoundingClientRect(), f: c });
|
||||||
|
}
|
||||||
|
handRects.current = m;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- side
|
// ---------------------------------------------------------------- side
|
||||||
|
|
||||||
function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
||||||
@@ -1034,7 +1421,7 @@ function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
|||||||
{v.winner ? ' · 게임 끝' : ''}
|
{v.winner ? ' · 게임 끝' : ''}
|
||||||
</strong>
|
</strong>
|
||||||
<span className="small muted">
|
<span className="small muted">
|
||||||
카드 더미 {v.deckCount}장 · 버린 카드 {v.discardCount}장 · 반응 {v.options.reactionSeconds}초 · 턴 {v.options.turnSeconds}초
|
카드 더미 {v.deckCount}장 · 버린 카드 {v.discardCount}장 · {secText('반응', v.options.reactionSeconds)} · {secText('턴', v.options.turnSeconds)}
|
||||||
</span>
|
</span>
|
||||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||||
{v.players.map((p) => (
|
{v.players.map((p) => (
|
||||||
@@ -1132,7 +1519,7 @@ function statusText(v: BangView, me: string | null, players: Record<string, Publ
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- options
|
// ---------------------------------------------------------------- options
|
||||||
|
|
||||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="segmented" role="group" aria-label={label}>
|
<div className="segmented" role="group" aria-label={label}>
|
||||||
{options.map(([k, l]) => (
|
{options.map(([k, l]) => (
|
||||||
@@ -1168,10 +1555,10 @@ function Options({ value: o, onChange }: OptionsProps<BangOptions>) {
|
|||||||
<Seg label="캐릭터 정하기" value={o.characterDraft} options={[['random', '무작위 1장'], ['choose2', '2장 중 고르기']]} onChange={(characterDraft) => set({ characterDraft })} />
|
<Seg label="캐릭터 정하기" value={o.characterDraft} options={[['random', '무작위 1장'], ['choose2', '2장 중 고르기']]} onChange={(characterDraft) => set({ characterDraft })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="내 턴 제한 시간">
|
<Field label="내 턴 제한 시간">
|
||||||
<Seg label="내 턴 제한 시간" value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [120, '120초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
<Seg label="내 턴 제한 시간" value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [120, '120초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="반응 제한 시간" help="빗나감!·맥주·결투·잡화점을 고르는 시간이에요.">
|
<Field label="반응 제한 시간" help="빗나감!·맥주·결투·잡화점을 고르는 시간이에요. 무제한이어도 연결이 끊긴 채 오래 돌아오지 않으면 자동으로 골라요.">
|
||||||
<Seg label="반응 제한 시간" value={o.reactionSeconds} options={[[8, '8초'], [15, '15초'], [25, '25초']]} onChange={(reactionSeconds) => set({ reactionSeconds })} />
|
<Seg label="반응 제한 시간" value={o.reactionSeconds} options={[[8, '8초'], [15, '15초'], [25, '25초'], [null, '무제한']]} onChange={(reactionSeconds) => set({ reactionSeconds })} />
|
||||||
</Field>
|
</Field>
|
||||||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||||||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||||||
@@ -1208,8 +1595,10 @@ function Options({ value: o, onChange }: OptionsProps<BangOptions>) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const secText = (what: string, sec: number | null) => (sec === null ? `${what} 시간 무제한` : `${what} ${sec}초`);
|
||||||
|
|
||||||
function optionsSummary(o: BangOptions): string {
|
function optionsSummary(o: BangOptions): string {
|
||||||
const parts = [o.characterDraft === 'choose2' ? '캐릭터 고르기' : '캐릭터 무작위', `턴 ${o.turnSeconds}초`, `반응 ${o.reactionSeconds}초`];
|
const parts = [o.characterDraft === 'choose2' ? '캐릭터 고르기' : '캐릭터 무작위', secText('턴', o.turnSeconds), secText('반응', o.reactionSeconds)];
|
||||||
if (!o.autoDefend) parts.push('자동 방어 끔');
|
if (!o.autoDefend) parts.push('자동 방어 끔');
|
||||||
if (o.drawBeforeDeath || o.beerAtFullHealth || o.selfTargetCatBalou || o.deputyCount7) parts.push('하우스 룰');
|
if (o.drawBeforeDeath || o.beerAtFullHealth || o.selfTargetCatBalou || o.deputyCount7) parts.push('하우스 룰');
|
||||||
return parts.join(' · ');
|
return parts.join(' · ');
|
||||||
@@ -1239,7 +1628,7 @@ function CardTable() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Rules() {
|
function Rules({ options }: { options?: BangOptions }) {
|
||||||
return (
|
return (
|
||||||
<div className="stack">
|
<div className="stack">
|
||||||
<p>
|
<p>
|
||||||
@@ -1256,7 +1645,10 @@ function Rules() {
|
|||||||
<p>
|
<p>
|
||||||
생명이 0이 되면 맥주로 살아날 수 있어요(2명 남으면 안 돼요). 무법자를 쓰러뜨리면 카드 3장을 받고, 보안관이 부관을 쓰러뜨리면 카드를 모두 버려요. 쓰러진 사람의 역할은 공개돼요.
|
생명이 0이 되면 맥주로 살아날 수 있어요(2명 남으면 안 돼요). 무법자를 쓰러뜨리면 카드 3장을 받고, 보안관이 부관을 쓰러뜨리면 카드를 모두 버려요. 쓰러진 사람의 역할은 공개돼요.
|
||||||
</p>
|
</p>
|
||||||
<p className="small muted">반응 시간이 지나면 막을 카드가 있을 때 자동으로 내요(설정에서 끌 수 있어요). 내 역할은 역할 카드를 꾹 누르고 있을 때만 보여요.</p>
|
<p className="small muted">
|
||||||
|
{options?.reactionSeconds === null ? '이 방은 반응 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '반응 시간이 지나면'} 막을 카드가 있을 때 자동으로 내요(설정에서 끌 수
|
||||||
|
있어요).{options?.turnSeconds === null ? ' 내 턴도 시간 제한이 없고, 연결이 끊긴 채 오래 돌아오지 않으면 턴을 자동으로 마쳐요.' : ''} 내 역할은 역할 카드를 꾹 누르고 있을 때만 보여요.
|
||||||
|
</p>
|
||||||
<CardTable />
|
<CardTable />
|
||||||
<table className="bg-rules small" style={{ borderCollapse: 'collapse', width: '100%' }}>
|
<table className="bg-rules small" style={{ borderCollapse: 'collapse', width: '100%' }}>
|
||||||
<tbody>
|
<tbody>
|
||||||
|
|||||||
228
apps/web/src/games/card-fx.tsx
Normal file
228
apps/web/src/games/card-fx.tsx
Normal file
@@ -0,0 +1,228 @@
|
|||||||
|
/**
|
||||||
|
* Motion + sound helpers shared by the card games (포커·고스톱·달무티·99·도둑잡기·우노·바퀴벌레 포커·뱅!, 2026-10-13).
|
||||||
|
*
|
||||||
|
* - Everything reacts to *view changes*, so the other players' moves animate and sound too, and skips the first
|
||||||
|
* render: joining, reloading or a replay jump (the replay page remounts the board) never replays old moves.
|
||||||
|
* - Web Animations only (no layout change, `composite: 'add'` keeps the element's own transform), short (≤ 0.6 s),
|
||||||
|
* and flying copies ("ghosts") never take clicks, so nothing waits for an animation.
|
||||||
|
* - Respects `prefers-reduced-motion` (Web Animations are not covered by the global CSS rule, so it is checked here).
|
||||||
|
* - Sounds stay in `lib/feedback` (`sfx`, `tone`, `noise`); game-specific ones live in each game folder.
|
||||||
|
*/
|
||||||
|
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||||
|
|
||||||
|
export const reducedMotion = (): boolean => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||||
|
|
||||||
|
type Where = Element | DOMRect | null | undefined;
|
||||||
|
|
||||||
|
function rectOf(w: Where): DOMRect | null {
|
||||||
|
if (!w) return null;
|
||||||
|
const r = w instanceof Element ? w.getBoundingClientRect() : w;
|
||||||
|
return r.width === 0 && r.height === 0 ? null : r;
|
||||||
|
}
|
||||||
|
|
||||||
|
const center = (r: DOMRect) => ({ x: r.left + r.width / 2, y: r.top + r.height / 2 });
|
||||||
|
|
||||||
|
/** `CSS.escape` (games usually shadow `CSS` with their own style string). */
|
||||||
|
export const cssEsc = (v: string): string => CSS.escape(v);
|
||||||
|
|
||||||
|
/** First element matching `[data-fx="<name>"]` (pile, deck, pot, hand …) or a seat `[data-fx-seat="<player id>"]`. */
|
||||||
|
export const fxEl = (name: string): Element | null => document.querySelector(`[data-fx="${CSS.escape(name)}"]`);
|
||||||
|
export const seatEl = (player: string): Element | null => document.querySelector(`[data-fx-seat="${CSS.escape(player)}"]`);
|
||||||
|
|
||||||
|
export interface FlyOpts {
|
||||||
|
ms?: number;
|
||||||
|
delay?: number;
|
||||||
|
/** Start scale (default 0.6). */
|
||||||
|
scale?: number;
|
||||||
|
/** Start rotation in degrees (default -10). */
|
||||||
|
rotate?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Makes `el` (already at its final place) fly in from `from` (an element or rect). */
|
||||||
|
export function flyFrom(el: Element | null | undefined, from: Where, o: FlyOpts = {}): void {
|
||||||
|
const a = rectOf(from);
|
||||||
|
const b = rectOf(el);
|
||||||
|
if (!el || !a || !b || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||||
|
const p = center(a);
|
||||||
|
const q = center(b);
|
||||||
|
const dx = p.x - q.x;
|
||||||
|
const dy = p.y - q.y;
|
||||||
|
if (Math.abs(dx) + Math.abs(dy) < 4) return;
|
||||||
|
(el as HTMLElement).animate(
|
||||||
|
[
|
||||||
|
{ transform: `translate(${dx}px, ${dy}px) scale(${o.scale ?? 0.6}) rotate(${o.rotate ?? -10}deg)`, opacity: 0.35 },
|
||||||
|
{ transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 },
|
||||||
|
],
|
||||||
|
{ duration: o.ms ?? 380, delay: o.delay ?? 0, easing: 'cubic-bezier(.2,.8,.3,1)', fill: 'backwards', composite: 'add' },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GhostKind = 'card' | 'hwatu' | 'chip' | 'coin';
|
||||||
|
|
||||||
|
export interface GhostOpts {
|
||||||
|
kind?: GhostKind;
|
||||||
|
/** How many copies (staggered by `gap` ms), e.g. dealing 3 cards or a stack of chips. */
|
||||||
|
count?: number;
|
||||||
|
gap?: number;
|
||||||
|
ms?: number;
|
||||||
|
delay?: number;
|
||||||
|
/** Optional text on the ghost (a chip amount, a card name). */
|
||||||
|
label?: string;
|
||||||
|
/** Extra class for a game-specific look (game CSS must target `.fx-ghost.<class>`). */
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const GHOST_SIZE: Record<GhostKind, [number, number]> = { card: [40, 56], hwatu: [34, 54], chip: [22, 22], coin: [22, 22] };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A temporary copy flying from one place to another (card dealt to a seat, chips to the pot, pot to the winner …).
|
||||||
|
* Fixed-position, pointer-events none, removed when done.
|
||||||
|
*/
|
||||||
|
export function flyGhost(from: Where, to: Where, o: GhostOpts = {}): void {
|
||||||
|
const a = rectOf(from);
|
||||||
|
const b = rectOf(to);
|
||||||
|
if (!a || !b || reducedMotion() || typeof document === 'undefined') return;
|
||||||
|
ensureCss();
|
||||||
|
const kind = o.kind ?? 'card';
|
||||||
|
const [w, h] = GHOST_SIZE[kind];
|
||||||
|
const p = center(a);
|
||||||
|
const q = center(b);
|
||||||
|
const n = Math.max(1, Math.min(o.count ?? 1, 12));
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const g = document.createElement('div');
|
||||||
|
g.className = `fx-ghost fx-ghost-${kind}${o.className ? ` ${o.className}` : ''}`;
|
||||||
|
g.setAttribute('aria-hidden', 'true');
|
||||||
|
if (o.label) g.textContent = o.label;
|
||||||
|
g.style.left = `${p.x - w / 2}px`;
|
||||||
|
g.style.top = `${p.y - h / 2}px`;
|
||||||
|
document.body.appendChild(g);
|
||||||
|
const jitter = n > 1 ? (i - (n - 1) / 2) * 6 : 0;
|
||||||
|
const anim = g.animate(
|
||||||
|
[
|
||||||
|
{ transform: 'translate(0px, 0px) scale(.85) rotate(-8deg)', opacity: 0 },
|
||||||
|
{ opacity: 1, offset: 0.15 },
|
||||||
|
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(1) rotate(0deg)`, opacity: 1, offset: 0.85 },
|
||||||
|
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(.9) rotate(0deg)`, opacity: 0 },
|
||||||
|
],
|
||||||
|
{ duration: o.ms ?? 480, delay: (o.delay ?? 0) + i * (o.gap ?? 70), easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'both' },
|
||||||
|
);
|
||||||
|
const done = () => g.remove();
|
||||||
|
anim.onfinish = done;
|
||||||
|
anim.oncancel = done;
|
||||||
|
// Safety net (a background tab may never finish the animation).
|
||||||
|
setTimeout(done, (o.ms ?? 480) + (o.delay ?? 0) + i * (o.gap ?? 70) + 1500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Quick attention wiggle / pop on an element that is already there (a seat that drew, a counter that changed). */
|
||||||
|
export function bump(el: Element | null | undefined, kind: 'pop' | 'shake' = 'pop'): void {
|
||||||
|
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||||
|
const frames =
|
||||||
|
kind === 'pop'
|
||||||
|
? [{ transform: 'scale(1)' }, { transform: 'scale(1.12)', offset: 0.4 }, { transform: 'scale(1)' }]
|
||||||
|
: [
|
||||||
|
{ transform: 'translateX(0px)' },
|
||||||
|
{ transform: 'translateX(-6px) rotate(-2deg)', offset: 0.25 },
|
||||||
|
{ transform: 'translateX(6px) rotate(2deg)', offset: 0.5 },
|
||||||
|
{ transform: 'translateX(-4px) rotate(-1deg)', offset: 0.75 },
|
||||||
|
{ transform: 'translateX(0px)' },
|
||||||
|
];
|
||||||
|
(el as HTMLElement).animate(frames, { duration: kind === 'pop' ? 320 : 420, easing: 'ease-out', composite: 'add' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- hooks
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls `onNew` (in a layout effect, before paint, so new elements can still be animated from elsewhere) with the
|
||||||
|
* entries of `list` whose `key` was not there on the previous render. Never on the first render. A jump of more
|
||||||
|
* than `max` new entries at once (resync, reconnect) is skipped silently.
|
||||||
|
*/
|
||||||
|
export function useNewEntries<T>(list: readonly T[] | null | undefined, key: (t: T) => string | number, onNew: (fresh: T[]) => void, max = 12): void {
|
||||||
|
const seen = useRef<Set<string | number> | null>(null);
|
||||||
|
const cb = useRef(onNew);
|
||||||
|
cb.current = onNew;
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const items = list ?? [];
|
||||||
|
const keys = items.map(key);
|
||||||
|
const prev = seen.current;
|
||||||
|
seen.current = new Set(keys);
|
||||||
|
if (!prev) return;
|
||||||
|
const fresh = items.filter((_, i) => !prev.has(keys[i]!));
|
||||||
|
if (fresh.length && fresh.length <= max) cb.current(fresh);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Calls `onChange(now, before)` in a layout effect when `value` (compared with `Object.is`) changes; not on the first render. */
|
||||||
|
export function useChange<T>(value: T, onChange: (now: T, before: T) => void): void {
|
||||||
|
const prev = useRef<{ v: T } | null>(null);
|
||||||
|
const cb = useRef(onChange);
|
||||||
|
cb.current = onChange;
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const before = prev.current;
|
||||||
|
prev.current = { v: value };
|
||||||
|
if (before && !Object.is(before.v, value)) cb.current(value, before.v);
|
||||||
|
}, [value]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BannerTone = 'gold' | 'red' | 'blue' | 'green' | 'dark';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Big short banner over the screen (우노!, 뻑!, 고!, 혁명!, 뱅! …). `show` replaces the current one.
|
||||||
|
* Render `node` once inside the board.
|
||||||
|
*/
|
||||||
|
export function useBanner(): [ReactNode, (text: string, tone?: BannerTone, sub?: string) => void] {
|
||||||
|
const [b, setB] = useState<{ id: number; text: string; tone: BannerTone; sub?: string } | null>(null);
|
||||||
|
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
const show = (text: string, tone: BannerTone = 'gold', sub?: string) => {
|
||||||
|
ensureCss();
|
||||||
|
if (timer.current) clearTimeout(timer.current);
|
||||||
|
setB((old) => ({ id: (old?.id ?? 0) + 1, text, tone, sub }));
|
||||||
|
timer.current = setTimeout(() => setB(null), 1700);
|
||||||
|
};
|
||||||
|
useLayoutEffect(() => () => {
|
||||||
|
if (timer.current) clearTimeout(timer.current);
|
||||||
|
}, []);
|
||||||
|
const node = b ? (
|
||||||
|
<div className="fx-banner-wrap" aria-hidden>
|
||||||
|
<div key={b.id} className={`fx-banner anim-banner fx-${b.tone}`}>
|
||||||
|
{b.text}
|
||||||
|
{b.sub && <small>{b.sub}</small>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null;
|
||||||
|
return [node, show];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- CSS
|
||||||
|
|
||||||
|
const FX_CSS = `
|
||||||
|
.fx-ghost { position: fixed; z-index: 60; pointer-events: none; box-sizing: border-box; will-change: transform, opacity; }
|
||||||
|
.fx-ghost-card { width: 40px; height: 56px; border-radius: 6px; background: #1e3a8a; border: 2px solid #fff;
|
||||||
|
box-shadow: 0 3px 8px rgba(0,0,0,.35), inset 0 0 0 4px #1e3a8a, inset 0 0 0 6px #93c5fd; }
|
||||||
|
.fx-ghost-hwatu { width: 34px; height: 54px; border-radius: 4px; background: #b91c1c; border: 2px solid #1f2937;
|
||||||
|
box-shadow: 0 3px 8px rgba(0,0,0,.35), inset 0 0 0 3px #7f1d1d; }
|
||||||
|
.fx-ghost-chip, .fx-ghost-coin { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
|
||||||
|
font: 800 10px/1 system-ui, sans-serif; color: #fff; white-space: nowrap; }
|
||||||
|
.fx-ghost-chip { background: #dc2626; border: 3px dashed #fff; box-shadow: 0 2px 5px rgba(0,0,0,.4), 0 0 0 1px #7f1d1d; }
|
||||||
|
.fx-ghost-coin { background: #f59e0b; border: 2px solid #fde68a; box-shadow: 0 2px 5px rgba(0,0,0,.4), 0 0 0 1px #92400e; color: #451a03; }
|
||||||
|
.fx-banner-wrap { position: fixed; inset: 0; z-index: 70; display: flex; align-items: center; justify-content: center; pointer-events: none; }
|
||||||
|
.fx-banner { pointer-events: none; font-size: clamp(2.2rem, 9vw, 4.6rem); font-weight: 900; letter-spacing: .02em; line-height: 1.05; text-align: center;
|
||||||
|
padding: .18em .6em; border-radius: 22px; color: #fff; border: 5px solid #fff; box-shadow: 0 10px 30px rgba(0,0,0,.4);
|
||||||
|
text-shadow: 0 3px 0 rgba(0,0,0,.3); display: flex; flex-direction: column; align-items: center; max-width: 92vw; }
|
||||||
|
.fx-banner small { font-size: .32em; font-weight: 800; text-shadow: none; opacity: .95; margin-top: .2em; }
|
||||||
|
.fx-gold { background: linear-gradient(180deg, #f59e0b, #d97706); }
|
||||||
|
.fx-red { background: linear-gradient(180deg, #ef4444, #b91c1c); }
|
||||||
|
.fx-blue { background: linear-gradient(180deg, #3b82f6, #1d4ed8); }
|
||||||
|
.fx-green { background: linear-gradient(180deg, #22c55e, #15803d); }
|
||||||
|
.fx-dark { background: linear-gradient(180deg, #374151, #111827); }
|
||||||
|
`;
|
||||||
|
|
||||||
|
let cssDone = false;
|
||||||
|
function ensureCss(): void {
|
||||||
|
if (cssDone || typeof document === 'undefined') return;
|
||||||
|
cssDone = true;
|
||||||
|
const s = document.createElement('style');
|
||||||
|
s.dataset.fx = 'card-fx';
|
||||||
|
s.textContent = FX_CSS;
|
||||||
|
document.head.appendChild(s);
|
||||||
|
}
|
||||||
@@ -4,7 +4,8 @@ import type { ClaimEntry, CockroachOptions, CockroachView, FrontView, Kind, Last
|
|||||||
import type { PublicUser } from '@bg/shared/lite';
|
import type { PublicUser } from '@bg/shared/lite';
|
||||||
import { Avatar } from '../../components/ui';
|
import { Avatar } from '../../components/ui';
|
||||||
import { TurnTimer } from '../../components/TurnTimer';
|
import { TurnTimer } from '../../components/TurnTimer';
|
||||||
import { haptic, sounds } from '../../lib/feedback';
|
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||||
|
import { bump, flyGhost, seatEl, useBanner } from '../card-fx';
|
||||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||||
import { helpNow } from './help';
|
import { helpNow } from './help';
|
||||||
import { quickStart } from './quick';
|
import { quickStart } from './quick';
|
||||||
@@ -213,6 +214,7 @@ const CSS = `
|
|||||||
.cp-seats { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 10px; }
|
.cp-seats { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 10px; }
|
||||||
.cp-seat { position: relative; background: var(--surface); border-radius: var(--radius-lg); padding: 9px 11px; box-shadow: var(--shadow); border: 3px solid transparent; display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
.cp-seat { position: relative; background: var(--surface); border-radius: var(--radius-lg); padding: 9px 11px; box-shadow: var(--shadow); border: 3px solid transparent; display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
||||||
.cp-seat.turn { border-color: var(--focus); }
|
.cp-seat.turn { border-color: var(--focus); }
|
||||||
|
.fx-ghost.cp-ghost { background: linear-gradient(135deg, #7c2d12, #431407); border: 2px solid #fdba74; border-radius: 7px; box-shadow: 0 3px 8px rgba(0,0,0,.35); }
|
||||||
.cp-seat.loser { border-color: var(--danger); }
|
.cp-seat.loser { border-color: var(--danger); }
|
||||||
.cp-head { display: flex; align-items: center; gap: 7px; min-height: 30px; min-width: 0; }
|
.cp-head { display: flex; align-items: center; gap: 7px; min-height: 30px; min-width: 0; }
|
||||||
.cp-name { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; }
|
.cp-name { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; }
|
||||||
@@ -354,7 +356,7 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: Cockroa
|
|||||||
const role = v.phase === 'finished' ? null : r.holder === id ? (r.peeked ? '넘기는 중' : '받는 중') : r.holder === null && r.starter === id ? '건네는 중' : null;
|
const role = v.phase === 'finished' ? null : r.holder === id ? (r.peeked ? '넘기는 중' : '받는 중') : r.holder === null && r.starter === id ? '건네는 중' : null;
|
||||||
const label = `${u.nickname}님${id === me ? '(나)' : ''}: 손패 ${v.handCounts[id]}장, ${frontText(front, v.loseCount)}${role ? `, ${role}` : ''}${r.seen.includes(id) && r.holder !== null ? ', 이 카드를 봤어요' : ''}${v.away[id] ? ', 자리 비움' : ''}`;
|
const label = `${u.nickname}님${id === me ? '(나)' : ''}: 손패 ${v.handCounts[id]}장, ${frontText(front, v.loseCount)}${role ? `, ${role}` : ''}${r.seen.includes(id) && r.holder !== null ? ', 이 카드를 봤어요' : ''}${v.away[id] ? ', 자리 비움' : ''}`;
|
||||||
return (
|
return (
|
||||||
<section className={`cp-seat${active ? ' turn' : ''}${loser ? ' loser' : ''}`} aria-label={label}>
|
<section className={`cp-seat${active ? ' turn anim-glow' : ''}${loser ? ' loser' : ''}`} data-fx-seat={id} aria-label={label}>
|
||||||
{bubble && (
|
{bubble && (
|
||||||
<span className="cp-bubble" aria-hidden>
|
<span className="cp-bubble" aria-hidden>
|
||||||
{bubble}
|
{bubble}
|
||||||
@@ -705,7 +707,7 @@ function MyArea({
|
|||||||
const active = waitingOn(v) === me;
|
const active = waitingOn(v) === me;
|
||||||
const total = v.handCounts[me] ?? 0;
|
const total = v.handCounts[me] ?? 0;
|
||||||
return (
|
return (
|
||||||
<section className={`cp-me${active ? ' turn' : ''}`} aria-label="내 자리">
|
<section className={`cp-me${active ? ' turn anim-glow' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||||
{bubble && (
|
{bubble && (
|
||||||
<span className="cp-bubble" aria-hidden>
|
<span className="cp-bubble" aria-hidden>
|
||||||
{bubble}
|
{bubble}
|
||||||
@@ -752,7 +754,15 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
|||||||
const [announce, setAnnounce] = useState('');
|
const [announce, setAnnounce] = useState('');
|
||||||
const [bubbles, setBubbles] = useState<Record<string, string>>({});
|
const [bubbles, setBubbles] = useState<Record<string, string>>({});
|
||||||
const [fresh, setFresh] = useState({ slide: false, flip: false });
|
const [fresh, setFresh] = useState({ slide: false, flip: false });
|
||||||
const prev = useRef({ claims: v.round.claims.length + v.round.no * 100, reveal: v.lastReveal?.round ?? 0, said: v.said[v.said.length - 1]?.seq ?? 0, waiting: waitingOn(v) });
|
const [banner, showBanner] = useBanner();
|
||||||
|
const prev = useRef({
|
||||||
|
claims: v.round.claims.length + v.round.no * 100,
|
||||||
|
reveal: v.lastReveal?.round ?? 0,
|
||||||
|
said: v.said[v.said.length - 1]?.seq ?? 0,
|
||||||
|
waiting: waitingOn(v),
|
||||||
|
peek: `${v.round.no}:${v.round.seen.length}`,
|
||||||
|
over: v.phase === 'finished',
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const p = prev.current;
|
const p = prev.current;
|
||||||
@@ -763,6 +773,37 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
|||||||
let msg = '';
|
let msg = '';
|
||||||
const slide = claimsKey !== p.claims && v.round.holder !== null;
|
const slide = claimsKey !== p.claims && v.round.holder !== null;
|
||||||
const flip = revealKey !== p.reveal && !!v.lastReveal;
|
const flip = revealKey !== p.reveal && !!v.lastReveal;
|
||||||
|
const peekKey = `${v.round.no}:${v.round.seen.length}`;
|
||||||
|
const over = v.phase === 'finished';
|
||||||
|
// Sounds + motion (2026-10-13): the same diff drives everyone's moves, so other players' and computers' moves show too.
|
||||||
|
if (slide && v.round.lastPasser && v.round.holder) {
|
||||||
|
flyGhost(seatEl(v.round.lastPasser), seatEl(v.round.holder), { ms: 460, className: 'cp-ghost' });
|
||||||
|
sfx.cardDeal();
|
||||||
|
cpSfx.sneak(80);
|
||||||
|
} else if (!flip && peekKey !== p.peek && v.round.peeked) {
|
||||||
|
sfx.cardFlip(); // someone takes a secret look before passing on
|
||||||
|
}
|
||||||
|
if (flip) {
|
||||||
|
const rv = v.lastReveal!;
|
||||||
|
sfx.cardFlip();
|
||||||
|
setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), 260);
|
||||||
|
showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`);
|
||||||
|
flyGhost(document.querySelector('.cp-table'), seatEl(rv.takenBy), { delay: 380, ms: 480, className: 'cp-ghost' });
|
||||||
|
setTimeout(() => {
|
||||||
|
bump(seatEl(rv.takenBy), 'shake');
|
||||||
|
const n = v.fronts[rv.takenBy]?.counts[rv.kind] ?? 0;
|
||||||
|
if (!over && n >= v.loseCount - 1) cpSfx.danger();
|
||||||
|
else cpSfx.splat();
|
||||||
|
}, 820);
|
||||||
|
}
|
||||||
|
if (over && !p.over && v.final) {
|
||||||
|
const f = v.final;
|
||||||
|
setTimeout(() => {
|
||||||
|
showBanner(`${f.loser === me ? '내가' : `${nick(players, f.loser)}님`} 패배!`, 'dark', f.losingKind ? `${KIND_KO[f.losingKind]}${hasBatchim(KIND_KO[f.losingKind]) ? '이' : '가'} 너무 많아요` : undefined);
|
||||||
|
cpSfx.danger();
|
||||||
|
bump(seatEl(f.loser), 'shake');
|
||||||
|
}, flip ? 1300 : 0);
|
||||||
|
}
|
||||||
if (flip) {
|
if (flip) {
|
||||||
const rv = v.lastReveal!;
|
const rv = v.lastReveal!;
|
||||||
msg = `${nick(players, rv.caller)}님이 ${rv.call === 'true' ? '진짜라고' : '거짓말이라고'} 했고 ${rv.correct ? '맞혔어요' : '틀렸어요'}. ${kj(rv.kind, '은', '는')} ${nick(players, rv.takenBy)}님 앞마당으로 갔어요.`;
|
msg = `${nick(players, rv.caller)}님이 ${rv.call === 'true' ? '진짜라고' : '거짓말이라고'} 했고 ${rv.correct ? '맞혔어요' : '틀렸어요'}. ${kj(rv.kind, '은', '는')} ${nick(players, rv.takenBy)}님 앞마당으로 갔어요.`;
|
||||||
@@ -779,10 +820,11 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
|||||||
if (lastSaid > p.said) {
|
if (lastSaid > p.said) {
|
||||||
const add: Record<string, string> = {};
|
const add: Record<string, string> = {};
|
||||||
for (const s of v.said) if (s.seq > p.said) add[s.player] = PHRASE_KO[s.phrase];
|
for (const s of v.said) if (s.seq > p.said) add[s.player] = PHRASE_KO[s.phrase];
|
||||||
|
sfx.pop();
|
||||||
setBubbles((b) => ({ ...b, ...add }));
|
setBubbles((b) => ({ ...b, ...add }));
|
||||||
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in add)))), 3500);
|
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in add)))), 3500);
|
||||||
}
|
}
|
||||||
prev.current = { claims: claimsKey, reveal: revealKey, said: lastSaid, waiting: w };
|
prev.current = { claims: claimsKey, reveal: revealKey, said: lastSaid, waiting: w, peek: peekKey, over };
|
||||||
if (slide || flip) {
|
if (slide || flip) {
|
||||||
setFresh({ slide, flip });
|
setFresh({ slide, flip });
|
||||||
const t = setTimeout(() => setFresh({ slide: false, flip: false }), 700);
|
const t = setTimeout(() => setFresh({ slide: false, flip: false }), 700);
|
||||||
@@ -818,10 +860,34 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
|||||||
<p className="sr-only" aria-live="polite">
|
<p className="sr-only" aria-live="polite">
|
||||||
{announce}
|
{announce}
|
||||||
</p>
|
</p>
|
||||||
|
{banner}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 바퀴벌레 포커 sounds on top of the shared palette (synthesized, no files). */
|
||||||
|
const cpSfx = {
|
||||||
|
/** The card slides over with a little scuttle. */
|
||||||
|
sneak: (delay = 0) => {
|
||||||
|
for (let i = 0; i < 4; i++) noise(25, 0.05, delay + i * 45, 'bandpass', 3200 + i * 300, 2);
|
||||||
|
},
|
||||||
|
/** Wrong guess: a sour "bwomp". */
|
||||||
|
wrong: () => {
|
||||||
|
tone(260, 160, 'sawtooth', 0.05, 0, { slideTo: 180 });
|
||||||
|
tone(180, 260, 'sawtooth', 0.05, 150, { slideTo: 110 });
|
||||||
|
},
|
||||||
|
/** The card lands face up in front of someone: a soft "splat". */
|
||||||
|
splat: () => {
|
||||||
|
noise(90, 0.12, 0, 'lowpass', 600);
|
||||||
|
tone(140, 90, 'sine', 0.12, 0, { slideTo: 90 });
|
||||||
|
},
|
||||||
|
/** One more of that critter and you lose (or you just lost). */
|
||||||
|
danger: () => {
|
||||||
|
[880, 660, 880].forEach((f, i) => tone(f, 110, 'square', 0.05, i * 130));
|
||||||
|
tone(110, 400, 'sawtooth', 0.04, 0, { slideTo: 70 });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
// ---------------------------------------------------------------- side
|
// ---------------------------------------------------------------- side
|
||||||
|
|
||||||
function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardProps<CockroachView>) {
|
function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardProps<CockroachView>) {
|
||||||
@@ -956,7 +1022,7 @@ function statusText(v: CockroachView, me: string | null, players: Record<string,
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- options
|
// ---------------------------------------------------------------- options
|
||||||
|
|
||||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="segmented" role="group" aria-label={label}>
|
<div className="segmented" role="group" aria-label={label}>
|
||||||
{options.map(([k, l]) => (
|
{options.map(([k, l]) => (
|
||||||
@@ -986,7 +1052,7 @@ function Options({ value: o, onChange }: OptionsProps<CockroachOptions>) {
|
|||||||
<Seg label="같은 벌레 몇 장이면 패배" value={o.loseCount} options={[['auto', '자동(2명 5장, 3~6명 4장)'], [3, '3장(짧게)'], [4, '4장'], [5, '5장']]} onChange={(loseCount) => set({ loseCount })} />
|
<Seg label="같은 벌레 몇 장이면 패배" value={o.loseCount} options={[['auto', '자동(2명 5장, 3~6명 4장)'], [3, '3장(짧게)'], [4, '4장'], [5, '5장']]} onChange={(loseCount) => set({ loseCount })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="건네기·판정 제한 시간">
|
<Field label="건네기·판정 제한 시간">
|
||||||
<Seg label="건네기·판정 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
<Seg label="건네기·판정 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="이번 라운드 주장 기록">
|
<Field label="이번 라운드 주장 기록">
|
||||||
<Seg label="이번 라운드 주장 기록" value={o.claimHistory} options={[[true, '보이기'], [false, '숨기기']]} onChange={(claimHistory) => set({ claimHistory })} />
|
<Seg label="이번 라운드 주장 기록" value={o.claimHistory} options={[[true, '보이기'], [false, '숨기기']]} onChange={(claimHistory) => set({ claimHistory })} />
|
||||||
@@ -1015,7 +1081,7 @@ function optionsSummary(o: CockroachOptions, players?: number): string {
|
|||||||
const lose = o.loseCount === 'auto' ? (players ? `${players === 2 ? 5 : 4}장` : '자동(2명 5장, 그 외 4장)') : `${o.loseCount}장`;
|
const lose = o.loseCount === 'auto' ? (players ? `${players === 2 ? 5 : 4}장` : '자동(2명 5장, 그 외 4장)') : `${o.loseCount}장`;
|
||||||
return [
|
return [
|
||||||
`같은 벌레 ${lose}이면 패배`,
|
`같은 벌레 ${lose}이면 패배`,
|
||||||
`제한 ${o.turnSeconds}초`,
|
o.turnSeconds === null ? '시간 무제한' : `제한 ${o.turnSeconds}초`,
|
||||||
...(o.claimHistory ? [] : ['주장 기록 숨김']),
|
...(o.claimHistory ? [] : ['주장 기록 숨김']),
|
||||||
...(o.quickChat ? [] : ['빠른 말 끔']),
|
...(o.quickChat ? [] : ['빠른 말 끔']),
|
||||||
...(o.eightKindsRule ? ['8종 모으면 패배'] : []),
|
...(o.eightKindsRule ? ['8종 모으면 패배'] : []),
|
||||||
@@ -1058,7 +1124,7 @@ function Rules({ options }: { options?: CockroachOptions }) {
|
|||||||
<p>카드를 앞마당에 놓은 사람이 다음 라운드를 시작해요. 그때 손에 카드가 한 장도 없으면 바로 져요.</p>
|
<p>카드를 앞마당에 놓은 사람이 다음 라운드를 시작해요. 그때 손에 카드가 한 장도 없으면 바로 져요.</p>
|
||||||
{o?.eightKindsRule && <p>하우스 룰: 앞마당에 8종을 모두 한 장 이상 모아도 져요.</p>}
|
{o?.eightKindsRule && <p>하우스 룰: 앞마당에 8종을 모두 한 장 이상 모아도 져요.</p>}
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
시간 안에 고르지 않으면 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
|
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
|
||||||
것으로 끝나요.
|
것으로 끝나요.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
/** 달무티 화면 (docs/games/dalmuti.md §9). */
|
/** 달무티 화면 (docs/games/dalmuti.md §9). */
|
||||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||||
import type { Choice, DCard, DalmutiOptions, DalmutiView, LogEntry, PlayView, SeatView, Title } from '@bg/games/dalmuti';
|
import type { Choice, DCard, DalmutiOptions, DalmutiView, LogEntry, PlayView, SeatView, Title } from '@bg/games/dalmuti';
|
||||||
import type { PublicUser } from '@bg/shared/lite';
|
import type { PublicUser } from '@bg/shared/lite';
|
||||||
import { Avatar } from '../../components/ui';
|
import { Avatar } from '../../components/ui';
|
||||||
import { TurnTimer } from '../../components/TurnTimer';
|
import { TurnTimer } from '../../components/TurnTimer';
|
||||||
import { haptic, sounds } from '../../lib/feedback';
|
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||||
|
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries } from '../card-fx';
|
||||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||||
import { helpNow } from './help';
|
import { helpNow } from './help';
|
||||||
import { quickStart } from './quick';
|
import { quickStart } from './quick';
|
||||||
@@ -51,6 +52,52 @@ const rankText = (rank: number) => (rank === JESTER ? '광대(13)' : String(rank
|
|||||||
const setText = (p: { rank: number; count: number }) => `${rankText(p.rank)} × ${p.count}장`;
|
const setText = (p: { rank: number; count: number }) => `${rankText(p.rank)} × ${p.count}장`;
|
||||||
const facesText = (cards: number[]) => cards.map((n) => (n === JESTER ? '광대' : String(n))).join(', ');
|
const facesText = (cards: number[]) => cards.map((n) => (n === JESTER ? '광대' : String(n))).join(', ');
|
||||||
|
|
||||||
|
/** 달무티 sounds on top of the shared palette (synthesized, no files). */
|
||||||
|
const dmSfx = {
|
||||||
|
/** A set lands on the pile: one slap per card. */
|
||||||
|
set: (n: number) => {
|
||||||
|
for (let i = 0; i < Math.min(n, 6); i++) noise(60, 0.15, i * 55, 'bandpass', 1500 + i * 120, 0.9);
|
||||||
|
tone(220, 70, 'sine', 0.09, Math.min(n - 1, 5) * 55);
|
||||||
|
},
|
||||||
|
/** Soft double knock on the table (pass). */
|
||||||
|
knock: () => {
|
||||||
|
tone(190, 70, 'sine', 0.14);
|
||||||
|
noise(35, 0.06, 0, 'lowpass', 700);
|
||||||
|
tone(165, 70, 'sine', 0.12, 120);
|
||||||
|
noise(35, 0.05, 120, 'lowpass', 700);
|
||||||
|
},
|
||||||
|
/** 혁명 / 대혁명: drum roll, falling growl, then a big chord (higher and longer for 대혁명). */
|
||||||
|
revolution: (great: boolean) => {
|
||||||
|
for (let i = 0; i < 7; i++) noise(90, 0.1 + i * 0.012, i * 55, 'lowpass', 320);
|
||||||
|
tone(130, 520, 'sawtooth', 0.06, 0, { slideTo: great ? 55 : 80 });
|
||||||
|
[392, 494, 587, 784].forEach((f, i) => tone(f, 420, 'square', 0.045, 420 + i * 35));
|
||||||
|
if (great) [523, 659, 784, 1046].forEach((f, i) => tone(f, 520, 'square', 0.045, 820 + i * 35));
|
||||||
|
},
|
||||||
|
/** Tax card slides over (with a little coin ring). */
|
||||||
|
tax: () => {
|
||||||
|
noise(140, 0.1, 0, 'bandpass', 1200, 0.6);
|
||||||
|
tone(660, 80, 'triangle', 0.07, 120);
|
||||||
|
tone(990, 130, 'triangle', 0.06, 190);
|
||||||
|
},
|
||||||
|
/** Card given back: slide + a lower note. */
|
||||||
|
give: () => {
|
||||||
|
noise(140, 0.1, 0, 'bandpass', 1000, 0.6);
|
||||||
|
tone(520, 110, 'triangle', 0.06, 120);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Where my last played set was (its button may be gone once the view arrives), so the pile cards fly from there. */
|
||||||
|
let myPlayRect: DOMRect | null = null;
|
||||||
|
const rememberPlay = (rank: number) => {
|
||||||
|
myPlayRect = document.querySelector(`.dm-group[data-n="${cssEsc(String(rank))}"]`)?.getBoundingClientRect() ?? null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Brief dim of a seat (pass). */
|
||||||
|
function dim(el: Element | null): void {
|
||||||
|
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||||
|
(el as HTMLElement).animate([{ opacity: 1 }, { opacity: 0.4, offset: 0.35 }, { opacity: 1 }], { duration: 650, easing: 'ease-out' });
|
||||||
|
}
|
||||||
|
|
||||||
const CSS = `
|
const CSS = `
|
||||||
.dm { width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 10px; align-self: center; }
|
.dm { width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 10px; align-self: center; }
|
||||||
.dm-tip { display: flex; align-items: center; gap: 8px; background: var(--primary-soft); color: var(--text); border-radius: 12px; padding: 6px 6px 6px 12px; font-weight: 700; font-size: .95rem; }
|
.dm-tip { display: flex; align-items: center; gap: 8px; background: var(--primary-soft); color: var(--text); border-radius: 12px; padding: 6px 6px 6px 12px; font-weight: 700; font-size: .95rem; }
|
||||||
@@ -60,6 +107,7 @@ const CSS = `
|
|||||||
.dm-seat { position: relative; flex: 0 1 124px; min-width: 104px; background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 8px;
|
.dm-seat { position: relative; flex: 0 1 124px; min-width: 104px; background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 8px;
|
||||||
border: 3px solid transparent; box-shadow: var(--shadow); display: flex; flex-direction: column; gap: 2px; font-size: .88rem; animation: dm-in .35s ease both; }
|
border: 3px solid transparent; box-shadow: var(--shadow); display: flex; flex-direction: column; gap: 2px; font-size: .88rem; animation: dm-in .35s ease both; }
|
||||||
.dm-seat.turn { border-color: var(--focus); }
|
.dm-seat.turn { border-color: var(--focus); }
|
||||||
|
.dm-seat.anim-glow { animation: anim-glow 1.4s ease-in-out infinite; }
|
||||||
.dm-seat.me { background: var(--primary-soft); }
|
.dm-seat.me { background: var(--primary-soft); }
|
||||||
.dm-seat.out { opacity: .7; }
|
.dm-seat.out { opacity: .7; }
|
||||||
.dm-seat .nm { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
|
.dm-seat .nm { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
|
||||||
@@ -80,7 +128,6 @@ const CSS = `
|
|||||||
.dm-prev .dm-card .nm { display: none; }
|
.dm-prev .dm-card .nm { display: none; }
|
||||||
.dm-set { display: flex; }
|
.dm-set { display: flex; }
|
||||||
.dm-set > .dm-card + .dm-card { margin-left: calc(var(--w) * -0.55); }
|
.dm-set > .dm-card + .dm-card { margin-left: calc(var(--w) * -0.55); }
|
||||||
.dm-set.top { animation: dm-fly .3s ease-out; }
|
|
||||||
.dm-card { --w: 60px; position: relative; flex: none; width: var(--w); height: calc(var(--w) * 1.4); border-radius: calc(var(--w) * .13); background: #fffdf7; color: #1f2937;
|
.dm-card { --w: 60px; position: relative; flex: none; width: var(--w); height: calc(var(--w) * 1.4); border-radius: calc(var(--w) * .13); background: #fffdf7; color: #1f2937;
|
||||||
border: 2px solid var(--c, #444); box-shadow: 0 2px 4px rgba(0,0,0,.28); display: flex; flex-direction: column; align-items: center; overflow: hidden; font-family: inherit; }
|
border: 2px solid var(--c, #444); box-shadow: 0 2px 4px rgba(0,0,0,.28); display: flex; flex-direction: column; align-items: center; overflow: hidden; font-family: inherit; }
|
||||||
.dm-card .band { width: 100%; background: var(--c, #444); color: #fff; font-weight: 900; font-size: calc(var(--w) * .2); line-height: 1.35; text-align: left; padding-left: 4px; }
|
.dm-card .band { width: 100%; background: var(--c, #444); color: #fff; font-weight: 900; font-size: calc(var(--w) * .2); line-height: 1.35; text-align: left; padding-left: 4px; }
|
||||||
@@ -129,10 +176,9 @@ const CSS = `
|
|||||||
.dm-flip { animation: dm-flip .7s ease both; }
|
.dm-flip { animation: dm-flip .7s ease both; }
|
||||||
@keyframes dm-in { from { transform: translateY(-8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
@keyframes dm-in { from { transform: translateY(-8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
||||||
@keyframes dm-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
@keyframes dm-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
||||||
@keyframes dm-fly { from { transform: translateY(40px) scale(.85); opacity: .2; } to { transform: none; opacity: 1; } }
|
|
||||||
@keyframes dm-flip { from { transform: rotateY(180deg); } to { transform: none; } }
|
@keyframes dm-flip { from { transform: rotateY(180deg); } to { transform: none; } }
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.dm *, .dm-seat, .dm-set.top, .dm-rev, .dm-bubble, .dm-draw, .dm-flip { animation: none !important; transition: none !important; }
|
.dm *, .dm-seat, .dm-rev, .dm-bubble, .dm-draw, .dm-flip { animation: none !important; transition: none !important; }
|
||||||
}
|
}
|
||||||
@media (max-width: 719px) {
|
@media (max-width: 719px) {
|
||||||
.dm { gap: 8px; }
|
.dm { gap: 8px; }
|
||||||
@@ -195,7 +241,8 @@ function Seats({ v, players, me, deadline }: { v: DalmutiView; players: Record<s
|
|||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
key={s.id}
|
key={s.id}
|
||||||
className={`dm-seat${s.isTurn && v.phase === 'playing' ? ' turn' : ''}${s.id === me ? ' me' : ''}${s.place ? ' out' : ''}`}
|
className={`dm-seat${s.isTurn && v.phase === 'playing' ? ' turn anim-glow' : ''}${s.id === me ? ' me' : ''}${s.place ? ' out' : ''}`}
|
||||||
|
data-fx-seat={s.id}
|
||||||
style={{ animationDelay: `${i * 40}ms` }}
|
style={{ animationDelay: `${i * 40}ms` }}
|
||||||
aria-label={seatLabel(s, v, players, me)}
|
aria-label={seatLabel(s, v, players, me)}
|
||||||
>
|
>
|
||||||
@@ -251,7 +298,7 @@ function TableArea({ v, players, me }: { v: DalmutiView; players: Record<string,
|
|||||||
const leaderName = t.leader === me ? '내가' : `${nick(players, t.leader)}님이`;
|
const leaderName = t.leader === me ? '내가' : `${nick(players, t.leader)}님이`;
|
||||||
const curName = v.current === me ? '내' : `${nick(players, v.current ?? '')}님`;
|
const curName = v.current === me ? '내' : `${nick(players, v.current ?? '')}님`;
|
||||||
return (
|
return (
|
||||||
<div className="dm-table" role="region" aria-label="바닥">
|
<div className="dm-table" data-fx="dm-center" role="region" aria-label="바닥">
|
||||||
{top ? (
|
{top ? (
|
||||||
<>
|
<>
|
||||||
<div className="dm-now" aria-live="polite">
|
<div className="dm-now" aria-live="polite">
|
||||||
@@ -339,6 +386,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
|
|||||||
setSel(null);
|
setSel(null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
sfx.select();
|
||||||
if (top) setSel({ rank: g.n, count: top.count, mix: ch.needsJester });
|
if (top) setSel({ rank: g.n, count: top.count, mix: ch.needsJester });
|
||||||
else setSel({ rank: g.n, count: ch.have, mix: false });
|
else setSel({ rank: g.n, count: ch.have, mix: false });
|
||||||
};
|
};
|
||||||
@@ -360,6 +408,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
|
|||||||
};
|
};
|
||||||
const send = () => {
|
const send = () => {
|
||||||
if (!ids || !legal) return;
|
if (!ids || !legal) return;
|
||||||
|
rememberPlay(sel!.rank);
|
||||||
act({ type: 'play', cardIds: ids });
|
act({ type: 'play', cardIds: ids });
|
||||||
setSel(null);
|
setSel(null);
|
||||||
};
|
};
|
||||||
@@ -374,7 +423,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
|
|||||||
</strong>
|
</strong>
|
||||||
{mine && <span className="small muted">{top ? `${setText(top)}보다 낮은 숫자를 골라요` : '낼 숫자를 골라요'}</span>}
|
{mine && <span className="small muted">{top ? `${setText(top)}보다 낮은 숫자를 골라요` : '낼 숫자를 골라요'}</span>}
|
||||||
</div>
|
</div>
|
||||||
<div className="dm-hand" role="group" aria-label="내 카드(숫자별). 좌우 방향키로 고르고 Enter로 선택해요" onKeyDown={(e) => onArrowKeys(e, 'button.dm-group')}>
|
<div className="dm-hand" data-fx="dm-hand" role="group" aria-label="내 카드(숫자별). 좌우 방향키로 고르고 Enter로 선택해요" onKeyDown={(e) => onArrowKeys(e, 'button.dm-group')}>
|
||||||
{groups.map((g) => {
|
{groups.map((g) => {
|
||||||
const c = choice(g.n);
|
const c = choice(g.n);
|
||||||
const picked = sel?.rank === g.n;
|
const picked = sel?.rank === g.n;
|
||||||
@@ -508,7 +557,7 @@ function RevolutionPanel({ v, players, me, act, pending }: { v: DalmutiView; pla
|
|||||||
const my = v.my;
|
const my = v.my;
|
||||||
const done = v.seats.filter((s) => s.confirmed).length;
|
const done = v.seats.filter((s) => s.confirmed).length;
|
||||||
return (
|
return (
|
||||||
<div className="dm-panel">
|
<div className="dm-panel" data-fx="dm-center">
|
||||||
<h3>
|
<h3>
|
||||||
{v.round}라운드 준비 · 손패 확인 ({done}/{v.seats.length})
|
{v.round}라운드 준비 · 손패 확인 ({done}/{v.seats.length})
|
||||||
</h3>
|
</h3>
|
||||||
@@ -553,11 +602,12 @@ function TaxPanel({ v, players, me, act, pending }: { v: DalmutiView; players: R
|
|||||||
const subject = (id: string) => (id === me ? '내가' : `${nick(players, id)}님이`);
|
const subject = (id: string) => (id === me ? '내가' : `${nick(players, id)}님이`);
|
||||||
const toggle = (id: string) => {
|
const toggle = (id: string) => {
|
||||||
if (!owe) return;
|
if (!owe) return;
|
||||||
|
sfx.select();
|
||||||
if (picked.includes(id)) setPicked(picked.filter((x) => x !== id));
|
if (picked.includes(id)) setPicked(picked.filter((x) => x !== id));
|
||||||
else setPicked(picked.length >= owe.count ? [...picked.slice(1), id] : [...picked, id]);
|
else setPicked(picked.length >= owe.count ? [...picked.slice(1), id] : [...picked, id]);
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<div className={`dm-panel${owe ? ' hot' : ''}`}>
|
<div className={`dm-panel${owe ? ' hot' : ''}`} data-fx="dm-center">
|
||||||
<h3>세금 카드 교환</h3>
|
<h3>세금 카드 교환</h3>
|
||||||
<RoundRecap v={v} players={players} me={me} />
|
<RoundRecap v={v} players={players} me={me} />
|
||||||
<ul style={{ margin: 0, paddingLeft: 20 }} aria-label="세금 내역">
|
<ul style={{ margin: 0, paddingLeft: 20 }} aria-label="세금 내역">
|
||||||
@@ -685,6 +735,8 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
|||||||
const mine = isMyTurn(v, me);
|
const mine = isMyTurn(v, me);
|
||||||
const prevMine = useRef(false);
|
const prevMine = useRef(false);
|
||||||
const lastLog = v.log[v.log.length - 1];
|
const lastLog = v.log[v.log.length - 1];
|
||||||
|
const [banner, showBanner] = useBanner();
|
||||||
|
useDalmutiFx(v, me, players, showBanner);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (mine && !prevMine.current) {
|
if (mine && !prevMine.current) {
|
||||||
haptic(40);
|
haptic(40);
|
||||||
@@ -715,10 +767,101 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
|||||||
<p className="sr-only" aria-live="polite">
|
<p className="sr-only" aria-live="polite">
|
||||||
{announce}
|
{announce}
|
||||||
</p>
|
</p>
|
||||||
|
{banner}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : 'from' in e ? e.from : ''}`;
|
||||||
|
|
||||||
|
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
|
||||||
|
function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||||
|
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
|
||||||
|
const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`);
|
||||||
|
// A new round (or the very first deal): cards go from the middle to everyone.
|
||||||
|
const deal = (delay = 0) => {
|
||||||
|
const c = fxEl('dm-center');
|
||||||
|
later(delay, sfx.shuffle);
|
||||||
|
later(delay + 300, () => sfx.deal(6, 60));
|
||||||
|
document.querySelectorAll('.dm-hand .dm-group, .dm-hand .dm-one').forEach((el, i) => flyFrom(el, c, { delay: delay + 280 + i * 45, rotate: 10 }));
|
||||||
|
for (const s of v.seats) if (s.id !== me) flyGhost(c, seatEl(s.id), { count: 3, gap: 90, delay: delay + 280 });
|
||||||
|
};
|
||||||
|
useNewEntries(v.log, logKey, (fresh) => {
|
||||||
|
const lastPlay = [...fresh].reverse().find((e) => e.t === 'play');
|
||||||
|
let t = 0;
|
||||||
|
for (const e of fresh) {
|
||||||
|
const at = t;
|
||||||
|
switch (e.t) {
|
||||||
|
case 'play': {
|
||||||
|
if (e === lastPlay) {
|
||||||
|
const from = e.p === me ? (myPlayRect ?? fxEl('dm-hand')) : seatEl(e.p);
|
||||||
|
document.querySelectorAll('.dm-set.top .dm-card').forEach((el, i) => flyFrom(el, from, { delay: at + i * 60, ms: 340, rotate: -12 }));
|
||||||
|
}
|
||||||
|
if (e.p === me) myPlayRect = null;
|
||||||
|
later(at, () => dmSfx.set(e.count));
|
||||||
|
t += 150;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'pass':
|
||||||
|
later(at, dmSfx.knock);
|
||||||
|
dim(seatEl(e.p));
|
||||||
|
t += 120;
|
||||||
|
break;
|
||||||
|
case 'trick':
|
||||||
|
// Everyone passed: the pile is swept to whoever leads next.
|
||||||
|
flyGhost(fxEl('dm-center'), seatEl(e.p), { count: 3, gap: 60, delay: at, ms: 420 });
|
||||||
|
later(at, sfx.whoosh);
|
||||||
|
later(at + 380, () => bump(seatEl(e.p)));
|
||||||
|
t += 200;
|
||||||
|
break;
|
||||||
|
case 'out':
|
||||||
|
showBanner(`${e.place}등!`, e.place === 1 ? 'gold' : 'green', e.p === me ? '손패를 다 냈어요' : `${nick(players, e.p)}님`);
|
||||||
|
later(at + 80, e.place === 1 ? sfx.fanfare : sfx.good);
|
||||||
|
bump(seatEl(e.p));
|
||||||
|
t += 250;
|
||||||
|
break;
|
||||||
|
case 'revolution': {
|
||||||
|
const great = e.kind === 'great';
|
||||||
|
showBanner(great ? '대혁명!' : '혁명!', great ? 'dark' : 'red', great ? `${who(e.p)} · 신분이 뒤집혀요` : `${who(e.p)} · 세금 없음`);
|
||||||
|
later(at, () => dmSfx.revolution(great));
|
||||||
|
t += 300;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'tax':
|
||||||
|
case 'return':
|
||||||
|
flyGhost(seatEl(e.from), seatEl(e.to), { count: e.n, gap: 90, delay: at, ms: 520 });
|
||||||
|
later(at, e.t === 'tax' ? dmSfx.tax : dmSfx.give);
|
||||||
|
t += 350;
|
||||||
|
break;
|
||||||
|
case 'round':
|
||||||
|
// The next round's cards are dealt (not after the last round).
|
||||||
|
if (v.phase !== 'finished') {
|
||||||
|
deal(at + 500);
|
||||||
|
t += 1300;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'timeout':
|
||||||
|
later(at, sfx.tick);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const started = useRef(false);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (started.current) return;
|
||||||
|
started.current = true;
|
||||||
|
// Mounted right at the start of the game (nobody has done anything yet): show the deal once.
|
||||||
|
const fresh =
|
||||||
|
v.round === 1 &&
|
||||||
|
(v.phase === 'revolutionCheck'
|
||||||
|
? v.log.length === 0 && !v.seats.some((s) => s.confirmed)
|
||||||
|
: v.phase === 'taxReturn' && !v.options.revolution && v.log.every((e) => e.t === 'tax') && v.taxPending.every((p) => !p.done));
|
||||||
|
if (fresh) deal();
|
||||||
|
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- side
|
// ---------------------------------------------------------------- side
|
||||||
|
|
||||||
function rulesLine(o: DalmutiOptions): string {
|
function rulesLine(o: DalmutiOptions): string {
|
||||||
@@ -729,7 +872,7 @@ function rulesLine(o: DalmutiOptions): string {
|
|||||||
o.jesterTaxable ? '세금에 광대 포함' : '세금에 광대 빼기',
|
o.jesterTaxable ? '세금에 광대 포함' : '세금에 광대 빼기',
|
||||||
o.passLocksOut ? '패스하면 트릭에서 빠짐' : '패스해도 다시 낼 수 있음',
|
o.passLocksOut ? '패스하면 트릭에서 빠짐' : '패스해도 다시 낼 수 있음',
|
||||||
o.removeHighCards ? '9~12 빼기' : '',
|
o.removeHighCards ? '9~12 빼기' : '',
|
||||||
`${o.turnSeconds}초`,
|
o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`,
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(' · ');
|
.join(' · ');
|
||||||
@@ -853,7 +996,7 @@ function statusText(v: DalmutiView, me: string | null, players: Record<string, P
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- options
|
// ---------------------------------------------------------------- options
|
||||||
|
|
||||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="segmented" role="group" aria-label={label}>
|
<div className="segmented" role="group" aria-label={label}>
|
||||||
{options.map(([k, l]) => (
|
{options.map(([k, l]) => (
|
||||||
@@ -895,7 +1038,7 @@ function Options({ value: o, onChange }: OptionsProps<DalmutiOptions>) {
|
|||||||
<Seg label="혁명 규칙" value={o.revolution} options={onOff} onChange={(revolution) => set({ revolution })} />
|
<Seg label="혁명 규칙" value={o.revolution} options={onOff} onChange={(revolution) => set({ revolution })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="한 턴 제한 시간">
|
<Field label="한 턴 제한 시간">
|
||||||
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [45, '45초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [45, '45초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||||
</Field>
|
</Field>
|
||||||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||||||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||||||
@@ -926,7 +1069,7 @@ function optionsSummary(o: DalmutiOptions): string {
|
|||||||
if (o.jesterTaxable) parts.push('세금에 광대');
|
if (o.jesterTaxable) parts.push('세금에 광대');
|
||||||
if (o.passLocksOut) parts.push('패스하면 빠짐');
|
if (o.passLocksOut) parts.push('패스하면 빠짐');
|
||||||
if (o.removeHighCards) parts.push('9~12 빼기');
|
if (o.removeHighCards) parts.push('9~12 빼기');
|
||||||
parts.push(`${o.turnSeconds}초`);
|
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
|
||||||
return parts.join(' · ');
|
return parts.join(' · ');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -990,7 +1133,10 @@ function Rules({ options }: { options?: DalmutiOptions }) {
|
|||||||
라운드에서 1등은 (사람 수 − 1)점, 마지막 순위는 0점을 받아요. {o?.scoring === 'last-round' ? '이 방은 마지막 라운드 순위가 최종 순위예요.' : '총점이 높은 사람이 이기고, 같으면 마지막 라운드 순위로 정해요.'}{' '}
|
라운드에서 1등은 (사람 수 − 1)점, 마지막 순위는 0점을 받아요. {o?.scoring === 'last-round' ? '이 방은 마지막 라운드 순위가 최종 순위예요.' : '총점이 높은 사람이 이기고, 같으면 마지막 라운드 순위로 정해요.'}{' '}
|
||||||
점수는 이 방 안에서만 쓰는 표시용이에요.
|
점수는 이 방 안에서만 쓰는 표시용이에요.
|
||||||
</p>
|
</p>
|
||||||
<p>시간 안에 고르지 않으면 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는 패스해요.</p>
|
<p>
|
||||||
|
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는
|
||||||
|
패스해요.
|
||||||
|
</p>
|
||||||
<CardTable removeHigh={o?.removeHighCards} />
|
<CardTable removeHigh={o?.removeHighCards} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -18,6 +18,9 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
|
|||||||
};
|
};
|
||||||
const seat = me ? v.seats.find((s) => s.id === me) : undefined;
|
const seat = me ? v.seats.find((s) => s.id === me) : undefined;
|
||||||
const seatOf = (id: string | null) => v.seats.find((s) => s.id === id);
|
const seatOf = (id: string | null) => v.seats.find((s) => s.id === id);
|
||||||
|
/** What happens when the decision clock runs out (무제한: only after a dropped connection). */
|
||||||
|
const late = (what: string) =>
|
||||||
|
v.rules.decisionSeconds === null ? `시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 ${what}` : `시간이 지나면 ${what}`;
|
||||||
|
|
||||||
if (v.phase === 'finished') {
|
if (v.phase === 'finished') {
|
||||||
const lines = [`게임이 끝났어요. ${v.result?.summary ?? ''}`.trim()];
|
const lines = [`게임이 끝났어요. ${v.result?.summary ?? ''}`.trim()];
|
||||||
@@ -57,7 +60,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
|
|||||||
const gain = n * v.rules.gwangPrice * (v.rules.gwangPayer === 'nonDealerPlayers' ? 2 : 3);
|
const gain = n * v.rules.gwangPrice * (v.rules.gwangPayer === 'nonDealerPlayers' ? 2 : 3);
|
||||||
lines.push('광팔기 차례예요. 4~5명이면 이번 판은 3명만 쳐요(선은 꼭 쳐요).');
|
lines.push('광팔기 차례예요. 4~5명이면 이번 판은 3명만 쳐요(선은 꼭 쳐요).');
|
||||||
lines.push(
|
lines.push(
|
||||||
`[치기]를 누르면 이번 판에 참가해요. ${n > 0 ? `[죽기 · 광 ${n}장 팔기]를 누르면 ${gain}점을 받고 이번 판은 쉬어요.` : '[죽기]를 누르면 팔 패가 없어 그냥 쉬어요.'} 시간이 지나면 죽기로 정해져요.`,
|
`[치기]를 누르면 이번 판에 참가해요. ${n > 0 ? `[죽기 · 광 ${n}장 팔기]를 누르면 ${gain}점을 받고 이번 판은 쉬어요.` : '[죽기]를 누르면 팔 패가 없어 그냥 쉬어요.'} ${late('죽기로 정해져요.')}`,
|
||||||
);
|
);
|
||||||
} else if (seat) {
|
} else if (seat) {
|
||||||
const mine = s?.decisions.find((d) => d.player === me);
|
const mine = s?.decisions.find((d) => d.player === me);
|
||||||
@@ -76,7 +79,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
|
|||||||
const each = v.rules.chongtongPoints * v.nagariMult;
|
const each = v.rules.chongtongPoints * v.nagariMult;
|
||||||
lines.push(`총통이에요! 손에 같은 월 4장${months.length ? `(${months.map((m) => `${m}월`).join(', ')})` : ''}이 있어요.`);
|
lines.push(`총통이에요! 손에 같은 월 4장${months.length ? `(${months.map((m) => `${m}월`).join(', ')})` : ''}이 있어요.`);
|
||||||
lines.push(`[총통 선언]을 누르면 이번 판을 바로 이기고 상대마다 ${each}점, 모두 ${each * others}점을 받아요. [그냥 치기]를 누르면 판을 계속하고, 그 월로 흔들기나 폭탄을 할 수 있어요.`);
|
lines.push(`[총통 선언]을 누르면 이번 판을 바로 이기고 상대마다 ${each}점, 모두 ${each * others}점을 받아요. [그냥 치기]를 누르면 판을 계속하고, 그 월로 흔들기나 폭탄을 할 수 있어요.`);
|
||||||
lines.push('시간이 지나면 총통 선언으로 정해져요.');
|
lines.push(late('총통 선언으로 정해져요.'));
|
||||||
} else {
|
} else {
|
||||||
lines.push(`${nm(who)}이 총통(손에 같은 월 4장)을 선언할지 고르는 중이에요. 선언하면 ${nm(who)}이 이번 판을 바로 이겨요.`);
|
lines.push(`${nm(who)}이 총통(손에 같은 월 4장)을 선언할지 고르는 중이에요. 선언하면 ${nm(who)}이 이번 판을 바로 이겨요.`);
|
||||||
}
|
}
|
||||||
@@ -122,7 +125,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
|
|||||||
const who = pf?.player ?? v.turn;
|
const who = pf?.player ?? v.turn;
|
||||||
if (seat && who === me && pf) {
|
if (seat && who === me && pf) {
|
||||||
lines.push(`뒤집은 ${pf.flipped.name}과(와) 같은 월 패가 바닥에 2장(${pf.options.map((c) => c.name).join(', ')}) 있어요. 창에서 가져올 패를 눌러 골라요.`);
|
lines.push(`뒤집은 ${pf.flipped.name}과(와) 같은 월 패가 바닥에 2장(${pf.options.map((c) => c.name).join(', ')}) 있어요. 창에서 가져올 패를 눌러 골라요.`);
|
||||||
lines.push('시간이 지나면 더 좋은 패를 저절로 가져와요.');
|
lines.push(late('더 좋은 패를 저절로 가져와요.'));
|
||||||
} else {
|
} else {
|
||||||
lines.push(`${nm(who)}이 뒤집은 패${pf ? `(${pf.flipped.name})` : ''}로 가져올 바닥 패를 고르는 중이에요.`);
|
lines.push(`${nm(who)}이 뒤집은 패${pf ? `(${pf.flipped.name})` : ''}로 가져올 바닥 패를 고르는 중이에요.`);
|
||||||
}
|
}
|
||||||
@@ -139,7 +142,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
|
|||||||
lines.push(`${g.score}점이 났어요! [고] 또는 [스톱]을 골라요.${g.goCount > 0 ? ` 지금까지 ${g.goCount}고 했어요.` : ''}`);
|
lines.push(`${g.score}점이 났어요! [고] 또는 [스톱]을 골라요.${g.goCount > 0 ? ` 지금까지 ${g.goCount}고 했어요.` : ''}`);
|
||||||
lines.push(`[스톱]: 판을 끝내고 ${g.stopNow.total}점을 받아요${notes}.${baks.length ? ` ${baks.join(', ')}이 붙어요.` : ''}`);
|
lines.push(`[스톱]: 판을 끝내고 ${g.stopNow.total}점을 받아요${notes}.${baks.length ? ` ${baks.join(', ')}이 붙어요.` : ''}`);
|
||||||
lines.push(`[고]: ${g.goNext.goCount}고로 판을 계속해요. +${g.goNext.plus}점${g.goNext.factor > 1 ? `, 점수 x${g.goNext.factor}` : ''}.${risk}`);
|
lines.push(`[고]: ${g.goNext.goCount}고로 판을 계속해요. +${g.goNext.plus}점${g.goNext.factor > 1 ? `, 점수 x${g.goNext.factor}` : ''}.${risk}`);
|
||||||
lines.push('시간이 지나면 스톱으로 정해져요.');
|
lines.push(late('스톱으로 정해져요.'));
|
||||||
} else {
|
} else {
|
||||||
lines.push(`${nm(who)}이 ${g ? `${g.score}점을 내서 ` : ''}고 또는 스톱을 고르는 중이에요. 스톱하면 이번 판이 끝나요.`);
|
lines.push(`${nm(who)}이 ${g ? `${g.score}점을 내서 ` : ''}고 또는 스톱을 고르는 중이에요. 스톱하면 이번 판이 끝나요.`);
|
||||||
const mine = g?.stopNow.perLoser.find((x) => x.player === me);
|
const mine = g?.stopNow.perLoser.find((x) => x.player === me);
|
||||||
@@ -152,7 +155,7 @@ export function helpNow(v: GostopView, me: string | null, players: Record<string
|
|||||||
const who = g?.player ?? v.turn;
|
const who = g?.player ?? v.turn;
|
||||||
if (seat && who === me && g) {
|
if (seat && who === me && g) {
|
||||||
lines.push('판이 끝나기 전에 내가 가진 9월 열끗(국진)을 어떻게 셀지 골라요.');
|
lines.push('판이 끝나기 전에 내가 가진 9월 열끗(국진)을 어떻게 셀지 골라요.');
|
||||||
lines.push(`[열끗으로]: 내 점수 ${g.yeolScore}점. [쌍피로](피 2장 값): 내 점수 ${g.piScore}점. 시간이 지나면 나에게 유리한 쪽으로 정해져요.`);
|
lines.push(`[열끗으로]: 내 점수 ${g.yeolScore}점. [쌍피로](피 2장 값): 내 점수 ${g.piScore}점. ${late('나에게 유리한 쪽으로 정해져요.')}`);
|
||||||
} else {
|
} else {
|
||||||
lines.push(`스톱이 나왔어요. ${nm(who)}이 9월 열끗(국진)을 열끗으로 셀지 쌍피로 셀지 정하는 중이에요. 정하면 이번 판 점수를 계산해요.`);
|
lines.push(`스톱이 나왔어요. ${nm(who)}이 9월 열끗(국진)을 열끗으로 셀지 쌍피로 셀지 정하는 중이에요. 정하면 이번 판 점수를 계산해요.`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
/** 고스톱 / 맞고 화면 (docs/games/gostop.md §9). Points are room-only play points. */
|
/** 고스톱 / 맞고 화면 (docs/games/gostop.md §9). Points are room-only play points. */
|
||||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||||
import type { BakKind, CardView, GostopOptions, GostopView, HandCardView, OutcomeView, SeatView, TurnTag } from '@bg/games/gostop';
|
import type { BakKind, CardView, GostopOptions, GostopView, HandCardView, OutcomeView, SeatView, TurnTag } from '@bg/games/gostop';
|
||||||
import type { PublicUser } from '@bg/shared/lite';
|
import type { PublicUser } from '@bg/shared/lite';
|
||||||
import { Avatar, Sheet } from '../../components/ui';
|
import { Avatar, Sheet } from '../../components/ui';
|
||||||
import { TurnTimer } from '../../components/TurnTimer';
|
import { TurnTimer } from '../../components/TurnTimer';
|
||||||
import { HwatuCard, type HwatuInfo } from '../../components/cards/HwatuCard';
|
import { HwatuCard, type HwatuInfo } from '../../components/cards/HwatuCard';
|
||||||
import { ChipIcon } from '../../components/cards/Chips';
|
import { ChipIcon } from '../../components/cards/Chips';
|
||||||
import { haptic, sounds } from '../../lib/feedback';
|
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||||
|
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, type BannerTone } from '../card-fx';
|
||||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||||
import { helpNow } from './help';
|
import { helpNow } from './help';
|
||||||
import { quickStart } from './quick';
|
import { quickStart } from './quick';
|
||||||
@@ -51,7 +52,7 @@ function totalMsOf(v: GostopView): number {
|
|||||||
if (v.phase === 'roundResult') return 10_000;
|
if (v.phase === 'roundResult') return 10_000;
|
||||||
const who = v.step === 'sell' ? v.sell?.current : v.turn;
|
const who = v.step === 'sell' ? v.sell?.current : v.turn;
|
||||||
if (who && v.seats.find((s) => s.id === who)?.autoPilot) return 2_000;
|
if (who && v.seats.find((s) => s.id === who)?.autoPilot) return 2_000;
|
||||||
return (v.step === 'play' ? v.rules.turnSeconds : v.rules.decisionSeconds) * 1000;
|
return ((v.step === 'play' ? v.rules.turnSeconds : v.rules.decisionSeconds) ?? 0) * 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Whoever the table is waiting for (null on result screens). */
|
/** Whoever the table is waiting for (null on result screens). */
|
||||||
@@ -152,10 +153,6 @@ const CSS = `
|
|||||||
background: #dc2626; color: #fff; pointer-events: none; }
|
background: #dc2626; color: #fff; pointer-events: none; }
|
||||||
.gs-hcard .tag.shake { background: #7c3aed; }
|
.gs-hcard .tag.shake { background: #7c3aed; }
|
||||||
.gs-hint { margin: 0; text-align: center; font-size: .9rem; color: var(--text-sub); }
|
.gs-hint { margin: 0; text-align: center; font-size: .9rem; color: var(--text-sub); }
|
||||||
.gs-flash { position: fixed; left: 50%; top: 36%; transform: translate(-50%, -50%); z-index: 30; pointer-events: none; text-align: center;
|
|
||||||
font-size: 3rem; font-weight: 900; color: #fde047; text-shadow: 0 3px 10px rgba(0,0,0,.7); animation: gs-pop .35s ease-out; white-space: nowrap; }
|
|
||||||
.gs-flash small { display: block; font-size: 1.1rem; color: #fff; }
|
|
||||||
@keyframes gs-pop { from { transform: translate(-50%, -50%) scale(.5); opacity: 0 } to { transform: translate(-50%, -50%) scale(1); opacity: 1 } }
|
|
||||||
.gs-big { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
.gs-big { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||||
.gs-big .btn { min-height: 76px; font-size: 1.3rem; flex-direction: column; gap: 2px; line-height: 1.2; }
|
.gs-big .btn { min-height: 76px; font-size: 1.3rem; flex-direction: column; gap: 2px; line-height: 1.2; }
|
||||||
.gs-big .btn small { font-size: .85rem; font-weight: 600; opacity: .95; }
|
.gs-big .btn small { font-size: .85rem; font-weight: 600; opacity: .95; }
|
||||||
@@ -177,7 +174,6 @@ const CSS = `
|
|||||||
.gs-me { padding: 6px 4px; }
|
.gs-me { padding: 6px 4px; }
|
||||||
.gs-hand { gap: 4px; }
|
.gs-hand { gap: 4px; }
|
||||||
.gs-hcard { border-width: 2px; }
|
.gs-hcard { border-width: 2px; }
|
||||||
.gs-flash { font-size: 2.4rem; }
|
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -197,9 +193,14 @@ function Card({ c, size = 'sm', className, style }: { c: CardView | null; size?:
|
|||||||
function CapturedRow({ seat, label }: { seat: SeatView; label: string }) {
|
function CapturedRow({ seat, label }: { seat: SeatView; label: string }) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const groups = (['gwang', 'yeol', 'tti', 'pi'] as const).filter((k) => seat.captured[k].length > 0);
|
const groups = (['gwang', 'yeol', 'tti', 'pi'] as const).filter((k) => seat.captured[k].length > 0);
|
||||||
if (groups.length === 0) return <span className="small muted">먹은 패 없음</span>;
|
if (groups.length === 0)
|
||||||
|
return (
|
||||||
|
<span className="small muted" data-fx-cap={seat.id}>
|
||||||
|
먹은 패 없음
|
||||||
|
</span>
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<button type="button" className="gs-cap" aria-expanded={open} onClick={() => setOpen(!open)} aria-label={`${label} 먹은 패: ${groups.map((k) => `${KIND_LABEL[k]} ${seat.captured[k].length}장`).join(', ')}. 눌러서 ${open ? '접기' : '펼치기'}`}>
|
<button type="button" className="gs-cap" data-fx-cap={seat.id} aria-expanded={open} onClick={() => setOpen(!open)} aria-label={`${label} 먹은 패: ${groups.map((k) => `${KIND_LABEL[k]} ${seat.captured[k].length}장`).join(', ')}. 눌러서 ${open ? '접기' : '펼치기'}`}>
|
||||||
{groups.map((k) => (
|
{groups.map((k) => (
|
||||||
<span key={k} className="gs-pile">
|
<span key={k} className="gs-pile">
|
||||||
<b>
|
<b>
|
||||||
@@ -207,7 +208,9 @@ function CapturedRow({ seat, label }: { seat: SeatView; label: string }) {
|
|||||||
</b>
|
</b>
|
||||||
<span className="gs-pile-cards">
|
<span className="gs-pile-cards">
|
||||||
{seat.captured[k].map((c) => (
|
{seat.captured[k].map((c) => (
|
||||||
<HwatuCard key={c.key} card={c as HwatuInfo} size="sm" />
|
<span key={c.key} data-gs-cap={c.key} style={{ display: 'inline-flex' }}>
|
||||||
|
<HwatuCard card={c as HwatuInfo} size="sm" />
|
||||||
|
</span>
|
||||||
))}
|
))}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
@@ -260,7 +263,7 @@ function SeatBox({ seat, v, players, me, deadline }: { seat: SeatView; v: Gostop
|
|||||||
const u = userOf(players, seat.id);
|
const u = userOf(players, seat.id);
|
||||||
const active = actorOf(v) === seat.id;
|
const active = actorOf(v) === seat.id;
|
||||||
return (
|
return (
|
||||||
<li className={`gs-seat${active ? ' turn' : ''}${!seat.participant && v.step !== 'sell' ? ' out' : ''}`} aria-label={`${u.nickname}, 방 점수 ${signed(seat.total)}${seat.isDealer ? ', 선' : ''}${seat.participant ? `, 지금 ${seat.score.total}점, 손패 ${seat.handCount}장` : ''}`}>
|
<li className={`gs-seat${active ? ' turn anim-glow' : ''}${!seat.participant && v.step !== 'sell' ? ' out' : ''}`} data-fx-seat={seat.id} aria-label={`${u.nickname}, 방 점수 ${signed(seat.total)}${seat.isDealer ? ', 선' : ''}${seat.participant ? `, 지금 ${seat.score.total}점, 손패 ${seat.handCount}장` : ''}`}>
|
||||||
<div className="gs-head">
|
<div className="gs-head">
|
||||||
<Avatar user={u} size={26} />
|
<Avatar user={u} size={26} />
|
||||||
<span className="nm">
|
<span className="nm">
|
||||||
@@ -308,7 +311,7 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
|||||||
const pf = v.pendingFlip;
|
const pf = v.pendingFlip;
|
||||||
return (
|
return (
|
||||||
<div className="gs-table" role="region" aria-label="바닥">
|
<div className="gs-table" role="region" aria-label="바닥">
|
||||||
<ul className="gs-floor" aria-label="바닥 패(월별)">
|
<ul className="gs-floor" data-fx="gs-floor" aria-label="바닥 패(월별)">
|
||||||
{months.map((m) => {
|
{months.map((m) => {
|
||||||
const g = v.floor.find((x) => x.month === m);
|
const g = v.floor.find((x) => x.month === m);
|
||||||
const cls = `gs-slot${g ? ' has' : ''}${g && g.cards.length === 3 ? (g.natural ? ' ppeok natural' : ' ppeok') : ''}`;
|
const cls = `gs-slot${g ? ' has' : ''}${g && g.cards.length === 3 ? (g.natural ? ' ppeok natural' : ' ppeok') : ''}`;
|
||||||
@@ -316,14 +319,16 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
|||||||
? `${m}월 ${g.cards.length}장${g.cards.length === 3 ? (g.natural ? ', 처음 깔린 3장' : `, ${nick(players, g.ppeokBy)}님이 싼 뻑`) : ''}: ${g.cards.map((c) => c.name).join(', ')}`
|
? `${m}월 ${g.cards.length}장${g.cards.length === 3 ? (g.natural ? ', 처음 깔린 3장' : `, ${nick(players, g.ppeokBy)}님이 싼 뻑`) : ''}: ${g.cards.map((c) => c.name).join(', ')}`
|
||||||
: `${m}월 없음`;
|
: `${m}월 없음`;
|
||||||
return (
|
return (
|
||||||
<li key={m} className={cls} aria-label={label}>
|
<li key={m} className={cls} data-gs-month={m} aria-label={label}>
|
||||||
<span className="m" aria-hidden>
|
<span className="m" aria-hidden>
|
||||||
{m}월
|
{m}월
|
||||||
</span>
|
</span>
|
||||||
{g && (
|
{g && (
|
||||||
<span className="gs-slot-cards">
|
<span className="gs-slot-cards">
|
||||||
{g.cards.map((c) => (
|
{g.cards.map((c) => (
|
||||||
<Card key={c.key} c={c} size={narrow ? 'sm' : 'md'} className={glow.has(c.id) ? 'gs-glow' : undefined} />
|
<span key={c.key} className={glow.has(c.id) ? 'gs-glow' : undefined} data-gs-floor={c.key} style={{ display: 'inline-flex' }}>
|
||||||
|
<HwatuCard card={c as HwatuInfo} size={narrow ? 'sm' : 'md'} />
|
||||||
|
</span>
|
||||||
))}
|
))}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -333,7 +338,7 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
|||||||
</ul>
|
</ul>
|
||||||
<div className="gs-side">
|
<div className="gs-side">
|
||||||
<div className="gs-deck">
|
<div className="gs-deck">
|
||||||
<div aria-label={`더미 ${v.deckCount}장`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
|
<div data-fx="gs-deck" aria-label={`더미 ${v.deckCount}장`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
|
||||||
<HwatuCard card={null} size={narrow ? 'sm' : 'md'} />
|
<HwatuCard card={null} size={narrow ? 'sm' : 'md'} />
|
||||||
<strong>{v.deckCount}장</strong>
|
<strong>{v.deckCount}장</strong>
|
||||||
</div>
|
</div>
|
||||||
@@ -351,7 +356,9 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
|||||||
{pf && (
|
{pf && (
|
||||||
<div aria-label={`뒤집은 패 ${pf.flipped.name}`} style={{ textAlign: 'center' }}>
|
<div aria-label={`뒤집은 패 ${pf.flipped.name}`} style={{ textAlign: 'center' }}>
|
||||||
<div className="small">뒤집은 패</div>
|
<div className="small">뒤집은 패</div>
|
||||||
<Card c={pf.flipped} size="sm" className="gs-glow" />
|
<span className="gs-glow" data-fx="gs-pflip" style={{ display: 'inline-flex' }}>
|
||||||
|
<HwatuCard card={pf.flipped as HwatuInfo} size="sm" />
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -423,8 +430,8 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a
|
|||||||
setAsk(null);
|
setAsk(null);
|
||||||
}, [v.turn, v.step, v.roundNo, v.lastTurn?.seq]);
|
}, [v.turn, v.step, v.roundNo, v.lastTurn?.seq]);
|
||||||
const hand = v.myHand ?? [];
|
const hand = v.myHand ?? [];
|
||||||
const send = (a: object) => {
|
const send = (a: { card: number | 'dummy'; target?: number; shake?: boolean; bomb?: boolean }) => {
|
||||||
sounds.stone();
|
rememberPlay(a.card);
|
||||||
act({ type: 'play', ...a });
|
act({ type: 'play', ...a });
|
||||||
setLifted(null);
|
setLifted(null);
|
||||||
setAsk(null);
|
setAsk(null);
|
||||||
@@ -446,7 +453,7 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a
|
|||||||
const floorCards = (ids: number[]) => v.floor.flatMap((g) => g.cards).filter((c) => ids.includes(c.id));
|
const floorCards = (ids: number[]) => v.floor.flatMap((g) => g.cards).filter((c) => ids.includes(c.id));
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="gs-hand" role="group" aria-label="내 손패">
|
<div className="gs-hand" data-fx="gs-hand" role="group" aria-label="내 손패">
|
||||||
{hand.map((h) => {
|
{hand.map((h) => {
|
||||||
const match = hints && h.matches.length > 0;
|
const match = hints && h.matches.length > 0;
|
||||||
const tag = h.canBomb ? '폭탄' : h.canShake ? '흔들기' : null;
|
const tag = h.canBomb ? '폭탄' : h.canShake ? '흔들기' : null;
|
||||||
@@ -456,6 +463,7 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a
|
|||||||
key={h.card.key}
|
key={h.card.key}
|
||||||
type="button"
|
type="button"
|
||||||
className="gs-hcard"
|
className="gs-hcard"
|
||||||
|
data-gs-hand={h.card.key}
|
||||||
data-match={match || undefined}
|
data-match={match || undefined}
|
||||||
data-lifted={lifted === h.card.id || undefined}
|
data-lifted={lifted === h.card.id || undefined}
|
||||||
disabled={!canPlay}
|
disabled={!canPlay}
|
||||||
@@ -540,7 +548,7 @@ function MyArea(props: BoardProps<GostopView> & { onFocusCard: (h: HandCardView
|
|||||||
const active = actorOf(v) === me;
|
const active = actorOf(v) === me;
|
||||||
if (v.phase !== 'playing') return null;
|
if (v.phase !== 'playing') return null;
|
||||||
return (
|
return (
|
||||||
<div className={`gs-me${active ? ' turn' : ''}`} aria-label="내 자리">
|
<div className={`gs-me${active ? ' turn anim-glow' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||||
<div className="gs-head">
|
<div className="gs-head">
|
||||||
<Avatar user={userOf(players, me)} size={26} />
|
<Avatar user={userOf(players, me)} size={26} />
|
||||||
<span className="nm">나 · 합계 {signed(seat.total)}</span>
|
<span className="nm">나 · 합계 {signed(seat.total)}</span>
|
||||||
@@ -672,7 +680,7 @@ function Decisions({ view: v, me, players, act, pending }: BoardProps<GostopView
|
|||||||
return (
|
return (
|
||||||
<Sheet onClose={nop} label="국진 정하기">
|
<Sheet onClose={nop} label="국진 정하기">
|
||||||
<h2>9월 열끗(국진)을 어떻게 쓸까요?</h2>
|
<h2>9월 열끗(국진)을 어떻게 쓸까요?</h2>
|
||||||
<p className="muted">열끗 1장 또는 쌍피(피 2장 값)로 셀 수 있어요. 시간이 지나면 나에게 유리한 쪽으로 정해져요.</p>
|
<p className="muted">열끗 1장 또는 쌍피(피 2장 값)로 셀 수 있어요.{v.rules.decisionSeconds === null ? '' : ' 시간이 지나면 나에게 유리한 쪽으로 정해져요.'}</p>
|
||||||
<div className="gs-big">
|
<div className="gs-big">
|
||||||
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'gukjin', as: 'yeol' })}>
|
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'gukjin', as: 'yeol' })}>
|
||||||
열끗으로<small>내 점수 {g.yeolScore}점</small>
|
열끗으로<small>내 점수 {g.yeolScore}점</small>
|
||||||
@@ -703,7 +711,7 @@ function RoundResult({ view: v, me, players, act, pending }: BoardProps<GostopVi
|
|||||||
const seat = v.seats.find((s) => s.id === me);
|
const seat = v.seats.find((s) => s.id === me);
|
||||||
const nextMult = v.rules.nagariMultiplier === 'x2' ? Math.min(2 ** v.nagariStreak, v.rules.nagariMaxMultiplier) : 1;
|
const nextMult = v.rules.nagariMultiplier === 'x2' ? Math.min(2 ** v.nagariStreak, v.rules.nagariMaxMultiplier) : 1;
|
||||||
return (
|
return (
|
||||||
<section className="gs-panel gs-res" aria-label={`${v.roundNo}판 결과`} aria-live="polite">
|
<section className="gs-panel gs-res" data-fx="gs-result" aria-label={`${v.roundNo}판 결과`} aria-live="polite">
|
||||||
<h2 style={{ margin: 0 }}>
|
<h2 style={{ margin: 0 }}>
|
||||||
{v.roundNo}판 결과 · {outcomeTitle(o, players, me)}
|
{v.roundNo}판 결과 · {outcomeTitle(o, players, me)}
|
||||||
</h2>
|
</h2>
|
||||||
@@ -777,13 +785,336 @@ function RoundResult({ view: v, me, players, act, pending }: BoardProps<GostopVi
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- motion + sound
|
||||||
|
|
||||||
|
/** 고스톱 sounds on top of the shared palette (synthesized, no files). */
|
||||||
|
const gsSfx = {
|
||||||
|
/** "탁!" — a hwatu card slapped on the floor. */
|
||||||
|
slap: (gain = 1, delay = 0) => {
|
||||||
|
noise(70, 0.3 * gain, delay, 'lowpass', 900);
|
||||||
|
noise(22, 0.12 * gain, delay, 'highpass', 3200);
|
||||||
|
tone(120, 90, 'sine', 0.22 * gain, delay, { slideTo: 60 });
|
||||||
|
},
|
||||||
|
/** Cards taken into the pile ("착착"). */
|
||||||
|
gather: (n: number) => {
|
||||||
|
for (let i = 0; i < Math.min(n, 4); i++) noise(45, 0.12, i * 60, 'bandpass', 1700 + i * 200, 1);
|
||||||
|
},
|
||||||
|
/** 쪽 */
|
||||||
|
kiss: () => {
|
||||||
|
tone(1100, 70, 'sine', 0.14, 0, { slideTo: 2300 });
|
||||||
|
noise(25, 0.08, 55, 'highpass', 5000);
|
||||||
|
},
|
||||||
|
/** 뻑 — a dull, deflating thud. */
|
||||||
|
ppeok: () => {
|
||||||
|
noise(140, 0.22, 0, 'lowpass', 500);
|
||||||
|
tone(320, 280, 'sawtooth', 0.06, 0, { slideTo: 90 });
|
||||||
|
},
|
||||||
|
/** 따닥 — two quick slaps. */
|
||||||
|
ttadak: () => {
|
||||||
|
gsSfx.slap(0.9);
|
||||||
|
gsSfx.slap(1, 110);
|
||||||
|
tone(988, 90, 'triangle', 0.08, 200);
|
||||||
|
},
|
||||||
|
/** 싹쓸이 — a broom sweep, then the pile. */
|
||||||
|
sweep: () => {
|
||||||
|
noise(260, 0.12, 0, 'bandpass', 1200, 0.5);
|
||||||
|
sfx.collect();
|
||||||
|
},
|
||||||
|
/** 폭탄 */
|
||||||
|
boom: () => {
|
||||||
|
noise(450, 0.35, 0, 'lowpass', 280);
|
||||||
|
tone(85, 420, 'sine', 0.3, 0, { slideTo: 38 });
|
||||||
|
},
|
||||||
|
/** 흔들기 — cards rattled in the hand. */
|
||||||
|
rattle: () => {
|
||||||
|
for (let i = 0; i < 6; i++) noise(35, 0.12, i * 60, 'bandpass', 2300 + (i % 2) * 700, 3);
|
||||||
|
},
|
||||||
|
/** 고 — rising, one step higher per 고. */
|
||||||
|
go: (n: number) => {
|
||||||
|
const up = Math.min(n, 5) * 60;
|
||||||
|
[523, 659, 784].forEach((f, i) => tone(f + up, 110, 'square', 0.06, i * 70));
|
||||||
|
},
|
||||||
|
nagari: () => [440, 370, 311].forEach((f, i) => tone(f, 200, 'triangle', 0.12, i * 160)),
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Where my last played card was (its button is gone once the view arrives), so the floor card flies from there. */
|
||||||
|
let myPlayRect: DOMRect | null = null;
|
||||||
|
function rememberPlay(card: number | 'dummy'): void {
|
||||||
|
myPlayRect = card === 'dummy' ? null : (document.querySelector(`.gs-hcard[data-gs-hand$="c${card}"]`)?.getBoundingClientRect() ?? null);
|
||||||
|
}
|
||||||
|
|
||||||
|
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
|
||||||
|
const byAttr = (attr: string, key: string | number): Element | null => document.querySelector(`[${attr}="${cssEsc(String(key))}"]`);
|
||||||
|
const slotEl = (month: number) => (month > 0 ? byAttr('data-gs-month', month) : null);
|
||||||
|
const capEl = (id: string) => byAttr('data-fx-cap', id) ?? seatEl(id);
|
||||||
|
const CAP_KINDS = ['gwang', 'yeol', 'tti', 'pi'] as const;
|
||||||
|
|
||||||
|
/** A card turned face up (Web Animations, composite add, so it can run together with a fly-in). */
|
||||||
|
function flipIn(el: Element | null | undefined, delay = 0): void {
|
||||||
|
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||||
|
(el as HTMLElement).animate(
|
||||||
|
[{ transform: 'perspective(600px) rotateY(90deg)' }, { transform: 'perspective(600px) rotateY(-12deg)', offset: 0.6 }, { transform: 'perspective(600px) rotateY(0deg)' }],
|
||||||
|
{ duration: 380, delay, easing: 'ease', fill: 'backwards', composite: 'add' },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function capOwners(v: GostopView): Map<string, string> {
|
||||||
|
const m = new Map<string, string>();
|
||||||
|
for (const s of v.seats) for (const k of CAP_KINDS) for (const c of s.captured[k]) m.set(c.key, s.id);
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TAG_ORDER: TurnTag[] = ['samPpeok', 'yeonPpeok', 'firstPpeok', 'bomb', 'ttadak', 'jaPpeok', 'ppeokEat', 'ppeok', 'jjok', 'sseul', 'shake', 'bonus', 'bonusFlip'];
|
||||||
|
const TAG_TONE: Partial<Record<TurnTag, BannerTone>> = {
|
||||||
|
samPpeok: 'red', yeonPpeok: 'red', firstPpeok: 'red', ppeok: 'red', bomb: 'red',
|
||||||
|
ttadak: 'gold', jaPpeok: 'gold', ppeokEat: 'gold', jjok: 'gold', sseul: 'green', shake: 'blue', bonus: 'blue', bonusFlip: 'blue',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Sound (and a shake) for the most important tag of a turn. */
|
||||||
|
function tagFx(tag: TurnTag | undefined, actor: string | null): void {
|
||||||
|
switch (tag) {
|
||||||
|
case 'samPpeok':
|
||||||
|
gsSfx.ppeok();
|
||||||
|
later(250, sfx.fanfare);
|
||||||
|
break;
|
||||||
|
case 'yeonPpeok':
|
||||||
|
case 'firstPpeok':
|
||||||
|
gsSfx.ppeok();
|
||||||
|
later(280, sfx.good);
|
||||||
|
break;
|
||||||
|
case 'ppeok':
|
||||||
|
gsSfx.ppeok();
|
||||||
|
bump(fxEl('gs-floor'), 'shake');
|
||||||
|
break;
|
||||||
|
case 'bomb':
|
||||||
|
gsSfx.boom();
|
||||||
|
bump(fxEl('gs-floor'), 'shake');
|
||||||
|
break;
|
||||||
|
case 'ttadak':
|
||||||
|
gsSfx.ttadak();
|
||||||
|
break;
|
||||||
|
case 'jaPpeok':
|
||||||
|
case 'ppeokEat':
|
||||||
|
sfx.good();
|
||||||
|
break;
|
||||||
|
case 'jjok':
|
||||||
|
gsSfx.kiss();
|
||||||
|
break;
|
||||||
|
case 'sseul':
|
||||||
|
gsSfx.sweep();
|
||||||
|
break;
|
||||||
|
case 'shake':
|
||||||
|
gsSfx.rattle();
|
||||||
|
if (actor) bump(seatEl(actor), 'shake');
|
||||||
|
break;
|
||||||
|
case 'bonus':
|
||||||
|
case 'bonusFlip':
|
||||||
|
sfx.pop();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
sfx.capture();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sounds + motion for every change of the table — mine, the other players' and the bots' — by diffing the previous
|
||||||
|
* view: deal, card played (탁), deck card flipped, cards taken into a pile, 피 taken from another pile, 뻑·쪽·따닥·
|
||||||
|
* 싹쓸이·폭탄·흔들기 banners, 고, 광 팔기 and the round result. Nothing on the first render (join / reload / replay),
|
||||||
|
* except the first deal when mounted right at the start of the game.
|
||||||
|
*/
|
||||||
|
function useGostopFx(v: GostopView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||||
|
const prev = useRef<GostopView | null>(null);
|
||||||
|
const origin = (id: string | null): Element | DOMRect | null =>
|
||||||
|
!id ? null : id === me ? (myPlayRect ?? fxEl('gs-hand') ?? seatEl(id)) : seatEl(id);
|
||||||
|
|
||||||
|
const deal = () => {
|
||||||
|
const deck = fxEl('gs-deck');
|
||||||
|
sfx.shuffle();
|
||||||
|
later(300, () => sfx.deal(8, 55));
|
||||||
|
document.querySelectorAll('[data-gs-floor]').forEach((el, i) => flyFrom(el, deck, { delay: 300 + i * 45, rotate: 8 }));
|
||||||
|
const mine = document.querySelectorAll('[data-gs-hand]');
|
||||||
|
mine.forEach((el, i) => flyFrom(el, deck, { delay: 300 + i * 40, rotate: 10 }));
|
||||||
|
for (const s of v.seats) {
|
||||||
|
if (s.handCount === 0 || (s.id === me && mine.length > 0)) continue;
|
||||||
|
flyGhost(deck, seatEl(s.id), { kind: 'hwatu', count: 3, gap: 90, delay: 300 });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const p = prev.current;
|
||||||
|
prev.current = v;
|
||||||
|
if (!p) {
|
||||||
|
// Mounted right at the start of the game (nothing played yet): show the deal once.
|
||||||
|
if (v.roundNo === 1 && v.phase === 'playing' && !v.lastTurn && !v.sell?.decisions.length) deal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (p === v) return;
|
||||||
|
// A new round, or the same round dealt again (총통 다시 돌리기).
|
||||||
|
if (v.roundNo !== p.roundNo || (v.phase === 'playing' && p.phase === 'playing' && v.deckCount > p.deckCount)) {
|
||||||
|
myPlayRect = null;
|
||||||
|
if (v.phase === 'playing') deal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const deck = fxEl('gs-deck');
|
||||||
|
const lt = v.lastTurn;
|
||||||
|
const newTurn = !!lt && lt.seq !== (p.lastTurn?.seq ?? 0);
|
||||||
|
const pendingNew = !!v.pendingFlip && !p.pendingFlip;
|
||||||
|
// The flip that needed a choice: the played card and the flip were already shown with the choice.
|
||||||
|
const resumed = newTurn && !!p.pendingFlip;
|
||||||
|
const actor = newTurn ? lt!.player : (v.pendingFlip?.player ?? p.turn);
|
||||||
|
let bannerShown = false;
|
||||||
|
|
||||||
|
if (newTurn || pendingNew) {
|
||||||
|
const fresh = newTurn && !resumed;
|
||||||
|
const flippedKeys = new Set(fresh ? lt!.flipped.map((c) => c.key) : []);
|
||||||
|
const before = new Set(p.floor.flatMap((g) => g.cards.map((c) => c.key)));
|
||||||
|
const onFloor = new Set<string>();
|
||||||
|
let played = false;
|
||||||
|
let flipped = false;
|
||||||
|
for (const g of v.floor)
|
||||||
|
for (const c of g.cards) {
|
||||||
|
onFloor.add(c.key);
|
||||||
|
if (before.has(c.key)) continue;
|
||||||
|
const el = byAttr('data-gs-floor', c.key);
|
||||||
|
if (flippedKeys.has(c.key)) {
|
||||||
|
flyFrom(el, deck, { delay: 380, ms: 300, rotate: 0, scale: 0.8 });
|
||||||
|
flipIn(el, 380);
|
||||||
|
flipped = true;
|
||||||
|
} else {
|
||||||
|
flyFrom(el, origin(actor), { ms: 340, rotate: -14 });
|
||||||
|
played = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (fresh) {
|
||||||
|
// Cards that were taken right away never stay on the floor: a copy flies to their month.
|
||||||
|
for (const c of lt!.played) {
|
||||||
|
played = true;
|
||||||
|
if (!onFloor.has(c.key) && c.month > 0) flyGhost(origin(actor), slotEl(c.month), { kind: 'hwatu', ms: 340 });
|
||||||
|
}
|
||||||
|
for (const c of lt!.flipped) {
|
||||||
|
flipped = true;
|
||||||
|
if (!onFloor.has(c.key) && c.month > 0) flyGhost(deck, slotEl(c.month), { kind: 'hwatu', delay: 380, ms: 300 });
|
||||||
|
}
|
||||||
|
// 보너스패: the player takes one more card from the deck.
|
||||||
|
if (lt!.tags.includes('bonus') && actor !== me) flyGhost(deck, seatEl(actor!), { kind: 'hwatu', delay: 300 });
|
||||||
|
}
|
||||||
|
if (pendingNew) {
|
||||||
|
const el = fxEl('gs-pflip');
|
||||||
|
flyFrom(el, deck, { delay: 380, ms: 300, rotate: 0, scale: 0.8 });
|
||||||
|
flipIn(el, 380);
|
||||||
|
flipped = true;
|
||||||
|
played = true;
|
||||||
|
}
|
||||||
|
const bomb = fresh && lt!.tags.includes('bomb');
|
||||||
|
if (played) later(260, () => gsSfx.slap(bomb ? 1.4 : 1));
|
||||||
|
if (flipped) {
|
||||||
|
later(380, sfx.cardFlip);
|
||||||
|
later(640, () => gsSfx.slap(0.6));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cards that reached a pile: from the floor (their month), the deck or hand (bonus cards), or another pile (피 뺏기).
|
||||||
|
const capAt = resumed ? 120 : 720;
|
||||||
|
const owners = capOwners(p);
|
||||||
|
const robbed = new Set<string>();
|
||||||
|
let got = 0;
|
||||||
|
for (const s of v.seats)
|
||||||
|
for (const k of CAP_KINDS)
|
||||||
|
for (const c of s.captured[k]) {
|
||||||
|
const was = owners.get(c.key);
|
||||||
|
if (was === s.id) continue;
|
||||||
|
const el = byAttr('data-gs-cap', c.key);
|
||||||
|
if (was) {
|
||||||
|
flyFrom(el, capEl(was), { delay: capAt + 250, ms: 420, scale: 0.8, rotate: 0 });
|
||||||
|
robbed.add(was);
|
||||||
|
} else {
|
||||||
|
flyFrom(el, slotEl(c.month) ?? (flippedKeys.has(c.key) ? deck : origin(actor)), { delay: capAt, ms: 400, scale: 0.9, rotate: 0 });
|
||||||
|
got++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (got) later(capAt + 40, () => gsSfx.gather(got));
|
||||||
|
if (robbed.size) {
|
||||||
|
later(capAt + 250, sfx.whoosh);
|
||||||
|
for (const id of robbed) later(capAt + 250, () => bump(seatEl(id), 'shake'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newTurn) {
|
||||||
|
const f = flashText(v, players);
|
||||||
|
if (f) {
|
||||||
|
const top = TAG_ORDER.find((x) => lt!.tags.includes(x));
|
||||||
|
later(resumed ? 150 : 600, () => {
|
||||||
|
showBanner(f.big, (top && TAG_TONE[top]) ?? 'blue', f.small);
|
||||||
|
tagFx(top, actor);
|
||||||
|
});
|
||||||
|
bannerShown = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (actor === me) myPlayRect = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// My new hand cards during a round (보너스패 draw).
|
||||||
|
if (v.myHand && p.myHand) {
|
||||||
|
const had = new Set(p.myHand.map((h) => h.card.key));
|
||||||
|
v.myHand.filter((h) => !had.has(h.card.key)).forEach((h, i) => flyFrom(byAttr('data-gs-hand', h.card.key), deck, { delay: 300 + i * 60, rotate: 10 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 고
|
||||||
|
for (const s of v.seats) {
|
||||||
|
const b = p.seats.find((x) => x.id === s.id);
|
||||||
|
if (!b || s.goCount <= b.goCount) continue;
|
||||||
|
showBanner(`${s.goCount}고!`, 'red', s.id === me ? undefined : `${nick(players, s.id)}님`);
|
||||||
|
gsSfx.go(s.goCount);
|
||||||
|
bump(seatEl(s.id));
|
||||||
|
bannerShown = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 광팔기: a player sits out (and shows the cards they sell).
|
||||||
|
for (const d of v.sell?.decisions.slice(p.sell?.decisions.length ?? 0) ?? []) {
|
||||||
|
if (!d.sell) {
|
||||||
|
sfx.select();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const n = v.seats.find((s) => s.id === d.player)?.seller?.shown.length ?? 0;
|
||||||
|
showBanner(n ? '광 팔기!' : '죽기', 'blue', `${nick(players, d.player)}님${n ? ` · 광 ${n}장` : ''}`);
|
||||||
|
if (n) sfx.chips(Math.min(n, 4));
|
||||||
|
else sfx.whoosh();
|
||||||
|
bump(seatEl(d.player));
|
||||||
|
bannerShown = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Round result: 스톱 / 총통 / 삼뻑 / 나가리.
|
||||||
|
const o = v.outcome;
|
||||||
|
if (o && !p.outcome) {
|
||||||
|
const at = bannerShown ? 1000 : 0;
|
||||||
|
const who = o.winner === me ? '내가 이겼어요' : `${nick(players, o.winner)}님이 이겼어요`;
|
||||||
|
const nextMult = v.rules.nagariMultiplier === 'x2' ? Math.min(2 ** v.nagariStreak, v.rules.nagariMaxMultiplier) : 1;
|
||||||
|
const mySeat = v.seats.find((s) => s.id === me);
|
||||||
|
later(at, () => {
|
||||||
|
if (o.type === 'nagari') showBanner('나가리', 'dark', nextMult > 1 ? `다음 판 x${nextMult}` : undefined);
|
||||||
|
else showBanner(o.type === 'chongtong' ? '총통!' : o.type === 'samppeok' ? '삼뻑!' : '스톱!', o.type === 'samppeok' ? 'red' : 'gold', who);
|
||||||
|
// The last round: the result dialog already plays the win/lose sound.
|
||||||
|
if (o.type === 'nagari') gsSfx.nagari();
|
||||||
|
else if (v.phase === 'finished' && mySeat) return;
|
||||||
|
else if (o.winner === me) sounds.win();
|
||||||
|
else if (mySeat?.participant) sounds.lose();
|
||||||
|
else sfx.fanfare();
|
||||||
|
});
|
||||||
|
if (o.winner) {
|
||||||
|
const to = seatEl(o.winner) ?? fxEl('gs-result');
|
||||||
|
o.payments.forEach((pay, i) => {
|
||||||
|
if (pay.amount > 0) flyGhost(seatEl(pay.from) ?? fxEl('gs-result'), to, { kind: 'chip', count: 3, gap: 70, delay: at + 250 + i * 120 });
|
||||||
|
});
|
||||||
|
if (o.payments.some((pay) => pay.amount > 0)) later(at + 500, () => sfx.chips(4));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- board
|
// ---------------------------------------------------------------- board
|
||||||
|
|
||||||
function GostopBoard(props: BoardProps<GostopView>) {
|
function GostopBoard(props: BoardProps<GostopView>) {
|
||||||
const { view: v, me, players } = props;
|
const { view: v, me, players } = props;
|
||||||
const narrow = useNarrow();
|
const narrow = useNarrow();
|
||||||
const [focus, setFocus] = useState<HandCardView | null>(null);
|
const [focus, setFocus] = useState<HandCardView | null>(null);
|
||||||
const [flash, setFlash] = useState<{ big: string; small: string } | null>(null);
|
|
||||||
const [announce, setAnnounce] = useState('');
|
const [announce, setAnnounce] = useState('');
|
||||||
const mine = isMyTurn(v, me);
|
const mine = isMyTurn(v, me);
|
||||||
const prevMine = useRef(false);
|
const prevMine = useRef(false);
|
||||||
@@ -796,10 +1127,6 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
|||||||
`${nick(players, t.player)}님: ${t.played.map((c) => c.name).join(', ')}${t.played.length ? ' 냄, ' : ''}${t.flipped.map((c) => c.name).join(', ')} 뒤집음, ${t.captured.length}장 먹음${f ? `. ${f.big}` : ''}`,
|
`${nick(players, t.player)}님: ${t.played.map((c) => c.name).join(', ')}${t.played.length ? ' 냄, ' : ''}${t.flipped.map((c) => c.name).join(', ')} 뒤집음, ${t.captured.length}장 먹음${f ? `. ${f.big}` : ''}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
setFlash(f);
|
|
||||||
if (!f) return undefined;
|
|
||||||
const tm = setTimeout(() => setFlash(null), 1300);
|
|
||||||
return () => clearTimeout(tm);
|
|
||||||
}, [seq]); // eslint-disable-line react-hooks/exhaustive-deps
|
}, [seq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (mine && !prevMine.current && v.phase === 'playing') {
|
if (mine && !prevMine.current && v.phase === 'playing') {
|
||||||
@@ -811,10 +1138,11 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
|||||||
}, [mine]); // eslint-disable-line react-hooks/exhaustive-deps
|
}, [mine]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (v.outcome && v.phase !== 'playing') {
|
if (v.outcome && v.phase !== 'playing') {
|
||||||
if (v.outcome.winner === me) sounds.win();
|
|
||||||
setAnnounce(`${v.roundNo}판 결과: ${outcomeTitle(v.outcome, players, me)}`);
|
setAnnounce(`${v.roundNo}판 결과: ${outcomeTitle(v.outcome, players, me)}`);
|
||||||
}
|
}
|
||||||
}, [v.roundNo, v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
}, [v.roundNo, v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
const [banner, showBanner] = useBanner();
|
||||||
|
useGostopFx(v, me, players, showBanner);
|
||||||
const myIdx = v.seats.findIndex((s) => s.id === me);
|
const myIdx = v.seats.findIndex((s) => s.id === me);
|
||||||
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
||||||
const glow = new Set<number>(v.rules.hints && focus ? focus.matches : []);
|
const glow = new Set<number>(v.rules.hints && focus ? focus.matches : []);
|
||||||
@@ -831,12 +1159,7 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
|||||||
<RoundResult {...props} />
|
<RoundResult {...props} />
|
||||||
<MyArea {...props} onFocusCard={setFocus} />
|
<MyArea {...props} onFocusCard={setFocus} />
|
||||||
<Decisions {...props} />
|
<Decisions {...props} />
|
||||||
{flash && v.phase === 'playing' && (
|
{banner}
|
||||||
<div className="gs-flash" aria-hidden>
|
|
||||||
{flash.big}
|
|
||||||
<small>{flash.small}</small>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<p className="sr-only" aria-live="polite">
|
<p className="sr-only" aria-live="polite">
|
||||||
{announce}
|
{announce}
|
||||||
</p>
|
</p>
|
||||||
@@ -1033,12 +1356,14 @@ function Rules({ options }: { options?: GostopOptions }) {
|
|||||||
</div>
|
</div>
|
||||||
<strong>족보</strong>
|
<strong>족보</strong>
|
||||||
<JokboTable rules={{ ogwangPoints: o?.ogwangPoints ?? 15, biGwangThree: o?.biGwangThree ?? 2 }} />
|
<JokboTable rules={{ ogwangPoints: o?.ogwangPoints ?? 15, biGwangThree: o?.biGwangThree ?? 2 }} />
|
||||||
<p className="small muted">시간 안에 내지 않으면 바닥과 맞는 패 중 가장 좋은 패를 대신 내고, 고·스톱은 스톱으로 정해요. 두 번 연속 시간을 넘기면 2초 만에 자동으로 진행돼요.</p>
|
<p className="small muted">
|
||||||
|
{o?.turnSeconds === null ? '이 방은 차례 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 내지 않으면'} 바닥과 맞는 패 중 가장 좋은 패를 대신 내고, 고·스톱은 스톱으로 정해요. 두 번 연속 시간을 넘기면 2초 만에 자동으로 진행돼요.
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="segmented" role="group" aria-label={label}>
|
<div className="segmented" role="group" aria-label={label}>
|
||||||
{options.map(([k, l]) => (
|
{options.map(([k, l]) => (
|
||||||
@@ -1080,7 +1405,7 @@ function Options({ value: o, onChange }: OptionsProps<GostopOptions>) {
|
|||||||
<Seg label="고·스톱 기준 점수" value={o.winScore} options={[['auto', '자동(맞고 7·고스톱 3)'], [3, '3점'], [5, '5점'], [7, '7점']]} onChange={(winScore) => set({ winScore })} />
|
<Seg label="고·스톱 기준 점수" value={o.winScore} options={[['auto', '자동(맞고 7·고스톱 3)'], [3, '3점'], [5, '5점'], [7, '7점']]} onChange={(winScore) => set({ winScore })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="한 턴 제한 시간">
|
<Field label="한 턴 제한 시간">
|
||||||
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[5, '5초'], [10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[5, '5초'], [10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||||
</Field>
|
</Field>
|
||||||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||||||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||||||
@@ -1091,7 +1416,7 @@ function Options({ value: o, onChange }: OptionsProps<GostopOptions>) {
|
|||||||
<Seg label="보너스패" value={o.bonusCards} options={[['auto', '자동(맞고만)'], ['none', '없음'], ['2+1', '2피 2장 + 3피 1장'], ['3+1', '2피 3장 + 3피 1장']]} onChange={(bonusCards) => set({ bonusCards })} />
|
<Seg label="보너스패" value={o.bonusCards} options={[['auto', '자동(맞고만)'], ['none', '없음'], ['2+1', '2피 2장 + 3피 1장'], ['3+1', '2피 3장 + 3피 1장']]} onChange={(bonusCards) => set({ bonusCards })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="고·스톱·선택 제한 시간">
|
<Field label="고·스톱·선택 제한 시간">
|
||||||
<Seg label="고·스톱·선택 제한 시간" value={o.decisionSeconds} options={[[5, '5초'], [10, '10초'], [15, '15초'], [20, '20초'], [30, '30초']]} onChange={(decisionSeconds) => set({ decisionSeconds })} />
|
<Seg label="고·스톱·선택 제한 시간" value={o.decisionSeconds} options={[[5, '5초'], [10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [null, '무제한']]} onChange={(decisionSeconds) => set({ decisionSeconds })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="피박 기준(진 사람 피 값)">
|
<Field label="피박 기준(진 사람 피 값)">
|
||||||
<Seg label="피박 기준" value={o.piBakLimit} options={[['auto', '자동(맞고 7·고스톱 5)'], [5, '5 이하'], [6, '6 이하'], [7, '7 이하']]} onChange={(piBakLimit) => set({ piBakLimit })} />
|
<Seg label="피박 기준" value={o.piBakLimit} options={[['auto', '자동(맞고 7·고스톱 5)'], [5, '5 이하'], [6, '6 이하'], [7, '7 이하']]} onChange={(piBakLimit) => set({ piBakLimit })} />
|
||||||
@@ -1155,7 +1480,7 @@ function optionsSummary(o: GostopOptions): string {
|
|||||||
return [
|
return [
|
||||||
`${o.rounds}판`,
|
`${o.rounds}판`,
|
||||||
o.winScore === 'auto' ? '맞고 7점·고스톱 3점' : `${o.winScore}점 나기`,
|
o.winScore === 'auto' ? '맞고 7점·고스톱 3점' : `${o.winScore}점 나기`,
|
||||||
`${o.turnSeconds}초`,
|
o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`,
|
||||||
o.bonusCards === 'none' ? '보너스패 없음' : o.bonusCards === 'auto' ? '' : `보너스 ${o.bonusCards}`,
|
o.bonusCards === 'none' ? '보너스패 없음' : o.bonusCards === 'auto' ? '' : `보너스 ${o.bonusCards}`,
|
||||||
o.gwangPalgi ? '' : '광팔기 없음',
|
o.gwangPalgi ? '' : '광팔기 없음',
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
/** 구십구 화면 (docs/games/ninety-nine.md §9). */
|
/** 구십구 화면 (docs/games/ninety-nine.md §9). */
|
||||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||||
import type { CardFace, CardKind, ChoiceView, HandCardView, LogEntry, NNOptions, NinetyNineView, SeatView } from '@bg/games/ninety-nine';
|
import type { CardFace, CardKind, ChoiceView, HandCardView, LogEntry, NNOptions, NinetyNineView, SeatView } from '@bg/games/ninety-nine';
|
||||||
import type { PublicUser } from '@bg/shared/lite';
|
import type { PublicUser } from '@bg/shared/lite';
|
||||||
import { Avatar } from '../../components/ui';
|
import { Avatar } from '../../components/ui';
|
||||||
import { TurnTimer } from '../../components/TurnTimer';
|
import { TurnTimer } from '../../components/TurnTimer';
|
||||||
import { PlayingCard } from '../../components/cards/PlayingCard';
|
import { PlayingCard } from '../../components/cards/PlayingCard';
|
||||||
import { haptic, sounds } from '../../lib/feedback';
|
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||||
|
import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useChange, useNewEntries } from '../card-fx';
|
||||||
import { useSeatRows } from '../../lib/seat-rows';
|
import { useSeatRows } from '../../lib/seat-rows';
|
||||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||||
import { helpNow, resolvedHandSize } from './help';
|
import { helpNow, resolvedHandSize } from './help';
|
||||||
@@ -148,6 +149,7 @@ const CSS = `
|
|||||||
.nn-rules td, .nn-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); }
|
.nn-rules td, .nn-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); }
|
||||||
.nn-rules .nn-face { width: 34px; height: 48px; --cw: 34px; }
|
.nn-rules .nn-face { width: 34px; height: 48px; --cw: 34px; }
|
||||||
.nn-rules .nn-art::before { inset: 3px; }
|
.nn-rules .nn-art::before { inset: 3px; }
|
||||||
|
.fx-ghost.nn-ghost { background: #fffdf7; color: #1f2937; border: 2px solid #334155; box-shadow: 0 3px 8px rgba(0,0,0,.35); display: flex; align-items: center; justify-content: center; font: 900 13px/1 system-ui, sans-serif; }
|
||||||
@keyframes nn-pop { 0% { transform: scale(.7); } 70% { transform: scale(1.08); } 100% { transform: scale(1); } }
|
@keyframes nn-pop { 0% { transform: scale(.7); } 70% { transform: scale(1.08); } 100% { transform: scale(1); } }
|
||||||
@keyframes nn-break { 0% { transform: scale(1); color: #e11d48; opacity: 1; } 40% { transform: scale(1.5) rotate(-15deg); } 100% { transform: scale(1); } }
|
@keyframes nn-break { 0% { transform: scale(1); color: #e11d48; opacity: 1; } 40% { transform: scale(1.5) rotate(-15deg); } 100% { transform: scale(1); } }
|
||||||
/* PC/tablet: many players stack into even rows (9 → 5 + 4) instead of scrolling sideways. Phones keep one swipeable row. */
|
/* PC/tablet: many players stack into even rows (9 → 5 + 4) instead of scrolling sideways. Phones keep one swipeable row. */
|
||||||
@@ -239,7 +241,7 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: NinetyNineV
|
|||||||
const u = userOf(players, s.id);
|
const u = userOf(players, s.id);
|
||||||
const rank = v.result?.ranking.find((r) => r.player === s.id)?.rank;
|
const rank = v.result?.ranking.find((r) => r.player === s.id)?.rank;
|
||||||
return (
|
return (
|
||||||
<li className={`nn-seat${s.isTurn ? ' turn' : ''}${s.alive ? '' : ' out'}`} aria-label={seatLabel(s, v, players, me)}>
|
<li className={`nn-seat${s.isTurn ? ' turn anim-glow' : ''}${s.alive ? '' : ' out'}`} data-fx-seat={s.id} aria-label={seatLabel(s, v, players, me)}>
|
||||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||||
<Avatar user={u} size={24} />
|
<Avatar user={u} size={24} />
|
||||||
<span className="nm">{u.nickname}</span>
|
<span className="nm">{u.nickname}</span>
|
||||||
@@ -287,12 +289,12 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor
|
|||||||
<TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={cur === me} size={40} />
|
<TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={cur === me} size={40} />
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<span className="nn-chip" aria-label={`뽑을 카드 ${v.drawPileCount}장`}>
|
<span className="nn-chip" data-fx="nn-deck" aria-label={`뽑을 카드 ${v.drawPileCount}장`}>
|
||||||
더미 {v.drawPileCount}장
|
더미 {v.drawPileCount}장
|
||||||
</span>
|
</span>
|
||||||
{v.livesStart > 0 && <span className="nn-chip">{v.round}판째</span>}
|
{v.livesStart > 0 && <span className="nn-chip">{v.round}판째</span>}
|
||||||
</div>
|
</div>
|
||||||
<div className="nn-dial" role="img" aria-label={`지금 합계 ${v.total}`}>
|
<div className="nn-dial" data-fx="nn-dial" role="img" aria-label={`지금 합계 ${v.total}`}>
|
||||||
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden>
|
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden>
|
||||||
<circle cx="50" cy="50" r={r} fill="rgba(0,0,0,.28)" stroke="rgba(255,255,255,.18)" strokeWidth="8" />
|
<circle cx="50" cy="50" r={r} fill="rgba(0,0,0,.28)" stroke="rgba(255,255,255,.18)" strokeWidth="8" />
|
||||||
<circle cx="50" cy="50" r={r} fill="none" stroke={gaugeColor(v.total)} strokeWidth="8" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - frac)} />
|
<circle cx="50" cy="50" r={r} fill="none" stroke={gaugeColor(v.total)} strokeWidth="8" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - frac)} />
|
||||||
@@ -396,8 +398,14 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
|||||||
setNote('');
|
setNote('');
|
||||||
}, [v.turnNo]);
|
}, [v.turnNo]);
|
||||||
const chosen = my.hand.find((c) => c.id === sel) ?? null;
|
const chosen = my.hand.find((c) => c.id === sel) ?? null;
|
||||||
|
// Cards that came to me (refill, a new round): fly in from the draw pile.
|
||||||
|
useNewEntries(my.hand, (c) => c.id, (fresh) => {
|
||||||
|
const deck = fxEl('nn-deck');
|
||||||
|
fresh.forEach((c, i) => flyFrom(document.querySelector(`.nn-card[data-id="${cssEsc(c.id)}"]`), deck, { delay: 120 + i * 70, rotate: 8 }));
|
||||||
|
}, 30);
|
||||||
const send = (c: HandCardView, extra: Record<string, unknown> = {}) => {
|
const send = (c: HandCardView, extra: Record<string, unknown> = {}) => {
|
||||||
if (pending) return;
|
if (pending) return;
|
||||||
|
rememberPlay(c.id);
|
||||||
act({ type: 'play', cardId: c.id, ...extra });
|
act({ type: 'play', cardId: c.id, ...extra });
|
||||||
setSel(null);
|
setSel(null);
|
||||||
};
|
};
|
||||||
@@ -419,6 +427,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
|||||||
else setSel(null);
|
else setSel(null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
sfx.select();
|
||||||
setSel(c.id);
|
setSel(c.id);
|
||||||
};
|
};
|
||||||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||||
@@ -449,7 +458,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="nn-hand" role="group" aria-label="내 카드. 좌우 방향키로 고르고 Enter로 고른 뒤 한 번 더 누르면 내요" onKeyDown={onKey} style={{ '--cw': cw } as CSSProperties}>
|
<div className="nn-hand" data-fx="nn-hand" role="group" aria-label="내 카드. 좌우 방향키로 고르고 Enter로 고른 뒤 한 번 더 누르면 내요" onKeyDown={onKey} style={{ '--cw': cw } as CSSProperties}>
|
||||||
{my.hand.map((c) => {
|
{my.hand.map((c) => {
|
||||||
const p = previewOf(c);
|
const p = previewOf(c);
|
||||||
return (
|
return (
|
||||||
@@ -457,6 +466,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
|||||||
key={c.id}
|
key={c.id}
|
||||||
type="button"
|
type="button"
|
||||||
className="nn-card"
|
className="nn-card"
|
||||||
|
data-id={c.id}
|
||||||
data-legal={myTurn ? c.legal : undefined}
|
data-legal={myTurn ? c.legal : undefined}
|
||||||
aria-pressed={sel === c.id}
|
aria-pressed={sel === c.id}
|
||||||
aria-label={`${cardAria(c, myTurn)}${sel === c.id && myTurn && single(c) ? '. 한 번 더 누르면 내요' : ''}`}
|
aria-label={`${cardAria(c, myTurn)}${sel === c.id && myTurn && single(c) ? '. 한 번 더 누르면 내요' : ''}`}
|
||||||
@@ -559,6 +569,8 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps<Nine
|
|||||||
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
||||||
const opps = useSeatRows<HTMLUListElement>(others.length);
|
const opps = useSeatRows<HTMLUListElement>(others.length);
|
||||||
const meSeat = v.seats.find((s) => s.id === me);
|
const meSeat = v.seats.find((s) => s.id === me);
|
||||||
|
const [banner, showBanner] = useBanner();
|
||||||
|
useNinetyNineFx(v, me, players, showBanner);
|
||||||
return (
|
return (
|
||||||
<div className="nn">
|
<div className="nn">
|
||||||
<style>{CSS}</style>
|
<style>{CSS}</style>
|
||||||
@@ -577,10 +589,145 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps<Nine
|
|||||||
<p className="sr-only" aria-live="polite">
|
<p className="sr-only" aria-live="polite">
|
||||||
{announce}
|
{announce}
|
||||||
</p>
|
</p>
|
||||||
|
{banner}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- sounds + motion (2026-10-13)
|
||||||
|
|
||||||
|
/** 구십구 sounds on top of the shared palette (synthesized, no files). */
|
||||||
|
const nnSfx = {
|
||||||
|
/** Direction flips: a rising then falling swoop. */
|
||||||
|
reverse: () => {
|
||||||
|
tone(420, 200, 'triangle', 0.09, 0, { slideTo: 880 });
|
||||||
|
tone(880, 200, 'triangle', 0.07, 150, { slideTo: 420 });
|
||||||
|
},
|
||||||
|
/** 홀드 / 0: a short "tock", nothing changes. */
|
||||||
|
hold: () => {
|
||||||
|
tone(600, 60, 'square', 0.04);
|
||||||
|
tone(600, 60, 'square', 0.04, 110);
|
||||||
|
},
|
||||||
|
/** Straight to 99: alarm-ish rising siren. */
|
||||||
|
to99: () => {
|
||||||
|
tone(330, 380, 'sawtooth', 0.05, 0, { slideTo: 990 });
|
||||||
|
tone(990, 160, 'square', 0.05, 380);
|
||||||
|
},
|
||||||
|
/** Total gets close to 99: a quick tense heartbeat. */
|
||||||
|
tense: () => {
|
||||||
|
tone(90, 120, 'sine', 0.2);
|
||||||
|
tone(80, 140, 'sine', 0.16, 180);
|
||||||
|
},
|
||||||
|
/** A life (heart) breaks. */
|
||||||
|
heart: () => {
|
||||||
|
noise(120, 0.1, 0, 'highpass', 2500);
|
||||||
|
tone(660, 300, 'triangle', 0.08, 40, { slideTo: 220 });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Where my last played card was (its button is gone once the view arrives), so the ghost starts there. */
|
||||||
|
let myPlayRect: DOMRect | null = null;
|
||||||
|
const rememberPlay = (id: string) => {
|
||||||
|
myPlayRect = document.querySelector(`.nn-card[data-id="${cssEsc(id)}"]`)?.getBoundingClientRect() ?? null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const nnLogKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`;
|
||||||
|
|
||||||
|
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
|
||||||
|
function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||||
|
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
|
||||||
|
const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`);
|
||||||
|
const dealAll = (delay: number) => {
|
||||||
|
const deck = fxEl('nn-deck');
|
||||||
|
later(delay, sfx.shuffle);
|
||||||
|
later(delay + 300, () => sfx.deal(Math.min(8, v.seats.filter((s) => s.alive).length * 2), 60));
|
||||||
|
for (const s of v.seats) if (s.alive && s.id !== me) flyGhost(deck, seatEl(s.id), { count: 3, gap: 90, delay: delay + 280 });
|
||||||
|
};
|
||||||
|
useNewEntries(v.log, nnLogKey, (fresh) => {
|
||||||
|
let t = 0;
|
||||||
|
for (const e of fresh) {
|
||||||
|
const at = t;
|
||||||
|
switch (e.t) {
|
||||||
|
case 'play': {
|
||||||
|
const from = e.p === me ? (myPlayRect ?? fxEl('nn-hand')) : seatEl(e.p);
|
||||||
|
if (e.p === me) myPlayRect = null;
|
||||||
|
flyGhost(from, fxEl('nn-dial'), { delay: at, ms: 380, label: faceName(e.face), className: 'nn-ghost' });
|
||||||
|
later(at + 300, () => {
|
||||||
|
sfx.cardPlay();
|
||||||
|
// (a direction flip sounds from the direction change below)
|
||||||
|
if (e.kind === 'hold' || e.choice === '방향 그대로') nnSfx.hold();
|
||||||
|
if (e.kind === 'to99') nnSfx.to99();
|
||||||
|
else if (e.total >= 90 && e.total > e.from) nnSfx.tense();
|
||||||
|
});
|
||||||
|
if (e.kind === 'to99') later(at + 300, () => showBanner('99!', 'red', `${who(e.p)} 바로 99`));
|
||||||
|
// Refill: the player takes one card from the pile (mine flies in from MyHand).
|
||||||
|
if (v.options.refill && e.p !== me) flyGhost(fxEl('nn-deck'), seatEl(e.p), { delay: at + 420, ms: 380 });
|
||||||
|
t += 160;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'noCard':
|
||||||
|
showBanner('낼 카드가 없어요!', 'red', who(e.p));
|
||||||
|
later(at, sfx.bad);
|
||||||
|
bump(seatEl(e.p), 'shake');
|
||||||
|
t += 200;
|
||||||
|
break;
|
||||||
|
case 'life':
|
||||||
|
later(at, nnSfx.heart);
|
||||||
|
bump(seatEl(e.p), 'shake');
|
||||||
|
t += 200;
|
||||||
|
break;
|
||||||
|
case 'out':
|
||||||
|
if (e.why === 'noCard') {
|
||||||
|
showBanner('탈락!', 'dark', who(e.p));
|
||||||
|
later(at + 120, sfx.bad);
|
||||||
|
}
|
||||||
|
t += 200;
|
||||||
|
break;
|
||||||
|
case 'round':
|
||||||
|
if (e.round > 1) {
|
||||||
|
dealAll(at + 400);
|
||||||
|
t += 900;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'reshuffle':
|
||||||
|
later(at, sfx.shuffle);
|
||||||
|
bump(fxEl('nn-deck'), 'shake');
|
||||||
|
break;
|
||||||
|
case 'timeout':
|
||||||
|
later(at, sfx.tick);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// The total jumps: the dial pops (shakes when it is close to 99).
|
||||||
|
useChange(v.total, (now, before) => {
|
||||||
|
if (now !== before) later(320, () => bump(fxEl('nn-dial'), now >= 90 ? 'shake' : 'pop'));
|
||||||
|
});
|
||||||
|
// Only a card flips it (a new round just resets it to clockwise, which the deal already covers).
|
||||||
|
const round = useRef(v.round);
|
||||||
|
useChange(v.direction, () => {
|
||||||
|
if (round.current !== v.round) return;
|
||||||
|
later(300, nnSfx.reverse);
|
||||||
|
bump(document.querySelector('.nn-dir b'));
|
||||||
|
});
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
round.current = v.round;
|
||||||
|
});
|
||||||
|
// Mounted right at the start of the game (nothing played yet): show the deal once.
|
||||||
|
const started = useRef(false);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (started.current) return;
|
||||||
|
started.current = true;
|
||||||
|
if (v.phase === 'playing' && v.round === 1 && !v.log.some((e) => e.t === 'play')) {
|
||||||
|
dealAll(0);
|
||||||
|
const deck = fxEl('nn-deck');
|
||||||
|
document.querySelectorAll('.nn-hand .nn-card').forEach((el, i) => flyFrom(el, deck, { delay: 280 + i * 70, rotate: 10 }));
|
||||||
|
}
|
||||||
|
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- side
|
// ---------------------------------------------------------------- side
|
||||||
|
|
||||||
function rulesLine(o: NNOptions): string {
|
function rulesLine(o: NNOptions): string {
|
||||||
@@ -686,7 +833,7 @@ function statusText(v: NinetyNineView, me: string | null, players: Record<string
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- options
|
// ---------------------------------------------------------------- options
|
||||||
|
|
||||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="segmented" role="group" aria-label={label}>
|
<div className="segmented" role="group" aria-label={label}>
|
||||||
{options.map(([k, l]) => (
|
{options.map(([k, l]) => (
|
||||||
@@ -735,7 +882,7 @@ function Options({ value: o, onChange }: OptionsProps<NNOptions>) {
|
|||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="한 턴 제한 시간">
|
<Field label="한 턴 제한 시간">
|
||||||
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||||
</Field>
|
</Field>
|
||||||
{kr && (
|
{kr && (
|
||||||
<button type="button" className="btn btn-secondary" onClick={() => set({ jokerRange: '0-99', handSize: 'auto' })}>
|
<button type="button" className="btn btn-secondary" onClick={() => set({ jokerRange: '0-99', handSize: 'auto' })}>
|
||||||
@@ -790,7 +937,7 @@ function optionsSummary(o: NNOptions): string {
|
|||||||
if (o.mode === 'kr-product' && o.startTotal === 'zero') parts.push('0부터 시작');
|
if (o.mode === 'kr-product' && o.startTotal === 'zero') parts.push('0부터 시작');
|
||||||
if (!o.refill) parts.push('보충 없음');
|
if (!o.refill) parts.push('보충 없음');
|
||||||
if (o.mode === 'kr-product' && o.jokerRange === '0-99') parts.push('조커 0~99');
|
if (o.mode === 'kr-product' && o.jokerRange === '0-99') parts.push('조커 0~99');
|
||||||
parts.push(`${o.turnSeconds}초`);
|
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
|
||||||
return parts.join(' · ');
|
return parts.join(' · ');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -872,7 +1019,7 @@ function Rules({ options }: { options?: NNOptions }) {
|
|||||||
</p>
|
</p>
|
||||||
<SpecialTable o={o} />
|
<SpecialTable o={o} />
|
||||||
<p className="small muted">
|
<p className="small muted">
|
||||||
시간 안에 내지 않으면 합계가 가장 작아지는 카드를 자동으로 내요. 어린이와 할 때는 조커 0~99를 추천해요. 목숨(하트)은 이 판에서만 쓰는 표시예요.
|
{o.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 내지 않으면'} 합계가 가장 작아지는 카드를 자동으로 내요. 어린이와 할 때는 조커 0~99를 추천해요. 목숨(하트)은 이 판에서만 쓰는 표시예요.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
/** 도둑잡기 화면 (docs/games/old-maid.md §9). Cards are the shared trump card SVGs. */
|
/** 도둑잡기 화면 (docs/games/old-maid.md §9). Cards are the shared trump card SVGs. */
|
||||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||||
import type { LogEntry, OldMaidOptions, OldMaidView } from '@bg/games/old-maid';
|
import type { LogEntry, OldMaidOptions, OldMaidView } from '@bg/games/old-maid';
|
||||||
import type { PublicUser } from '@bg/shared/lite';
|
import type { PublicUser } from '@bg/shared/lite';
|
||||||
import { Avatar } from '../../components/ui';
|
import { Avatar } from '../../components/ui';
|
||||||
import { TurnTimer } from '../../components/TurnTimer';
|
import { TurnTimer } from '../../components/TurnTimer';
|
||||||
import { PlayingCard, cardAria } from '../../components/cards/PlayingCard';
|
import { PlayingCard, cardAria } from '../../components/cards/PlayingCard';
|
||||||
import { haptic, sounds } from '../../lib/feedback';
|
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||||
import { toast } from '../../store/toast';
|
import { toast } from '../../store/toast';
|
||||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||||
|
import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useChange, useNewEntries } from '../card-fx';
|
||||||
import { helpNow } from './help';
|
import { helpNow } from './help';
|
||||||
import { quickStart } from './quick';
|
import { quickStart } from './quick';
|
||||||
|
|
||||||
@@ -15,6 +16,35 @@ import { quickStart } from './quick';
|
|||||||
const JOKER = 'X1';
|
const JOKER = 'X1';
|
||||||
const SHUFFLES_PER_TURN = 3;
|
const SHUFFLES_PER_TURN = 3;
|
||||||
|
|
||||||
|
/** 도둑잡기 sounds on top of the shared palette (synthesized, no files). */
|
||||||
|
const omSfx = {
|
||||||
|
/** Two cards snapped down together + a bright chime: a pair thrown away. */
|
||||||
|
pair: () => {
|
||||||
|
noise(60, 0.16, 0, 'bandpass', 1700, 0.9);
|
||||||
|
noise(60, 0.16, 90, 'bandpass', 1500, 0.9);
|
||||||
|
tone(988, 90, 'triangle', 0.1, 120);
|
||||||
|
tone(1319, 160, 'triangle', 0.09, 190);
|
||||||
|
},
|
||||||
|
/** Someone emptied their hand. */
|
||||||
|
out: () => [784, 988, 1175, 1568].forEach((f, i) => tone(f, 110, 'triangle', 0.08, i * 70)),
|
||||||
|
/** I just got the joker: a sly, sinking "uh-oh" (only on the screen of whoever got it). */
|
||||||
|
jokerGot: () => {
|
||||||
|
tone(466, 150, 'sawtooth', 0.04, 0, { slideTo: 415 });
|
||||||
|
tone(370, 260, 'sawtooth', 0.045, 150, { slideTo: 311 });
|
||||||
|
tone(185, 300, 'sine', 0.1, 150);
|
||||||
|
},
|
||||||
|
/** My joker was taken: a sneaky "hehe" (only on the screen of whoever gave it away). */
|
||||||
|
jokerGone: () => {
|
||||||
|
[1047, 1175, 1047, 1397].forEach((f, i) => tone(f, 70, 'square', 0.035, i * 85));
|
||||||
|
tone(1568, 200, 'triangle', 0.06, 340, { slideTo: 2093 });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Where I clicked the card I drew (its button is gone once the view arrives), so the new card flies in from there. */
|
||||||
|
let myDrawRect: DOMRect | null = null;
|
||||||
|
const handCardEl = (c: string) => document.querySelector(`.om-hand [data-card="${cssEsc(c)}"]`);
|
||||||
|
const pairKey = (p: [string, string]) => `${p[0]}-${p[1]}`;
|
||||||
|
|
||||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||||
const who = (players: Record<string, PublicUser>, id: string, me: string | null) => (id === me ? '나' : `${nick(players, id)}님`);
|
const who = (players: Record<string, PublicUser>, id: string, me: string | null) => (id === me ? '나' : `${nick(players, id)}님`);
|
||||||
@@ -122,7 +152,7 @@ button.om-back:hover:not(:disabled) { transform: translateY(-5px); }
|
|||||||
|
|
||||||
function Card({ card, className }: { card: string | null; className?: string }) {
|
function Card({ card, className }: { card: string | null; className?: string }) {
|
||||||
return (
|
return (
|
||||||
<span className={`om-card${className ? ` ${className}` : ''}`} aria-hidden>
|
<span className={`om-card${className ? ` ${className}` : ''}`} data-card={card ?? undefined} aria-hidden>
|
||||||
<span className="om-face">
|
<span className="om-face">
|
||||||
<PlayingCard card={card} size="lg" style={{ width: '100%', height: '100%', filter: 'none' }} />
|
<PlayingCard card={card} size="lg" style={{ width: '100%', height: '100%', filter: 'none' }} />
|
||||||
</span>
|
</span>
|
||||||
@@ -158,9 +188,9 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaid
|
|||||||
const u = userOf(players, id);
|
const u = userOf(players, id);
|
||||||
const st = v.status[id];
|
const st = v.status[id];
|
||||||
const thief = v.final?.thief === id;
|
const thief = v.final?.thief === id;
|
||||||
const cls = ['om-seat', v.turn === id ? 'turn' : '', v.target === id ? 'target' : '', st !== 'playing' && !thief ? 'done' : '', thief ? 'thief' : ''].filter(Boolean).join(' ');
|
const cls = ['om-seat', v.turn === id ? 'turn anim-glow' : '', v.target === id ? 'target' : '', st !== 'playing' && !thief ? 'done' : '', thief ? 'thief' : ''].filter(Boolean).join(' ');
|
||||||
return (
|
return (
|
||||||
<section className={cls} aria-label={seatLabel(v, id, me, players)}>
|
<section className={cls} data-fx-seat={id} aria-label={seatLabel(v, id, me, players)}>
|
||||||
{bubble && (
|
{bubble && (
|
||||||
<span className="om-bubble" aria-hidden>
|
<span className="om-bubble" aria-hidden>
|
||||||
{bubble}
|
{bubble}
|
||||||
@@ -204,13 +234,17 @@ function Fan({ v, me, players, act, pending, tapConfirm, shake }: { v: OldMaidVi
|
|||||||
useEffect(() => setSel(null), [v.turnNo, target, count, v.shuffles[target]]);
|
useEffect(() => setSel(null), [v.turnNo, target, count, v.shuffles[target]]);
|
||||||
const draw = (index: number) => {
|
const draw = (index: number) => {
|
||||||
if (pending) return;
|
if (pending) return;
|
||||||
|
myDrawRect = document.querySelectorAll('.om-fan button.om-back')[index]?.getBoundingClientRect() ?? null;
|
||||||
act({ type: 'draw', from: target, index });
|
act({ type: 'draw', from: target, index });
|
||||||
setSel(null);
|
setSel(null);
|
||||||
};
|
};
|
||||||
const tap = (i: number) => {
|
const tap = (i: number) => {
|
||||||
if (!mine) return;
|
if (!mine) return;
|
||||||
if (sel === i || !tapConfirm) draw(i);
|
if (sel === i || !tapConfirm) draw(i);
|
||||||
else setSel(i);
|
else {
|
||||||
|
setSel(i);
|
||||||
|
sfx.select();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||||
if (e.key === 'Escape') {
|
if (e.key === 'Escape') {
|
||||||
@@ -291,10 +325,10 @@ function Pile({ v }: { v: OldMaidView }) {
|
|||||||
const pairs = v.log.flatMap((e) => (e.t === 'draw' && e.pair ? [e.pair] : e.t === 'left' ? e.pairs : [])).slice(-6);
|
const pairs = v.log.flatMap((e) => (e.t === 'draw' && e.pair ? [e.pair] : e.t === 'left' ? e.pairs : [])).slice(-6);
|
||||||
const total = Object.values(v.pairCounts).reduce((a, b) => a + b, 0);
|
const total = Object.values(v.pairCounts).reduce((a, b) => a + b, 0);
|
||||||
return (
|
return (
|
||||||
<div className="om-pile" aria-label={`버린 짝 모두 ${total}쌍${pairs.length ? `, 최근: ${pairs.map((p) => `${cardName(p[0])}·${cardName(p[1])}`).join(', ')}` : ''}`} role="group">
|
<div className="om-pile" data-fx="om-pile" aria-label={`버린 짝 모두 ${total}쌍${pairs.length ? `, 최근: ${pairs.map((p) => `${cardName(p[0])}·${cardName(p[1])}`).join(', ')}` : ''}`} role="group">
|
||||||
<span>버린 짝 {total}쌍 / 26쌍</span>
|
<span>버린 짝 {total}쌍 / 26쌍</span>
|
||||||
{pairs.map((p, i) => (
|
{pairs.map((p, i) => (
|
||||||
<span key={i} className="pair" aria-hidden>
|
<span key={i} className="pair" data-pair={pairKey(p)} aria-hidden>
|
||||||
<Card card={p[0]} />
|
<Card card={p[0]} />
|
||||||
<Card card={p[1]} />
|
<Card card={p[1]} />
|
||||||
</span>
|
</span>
|
||||||
@@ -308,11 +342,11 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record<strin
|
|||||||
if (v.phase === 'finished') {
|
if (v.phase === 'finished') {
|
||||||
const f = v.final!;
|
const f = v.final!;
|
||||||
return (
|
return (
|
||||||
<div className="om-table" role="group" aria-label="테이블">
|
<div className="om-table" role="group" aria-label="테이블" data-fx="om-table">
|
||||||
<strong className="om-title">게임이 끝났어요</strong>
|
<strong className="om-title">게임이 끝났어요</strong>
|
||||||
{f.thief ? (
|
{f.thief ? (
|
||||||
<>
|
<>
|
||||||
<Card card={JOKER} />
|
<Card card={JOKER} className="om-thief-joker" />
|
||||||
<span style={{ textAlign: 'center', fontWeight: 800 }}>🃏 도둑: {who(players, f.thief, me)}</span>
|
<span style={{ textAlign: 'center', fontWeight: 800 }}>🃏 도둑: {who(players, f.thief, me)}</span>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
@@ -328,7 +362,7 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record<strin
|
|||||||
const drawer = v.turn!;
|
const drawer = v.turn!;
|
||||||
const target = v.target;
|
const target = v.target;
|
||||||
return (
|
return (
|
||||||
<div className="om-table" role="group" aria-label="테이블">
|
<div className="om-table" role="group" aria-label="테이블" data-fx="om-table">
|
||||||
<div className="om-title">
|
<div className="om-title">
|
||||||
<span>{who(players, drawer, me)}</span>
|
<span>{who(players, drawer, me)}</span>
|
||||||
<span className="arrow" aria-hidden>
|
<span className="arrow" aria-hidden>
|
||||||
@@ -355,9 +389,9 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record<strin
|
|||||||
function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v: OldMaidView; me: string; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) {
|
function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v: OldMaidView; me: string; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) {
|
||||||
const hand = v.myHand ?? [];
|
const hand = v.myHand ?? [];
|
||||||
const st = v.status[me];
|
const st = v.status[me];
|
||||||
const cls = ['om-me', v.turn === me ? 'turn' : '', v.target === me ? 'target' : ''].filter(Boolean).join(' ');
|
const cls = ['om-me', v.turn === me ? 'turn anim-glow' : '', v.target === me ? 'target' : ''].filter(Boolean).join(' ');
|
||||||
return (
|
return (
|
||||||
<section className={cls} aria-label="내 자리">
|
<section className={cls} data-fx-seat={me} aria-label="내 자리">
|
||||||
{bubble && (
|
{bubble && (
|
||||||
<span className="om-bubble" aria-hidden>
|
<span className="om-bubble" aria-hidden>
|
||||||
{bubble}
|
{bubble}
|
||||||
@@ -382,7 +416,7 @@ function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v:
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{hand.length > 0 ? (
|
{hand.length > 0 ? (
|
||||||
<div className={`om-hand${hand.length > 12 ? ' many' : ''}`} role="list" aria-label={`내 손패, 왼쪽부터: ${hand.map(cardAria).join(', ')}`}>
|
<div className={`om-hand${hand.length > 12 ? ' many' : ''}`} data-fx="om-hand" role="list" aria-label={`내 손패, 왼쪽부터: ${hand.map(cardAria).join(', ')}`}>
|
||||||
{hand.map((c) => (
|
{hand.map((c) => (
|
||||||
<span key={c} role="listitem" aria-label={cardAria(c)} style={{ display: 'contents' }}>
|
<span key={c} role="listitem" aria-label={cardAria(c)} style={{ display: 'contents' }}>
|
||||||
<Card card={c} className={[c === JOKER ? 'joker' : '', c === fresh ? 'fresh' : ''].filter(Boolean).join(' ')} />
|
<Card card={c} className={[c === JOKER ? 'joker' : '', c === fresh ? 'fresh' : ''].filter(Boolean).join(' ')} />
|
||||||
@@ -408,6 +442,8 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
|||||||
const [shake, setShake] = useState(false);
|
const [shake, setShake] = useState(false);
|
||||||
const [fresh, setFresh] = useState<string | null>(null);
|
const [fresh, setFresh] = useState<string | null>(null);
|
||||||
const prev = useRef({ logCount: v.logCount, hand: v.myHand ?? [], turn: v.turn });
|
const prev = useRef({ logCount: v.logCount, hand: v.myHand ?? [], turn: v.turn });
|
||||||
|
const [banner, showBanner] = useBanner();
|
||||||
|
useOldMaidFx(v, me, players, showBanner);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const p = prev.current;
|
const p = prev.current;
|
||||||
@@ -470,10 +506,119 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
|||||||
<p className="sr-only" aria-live="polite">
|
<p className="sr-only" aria-live="polite">
|
||||||
{announce}
|
{announce}
|
||||||
</p>
|
</p>
|
||||||
|
{banner}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sounds + motion for every change of the table (new public log entries), mine or anyone else's. Only uses what this
|
||||||
|
* viewer's view shows: the joker sounds play only for whoever saw the joker come or go in their own hand.
|
||||||
|
*/
|
||||||
|
function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||||
|
const amPlayer = !!me && v.order.includes(me);
|
||||||
|
const hand = v.myHand ?? [];
|
||||||
|
const prevHand = useRef(hand);
|
||||||
|
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
|
||||||
|
/** My seat is my own area; the hand inside it is a better spot for cards leaving / arriving. */
|
||||||
|
const spot = (p: string) => (p === me ? (fxEl('om-hand') ?? seatEl(p)) : seatEl(p));
|
||||||
|
const entries = v.log.map((e, i) => ({ e, n: v.logCount - v.log.length + i }));
|
||||||
|
useNewEntries(entries, (x) => x.n, (fresh) => {
|
||||||
|
let t = 0;
|
||||||
|
const ld = v.lastDraw;
|
||||||
|
const pile = (pairs: [string, string][], from: Element | null, delay: number) => {
|
||||||
|
for (const p of pairs) flyFrom(document.querySelector(`.om-pile [data-pair="${cssEsc(pairKey(p))}"]`), from, { delay, ms: 420, rotate: 14 });
|
||||||
|
};
|
||||||
|
for (const { e } of fresh) {
|
||||||
|
const at = t;
|
||||||
|
switch (e.t) {
|
||||||
|
case 'draw': {
|
||||||
|
const newMine = e.drawer === me && !e.pair && ld?.no === e.no && ld.drawer === me && ld.card ? handCardEl(ld.card) : null;
|
||||||
|
if (newMine) flyFrom(newMine, myDrawRect ?? seatEl(e.from), { ms: 420, rotate: 12, delay: at });
|
||||||
|
else flyGhost(e.drawer === me && myDrawRect ? myDrawRect : spot(e.from), spot(e.drawer), { delay: at, ms: 420 });
|
||||||
|
if (e.drawer === me) myDrawRect = null;
|
||||||
|
later(at, () => {
|
||||||
|
if (e.auto) sfx.tick();
|
||||||
|
sfx.draw();
|
||||||
|
});
|
||||||
|
if (e.pair) {
|
||||||
|
pile([e.pair], spot(e.drawer), at + 300);
|
||||||
|
later(at + 330, omSfx.pair);
|
||||||
|
later(at + 330, () => bump(document.querySelector('.om-last .cards'), 'pop'));
|
||||||
|
t += 420;
|
||||||
|
} else t += 160;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'out':
|
||||||
|
later(at, () => {
|
||||||
|
omSfx.out();
|
||||||
|
bump(seatEl(e.player), 'pop');
|
||||||
|
});
|
||||||
|
showBanner(`${e.place}등!`, 'green', e.player === me ? '손패를 다 털었어요' : `${nick(players, e.player)}님 다 털었어요`);
|
||||||
|
t += 150;
|
||||||
|
break;
|
||||||
|
case 'shuffle':
|
||||||
|
later(at, () => {
|
||||||
|
sfx.shuffle();
|
||||||
|
bump(e.player === me ? fxEl('om-hand') : seatEl(e.player), 'shake');
|
||||||
|
});
|
||||||
|
t += 120;
|
||||||
|
break;
|
||||||
|
case 'left': {
|
||||||
|
let n = 0;
|
||||||
|
for (const g of e.gave) {
|
||||||
|
flyGhost(seatEl(e.player), spot(g.to), { count: g.count, gap: 60, delay: at });
|
||||||
|
n += g.count;
|
||||||
|
}
|
||||||
|
if (n) later(at, () => sfx.deal(Math.min(n, 8), 60));
|
||||||
|
if (e.pairs.length) {
|
||||||
|
pile(e.pairs, seatEl(e.player), at + 350);
|
||||||
|
later(at + 380, omSfx.pair);
|
||||||
|
}
|
||||||
|
t += 400;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The joker came into / left my own hand: only this screen knows, so only this screen hears it.
|
||||||
|
if (amPlayer) {
|
||||||
|
const had = prevHand.current.includes(JOKER);
|
||||||
|
const has = hand.includes(JOKER);
|
||||||
|
if (!had && has) {
|
||||||
|
later(t + 150, () => {
|
||||||
|
omSfx.jokerGot();
|
||||||
|
bump(handCardEl(JOKER), 'shake');
|
||||||
|
});
|
||||||
|
} else if (had && !has && v.phase === 'playing') later(t + 150, omSfx.jokerGone);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
prevHand.current = hand;
|
||||||
|
});
|
||||||
|
// The end: the thief is unmasked (the win / lose sound itself comes from the room screen).
|
||||||
|
useChange(v.phase, (now) => {
|
||||||
|
const thief = v.final?.thief;
|
||||||
|
if (now !== 'finished' || !thief) return;
|
||||||
|
showBanner('🃏 도둑!', 'dark', thief === me ? '내가 조커를 들고 있었어요' : `${nick(players, thief)}님`);
|
||||||
|
setTimeout(() => {
|
||||||
|
bump(seatEl(thief), 'shake');
|
||||||
|
bump(fxEl('om-table')?.querySelector('.om-thief-joker'), 'pop');
|
||||||
|
}, 200);
|
||||||
|
});
|
||||||
|
const started = useRef(false);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (started.current) return;
|
||||||
|
started.current = true;
|
||||||
|
// Mounted right at the start (nobody has drawn or shuffled yet): show the deal once.
|
||||||
|
if (v.phase !== 'playing' || v.logCount !== 0 || v.turnNo !== 1) return;
|
||||||
|
const table = fxEl('om-table');
|
||||||
|
sfx.shuffle();
|
||||||
|
setTimeout(() => sfx.deal(8, 60), 300);
|
||||||
|
document.querySelectorAll('.om-hand .om-card').forEach((el, i) => flyFrom(el, table, { delay: 280 + i * 40, rotate: 10 }));
|
||||||
|
for (const p of v.order) if (p !== me) flyGhost(table, seatEl(p), { count: 3, gap: 90, delay: 280 });
|
||||||
|
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- side
|
// ---------------------------------------------------------------- side
|
||||||
|
|
||||||
function OldMaidSide({ view: v, me, players, deadline }: BoardProps<OldMaidView>) {
|
function OldMaidSide({ view: v, me, players, deadline }: BoardProps<OldMaidView>) {
|
||||||
@@ -558,7 +703,7 @@ function statusText(v: OldMaidView, me: string | null, players: Record<string, P
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- options
|
// ---------------------------------------------------------------- options
|
||||||
|
|
||||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="segmented" role="group" aria-label={label}>
|
<div className="segmented" role="group" aria-label={label}>
|
||||||
{options.map(([k, l]) => (
|
{options.map(([k, l]) => (
|
||||||
@@ -591,6 +736,7 @@ function Options({ value: o, onChange }: OptionsProps<OldMaidOptions>) {
|
|||||||
[20, '20초'],
|
[20, '20초'],
|
||||||
[30, '30초'],
|
[30, '30초'],
|
||||||
[60, '60초'],
|
[60, '60초'],
|
||||||
|
[null, '무제한'],
|
||||||
]}
|
]}
|
||||||
onChange={(turnSeconds) => onChange({ ...o, turnSeconds })}
|
onChange={(turnSeconds) => onChange({ ...o, turnSeconds })}
|
||||||
/>
|
/>
|
||||||
@@ -600,7 +746,7 @@ function Options({ value: o, onChange }: OptionsProps<OldMaidOptions>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function optionsSummary(o: OldMaidOptions): string {
|
function optionsSummary(o: OldMaidOptions): string {
|
||||||
return `트럼프 52장 + 조커 1장 · 제한 ${o.turnSeconds}초`;
|
return `트럼프 52장 + 조커 1장 · ${o.turnSeconds === null ? '시간 무제한' : `제한 ${o.turnSeconds}초`}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function Rules({ options }: { options?: OldMaidOptions }) {
|
function Rules({ options }: { options?: OldMaidOptions }) {
|
||||||
@@ -631,7 +777,10 @@ function Rules({ options }: { options?: OldMaidOptions }) {
|
|||||||
<strong>끝</strong>: 손패를 다 턴 사람은 빠지고, 먼저 턴 순서대로 1등, 2등…이에요. 짝이 다 버려지면 조커 한 장만 남고, 그걸 든 사람이 도둑이에요.
|
<strong>끝</strong>: 손패를 다 턴 사람은 빠지고, 먼저 턴 순서대로 1등, 2등…이에요. 짝이 다 버려지면 조커 한 장만 남고, 그걸 든 사람이 도둑이에요.
|
||||||
</p>
|
</p>
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
{options?.turnSeconds ?? 20}초 안에 고르지 않으면 무작위로 한 장을 뽑아요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 카드를 든 채 게임을 나가면 그 사람 카드는 섞어서 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고(짝이
|
{options?.turnSeconds === null
|
||||||
|
? '시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 무작위로 한 장을 대신 뽑아 주고, 그런 일이 세 번 연속이면 그 사람은 5초 안에 뽑아야 해요.'
|
||||||
|
: `${options?.turnSeconds ?? 20}초 안에 고르지 않으면 무작위로 한 장을 뽑아요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요.`}{' '}
|
||||||
|
카드를 든 채 게임을 나가면 그 사람 카드는 섞어서 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고(짝이
|
||||||
생기면 버려요), 나간 사람은 맨 아래 등수가 돼요. 둘만 남았을 때 한 사람이 나가면 도둑 없이 끝나요.
|
생기면 버려요), 나간 사람은 맨 아래 등수가 돼요. 둘만 남았을 때 한 사람이 나가면 도둑 없이 끝나요.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
/** 포커 화면 (docs/games/poker.md §9). Chips are room-only play points. */
|
/** 포커 화면 (docs/games/poker.md §9). Chips are room-only play points. */
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||||
import type { BetActionType, LegalBetView, PokerMode, PokerOptions, PokerView, SeatView, Side, ViewCard } from '@bg/games/poker';
|
import type { BetActionType, LegalBetView, LogEntry, PokerMode, PokerOptions, PokerView, SeatView, Side, ViewCard } from '@bg/games/poker';
|
||||||
import type { PublicUser } from '@bg/shared/lite';
|
import type { PublicUser } from '@bg/shared/lite';
|
||||||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||||
import { TurnTimer } from '../../components/TurnTimer';
|
import { TurnTimer } from '../../components/TurnTimer';
|
||||||
import { PlayingCard } from '../../components/cards/PlayingCard';
|
import { PlayingCard } from '../../components/cards/PlayingCard';
|
||||||
import { Chips, PlayChipNotice, formatChips } from '../../components/cards/Chips';
|
import { Chips, PlayChipNotice, formatChips } from '../../components/cards/Chips';
|
||||||
import { haptic, sounds } from '../../lib/feedback';
|
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||||
|
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useChange } from '../card-fx';
|
||||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||||
import { helpNow } from './help';
|
import { helpNow } from './help';
|
||||||
import { quickStart } from './quick';
|
import { quickStart } from './quick';
|
||||||
@@ -119,7 +120,7 @@ function SeatCards({ seat, v, me }: { seat: SeatView; v: PokerView; me: string |
|
|||||||
if (!cards.length) return null;
|
if (!cards.length) return null;
|
||||||
const best = new Set(sd?.best ?? []);
|
const best = new Set(sd?.best ?? []);
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexWrap: 'nowrap', justifyContent: 'center' }}>
|
<div style={{ display: 'flex', flexWrap: 'nowrap', justifyContent: 'center' }} data-fx="seat-cards">
|
||||||
{cards.map((x, i) => (
|
{cards.map((x, i) => (
|
||||||
<PlayingCard
|
<PlayingCard
|
||||||
key={x.key}
|
key={x.key}
|
||||||
@@ -148,8 +149,9 @@ function SeatBox({ seat, v, players, me, deadline, x, y }: { seat: SeatView; v:
|
|||||||
if (seat.boss) marks.push(['보스', '#fb923c', '보스(먼저 베팅)']);
|
if (seat.boss) marks.push(['보스', '#fb923c', '보스(먼저 베팅)']);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={`pk-seat${waiting ? ' turn' : ''}${seat.id === me ? ' me' : ''}${won ? ' win' : ''}${out ? ' out' : ''}`}
|
className={`pk-seat${waiting ? ' turn anim-glow' : ''}${seat.id === me ? ' me' : ''}${won ? ' win' : ''}${out ? ' out' : ''}`}
|
||||||
style={{ '--x': `${x}%`, '--y': `${y}%` } as React.CSSProperties}
|
style={{ '--x': `${x}%`, '--y': `${y}%` } as React.CSSProperties}
|
||||||
|
data-fx-seat={seat.id}
|
||||||
aria-label={`${u.nickname} ${formatChips(seat.stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`}
|
aria-label={`${u.nickname} ${formatChips(seat.stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`}
|
||||||
>
|
>
|
||||||
<div className="row" style={{ gap: 5, flexWrap: 'nowrap' }}>
|
<div className="row" style={{ gap: 5, flexWrap: 'nowrap' }}>
|
||||||
@@ -195,15 +197,15 @@ function CenterInfo({ v, players }: { v: PokerView; players: Record<string, Publ
|
|||||||
const limit = v.options.endCondition === 'hands' ? `/${v.options.handLimit}` : '';
|
const limit = v.options.endCondition === 'hands' ? `/${v.options.handLimit}` : '';
|
||||||
const penalty = v.penalties.reduce((a, p) => a + p.amount, 0);
|
const penalty = v.penalties.reduce((a, p) => a + p.amount, 0);
|
||||||
return (
|
return (
|
||||||
<div className="pk-center">
|
<div className="pk-center" data-fx="poker-center">
|
||||||
{v.streetName && <div className="pk-badge" style={{ background: '#fde047', color: '#422006', fontSize: '0.95rem', padding: '2px 12px' }}>{v.streetName}</div>}
|
{v.streetName && <div className="pk-badge" style={{ background: '#fde047', color: '#422006', fontSize: '0.95rem', padding: '2px 12px' }}>{v.streetName}</div>}
|
||||||
{isCommunity(v.mode) && (
|
{isCommunity(v.mode) && (
|
||||||
<div className="pk-board" aria-label="공용 카드">
|
<div className="pk-board" aria-label="공용 카드" data-fx="poker-board">
|
||||||
{Array.from({ length: 5 }, (_, i) => (v.board[i] ? <PlayingCard key={v.board[i]} card={v.board[i]!} size="md" /> : <span key={`e${i}`} className="pk-slot" aria-hidden />))}
|
{Array.from({ length: 5 }, (_, i) => (v.board[i] ? <PlayingCard key={v.board[i]} card={v.board[i]!} size="md" /> : <span key={`e${i}`} className="pk-slot" aria-hidden />))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div style={{ fontSize: '0.95rem', opacity: 0.9 }}>모인 칩</div>
|
<div style={{ fontSize: '0.95rem', opacity: 0.9 }}>모인 칩</div>
|
||||||
<div style={{ fontSize: '2.2rem', fontWeight: 900, fontVariantNumeric: 'tabular-nums' }} aria-live="polite">
|
<div style={{ fontSize: '2.2rem', fontWeight: 900, fontVariantNumeric: 'tabular-nums' }} aria-live="polite" data-fx="poker-pot">
|
||||||
{formatChips(v.pot)}
|
{formatChips(v.pot)}
|
||||||
</div>
|
</div>
|
||||||
{v.pots.length > 1 && (
|
{v.pots.length > 1 && (
|
||||||
@@ -239,6 +241,8 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
|||||||
const prevWaiting = useRef(false);
|
const prevWaiting = useRef(false);
|
||||||
const mine = isMyTurn(v, me);
|
const mine = isMyTurn(v, me);
|
||||||
const showKey = `${v.handNo}-${v.handPhase}`;
|
const showKey = `${v.handNo}-${v.handPhase}`;
|
||||||
|
const [banner, showBanner] = useBanner();
|
||||||
|
usePokerFx(v, me, players, showBanner);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (mine && !prevWaiting.current) {
|
if (mine && !prevWaiting.current) {
|
||||||
@@ -270,10 +274,259 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
|||||||
<p className="sr-only" aria-live="polite">
|
<p className="sr-only" aria-live="polite">
|
||||||
{announce}
|
{announce}
|
||||||
</p>
|
</p>
|
||||||
|
{banner}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- sounds + motion (2026-10-13)
|
||||||
|
|
||||||
|
/** 포커 sounds on top of the shared palette (synthesized, no files). */
|
||||||
|
const pokerSfx = {
|
||||||
|
/** 체크: two knuckle knocks on the felt. */
|
||||||
|
knock: (delay = 0) => {
|
||||||
|
for (const d of [0, 120]) {
|
||||||
|
tone(190, 60, 'sine', 0.22, delay + d, { slideTo: 120 });
|
||||||
|
noise(35, 0.1, delay + d, 'lowpass', 700);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/** 다이/폴드: cards slid away to the muck. */
|
||||||
|
fold: (delay = 0) => {
|
||||||
|
noise(220, 0.09, delay, 'bandpass', 800, 0.6);
|
||||||
|
tone(330, 160, 'triangle', 0.05, delay + 40, { slideTo: 200 });
|
||||||
|
},
|
||||||
|
/** 올인: a big push of chips with a low swell. */
|
||||||
|
allIn: (delay = 0) => {
|
||||||
|
for (let i = 0; i < 7; i++) sfx.chip(delay + i * 45);
|
||||||
|
tone(140, 360, 'sawtooth', 0.05, delay, { slideTo: 280 });
|
||||||
|
tone(70, 300, 'sine', 0.14, delay);
|
||||||
|
},
|
||||||
|
/** 하이·로우·스윙 선언 공개. */
|
||||||
|
declare: (delay = 0) => tone(660, 120, 'triangle', 0.1, delay, { slideTo: 990 }),
|
||||||
|
};
|
||||||
|
|
||||||
|
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
|
||||||
|
|
||||||
|
/** Card turned over in place (WAAPI so React's own style/transform stays). */
|
||||||
|
function flipIn(el: Element | null | undefined, delay = 0): void {
|
||||||
|
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||||
|
(el as HTMLElement).animate(
|
||||||
|
[
|
||||||
|
{ transform: 'perspective(600px) rotateY(90deg)' },
|
||||||
|
{ transform: 'perspective(600px) rotateY(-12deg)', offset: 0.6 },
|
||||||
|
{ transform: 'perspective(600px) rotateY(0deg)' },
|
||||||
|
],
|
||||||
|
{ duration: 420, delay, easing: 'ease', fill: 'backwards', composite: 'add' },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The card elements of a seat on the table (forehead, hole, choice, up — same order as SeatCards). */
|
||||||
|
const seatCardEls = (id: string): Element[] => [...(seatEl(id)?.querySelector('[data-fx="seat-cards"]')?.children ?? [])];
|
||||||
|
const myCardEl = (slot: string) => document.querySelector(`[data-fx="poker-mine"] [data-slot="${cssEsc(slot)}"]`);
|
||||||
|
const cardCount = (s: SeatView) => (s.forehead !== undefined ? 1 : 0) + s.hole.length + s.choiceCount + s.up.length;
|
||||||
|
/** My visible card slots (ids where I can see them) — a new id means a card just came to me. */
|
||||||
|
function mySlots(v: PokerView, me: string | null): string[] {
|
||||||
|
const seat = v.seats.find((s) => s.id === me);
|
||||||
|
if (!seat) return [];
|
||||||
|
const out: string[] = [];
|
||||||
|
seat.hole.forEach((c, i) => out.push(c ?? `h${i}`));
|
||||||
|
seat.up.forEach((c, i) => out.push(c ?? `u${i}`));
|
||||||
|
if (v.my.choice) out.push(...v.my.choice);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const sameEntry = (a: LogEntry, b: LogEntry) => a.hand === b.hand && a.by === b.by && a.msg === b.msg;
|
||||||
|
/** Entries appended to the (sliding, last-30) log since `prev`; null when the two don't line up (resync/jump). */
|
||||||
|
function newLogEntries(prev: readonly LogEntry[], next: readonly LogEntry[]): LogEntry[] | null {
|
||||||
|
for (let d = 0; d <= next.length; d++) {
|
||||||
|
const keep = next.length - d;
|
||||||
|
if (keep > prev.length) continue;
|
||||||
|
if (keep === 0) return prev.length === 0 ? [...next] : null;
|
||||||
|
let ok = true;
|
||||||
|
for (let i = 0; i < keep && ok; i++) ok = sameEntry(next[i]!, prev[prev.length - keep + i]!);
|
||||||
|
if (ok) return next.slice(keep);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const BET_RE = /^(삥|콜|따당|쿼터|하프|풀|레이즈|벳|올인) (\d+) 칩/;
|
||||||
|
const DRAW_RE = /(\d)장 바꿈|박스\((\d)장\)/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sounds + motion for every change of the table, mine or anyone else's (log entries and view diffs since the last
|
||||||
|
* view). Nothing on the first render (join, reload, replay jump).
|
||||||
|
*/
|
||||||
|
function usePokerFx(v: PokerView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||||
|
const prev = useRef<PokerView | null>(null);
|
||||||
|
const chipN = (amount: number) => Math.max(1, Math.min(6, Math.round(Math.log2(1 + amount / Math.max(1, v.baseUnit)))));
|
||||||
|
const center = () => fxEl('poker-center');
|
||||||
|
const pot = () => fxEl('poker-pot');
|
||||||
|
|
||||||
|
/** New hand (or the very first one on mount): antes/blinds to the pot, then cards from the middle to everyone. */
|
||||||
|
const deal = (p: PokerView | null) => {
|
||||||
|
sfx.shuffle();
|
||||||
|
const inHand = v.seats.filter((s) => s.inHand && s.status !== 'left');
|
||||||
|
inHand.forEach((s, i) => {
|
||||||
|
if (s.handBet > 0) flyGhost(seatEl(s.id), pot(), { kind: 'chip', count: Math.min(3, chipN(s.handBet)), delay: i * 50 });
|
||||||
|
});
|
||||||
|
if (v.pot > 0) later(150, () => sfx.chips(3));
|
||||||
|
const per = Math.max(0, ...inHand.map(cardCount));
|
||||||
|
later(320, () => sfx.deal(Math.min(8, per * Math.max(1, inHand.length)), 55));
|
||||||
|
inHand.forEach((s, i) => {
|
||||||
|
if (s.id !== me) flyGhost(center(), seatEl(s.id), { count: Math.min(4, cardCount(s)), gap: 90, delay: 320 + i * 60 });
|
||||||
|
});
|
||||||
|
const known = new Set(p ? mySlots(p, me) : []);
|
||||||
|
mySlots(v, me)
|
||||||
|
.filter((k) => !known.has(k))
|
||||||
|
.forEach((k, i) => flyFrom(myCardEl(k), center(), { delay: 320 + i * 80, rotate: 10 }));
|
||||||
|
if (v.seats.find((s) => s.id === me)?.forehead !== undefined) flyFrom(myCardEl('f'), center(), { delay: 320, rotate: -10 });
|
||||||
|
};
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const p = prev.current;
|
||||||
|
prev.current = v;
|
||||||
|
if (!p || p === v) return;
|
||||||
|
const newHand = v.handNo !== p.handNo && v.handNo > 0;
|
||||||
|
let t = 0;
|
||||||
|
if (newHand) {
|
||||||
|
deal(p);
|
||||||
|
t = 600;
|
||||||
|
} else if (v.handNo > 0) {
|
||||||
|
// Cards dealt during the hand (7포커 streets, 인디언 2nd card …) and community cards.
|
||||||
|
let dealt = 0;
|
||||||
|
v.seats.forEach((s) => {
|
||||||
|
const before = p.seats.find((x) => x.id === s.id);
|
||||||
|
const k = before ? cardCount(s) - cardCount(before) : 0;
|
||||||
|
if (k > 0 && s.id !== me) flyGhost(center(), seatEl(s.id), { count: Math.min(4, k), gap: 90, delay: dealt * 70 });
|
||||||
|
if (k > 0) dealt += k;
|
||||||
|
});
|
||||||
|
const known = new Set(mySlots(p, me));
|
||||||
|
const mine = mySlots(v, me).filter((k) => !known.has(k));
|
||||||
|
mine.forEach((k, i) => flyFrom(myCardEl(k), center(), { delay: i * 80, rotate: 10 }));
|
||||||
|
if (dealt > 0) sfx.deal(Math.min(8, dealt), 60);
|
||||||
|
const boardEl = fxEl('poker-board');
|
||||||
|
for (let i = p.board.length; i < v.board.length; i++) {
|
||||||
|
const at = (i - p.board.length) * 140;
|
||||||
|
flipIn(boardEl?.children[i], at);
|
||||||
|
later(at, sfx.cardFlip);
|
||||||
|
}
|
||||||
|
if (v.board.length > p.board.length) t = (v.board.length - p.board.length) * 140;
|
||||||
|
// Showdown: hidden cards are turned over seat by seat.
|
||||||
|
if (v.showdown && !p.showdown) {
|
||||||
|
let n = 0;
|
||||||
|
for (const e of v.showdown) {
|
||||||
|
const s = v.seats.find((x) => x.id === e.id);
|
||||||
|
if (!s || s.id === me) continue;
|
||||||
|
const els = seatCardEls(s.id);
|
||||||
|
const off = s.forehead !== undefined ? 1 : 0;
|
||||||
|
const at = t + n * 160;
|
||||||
|
for (let i = 0; i < s.hole.length; i++) flipIn(els[off + i], at + i * 40);
|
||||||
|
later(at, sfx.cardFlip);
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
t += n * 160 + 100;
|
||||||
|
}
|
||||||
|
// 인디언: my own forehead card is shown at the end of the hand.
|
||||||
|
const myNow = v.seats.find((s) => s.id === me);
|
||||||
|
const myBefore = p.seats.find((s) => s.id === me);
|
||||||
|
if (myNow?.forehead && myBefore && !myBefore.forehead) {
|
||||||
|
flipIn(myCardEl('f'), t);
|
||||||
|
later(t, sfx.cardFlip);
|
||||||
|
t += 160;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fresh = newLogEntries(p.log, v.log);
|
||||||
|
if (!fresh || fresh.length > 12) return;
|
||||||
|
for (const e of fresh) {
|
||||||
|
const at = t;
|
||||||
|
const by = e.by;
|
||||||
|
const msg = e.msg;
|
||||||
|
if (!by) {
|
||||||
|
if (msg.includes('오픈 카드를 공개')) {
|
||||||
|
v.seats.forEach((s, i) => {
|
||||||
|
if (!s.up.length) return;
|
||||||
|
const els = seatCardEls(s.id);
|
||||||
|
flipIn(els[els.length - 1], at + i * 70);
|
||||||
|
});
|
||||||
|
later(at, sfx.cardFlip);
|
||||||
|
later(at + 140, sfx.cardFlip);
|
||||||
|
t += 200;
|
||||||
|
} else if (msg.includes('섞')) {
|
||||||
|
later(at, sfx.shuffle);
|
||||||
|
} else if (msg.includes('기본 단위가')) {
|
||||||
|
later(at, sfx.good);
|
||||||
|
bump(pot());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const bet = BET_RE.exec(msg);
|
||||||
|
if (bet) {
|
||||||
|
const amount = Number(bet[2]);
|
||||||
|
const n = chipN(amount);
|
||||||
|
flyGhost(seatEl(by), pot(), { kind: 'chip', count: n, gap: 60, delay: at });
|
||||||
|
if (msg.includes('올인')) {
|
||||||
|
later(at, () => pokerSfx.allIn());
|
||||||
|
later(at, () => showBanner('올인!', 'red', by === me ? undefined : `${nick(players, by)}님`));
|
||||||
|
bump(seatEl(by), 'shake');
|
||||||
|
} else later(at, () => sfx.chips(Math.min(5, n + 1)));
|
||||||
|
t += 140;
|
||||||
|
} else if (msg === '체크') {
|
||||||
|
later(at, () => pokerSfx.knock());
|
||||||
|
t += 120;
|
||||||
|
} else if (msg === '다이' || msg === '폴드' || msg.includes('나가서 다이')) {
|
||||||
|
const s = v.seats.find((x) => x.id === by);
|
||||||
|
flyGhost(seatEl(by), center(), { count: Math.min(3, s ? Math.max(1, cardCount(s)) : 2), gap: 50, delay: at });
|
||||||
|
later(at, () => pokerSfx.fold());
|
||||||
|
t += 130;
|
||||||
|
} else if (DRAW_RE.test(msg)) {
|
||||||
|
const m = DRAW_RE.exec(msg)!;
|
||||||
|
const k = Number(m[1] ?? m[2]);
|
||||||
|
flyGhost(seatEl(by), center(), { count: k, gap: 60, delay: at });
|
||||||
|
if (by !== me) flyGhost(center(), seatEl(by), { count: k, gap: 70, delay: at + 300 });
|
||||||
|
later(at, () => sfx.cardDeal());
|
||||||
|
later(at + 300, () => sfx.draw(Math.min(4, k)));
|
||||||
|
t += 150;
|
||||||
|
} else if (msg.endsWith('패스')) {
|
||||||
|
later(at, () => pokerSfx.knock());
|
||||||
|
t += 120;
|
||||||
|
} else if (msg.startsWith('선언:')) {
|
||||||
|
later(at, () => pokerSfx.declare());
|
||||||
|
bump(seatEl(by));
|
||||||
|
t += 120;
|
||||||
|
} else if (msg.includes('벌칙')) {
|
||||||
|
flyGhost(seatEl(by), pot(), { kind: 'chip', count: 4, gap: 50, delay: at });
|
||||||
|
later(at, sfx.alarm);
|
||||||
|
bump(seatEl(by), 'shake');
|
||||||
|
t += 200;
|
||||||
|
} else if (msg.includes('가져갔어요')) {
|
||||||
|
flyGhost(pot(), seatEl(by), { kind: 'chip', count: 6, gap: 55, delay: at + 150 });
|
||||||
|
later(at + 300, sfx.collect);
|
||||||
|
later(at + 500, () => bump(seatEl(by)));
|
||||||
|
t += 250;
|
||||||
|
} else if (msg.includes('다시 받았어요')) {
|
||||||
|
flyGhost(center(), seatEl(by), { kind: 'coin', count: 5, gap: 60, delay: at });
|
||||||
|
later(at, sfx.coin);
|
||||||
|
t += 150;
|
||||||
|
} else if (msg.includes('자리 비움')) {
|
||||||
|
later(at, sfx.tick);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Pot amount pops when it grows (after the chips arrive).
|
||||||
|
useChange(v.pot, (now, before) => {
|
||||||
|
if (now > before) later(380, () => bump(pot()));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mounted right at the start of the game (nothing played yet): show the deal once.
|
||||||
|
const started = useRef(false);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (started.current) return;
|
||||||
|
started.current = true;
|
||||||
|
if (v.handNo === 1 && v.handPhase !== 'handEnd' && !v.log.some((e) => e.by !== null)) deal(null);
|
||||||
|
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
}
|
||||||
|
|
||||||
function resultLine(v: PokerView, players: Record<string, PublicUser>): string {
|
function resultLine(v: PokerView, players: Record<string, PublicUser>): string {
|
||||||
if (!v.awards) return '';
|
if (!v.awards) return '';
|
||||||
const won = new Map<string, number>();
|
const won = new Map<string, number>();
|
||||||
@@ -369,21 +622,21 @@ function MyCards({ v, seat }: { v: PokerView; seat: SeatView }) {
|
|||||||
const sd = v.showdown?.find((e) => e.id === seat.id);
|
const sd = v.showdown?.find((e) => e.id === seat.id);
|
||||||
const best = new Set(sd?.best ?? []);
|
const best = new Set(sd?.best ?? []);
|
||||||
return (
|
return (
|
||||||
<div className="pk-mine" aria-label="내 카드">
|
<div className="pk-mine" aria-label="내 카드" data-fx="poker-mine">
|
||||||
{seat.forehead !== undefined && (
|
{seat.forehead !== undefined && (
|
||||||
<div className="stack" style={{ gap: 2, alignItems: 'center' }}>
|
<div className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot="f">
|
||||||
<PlayingCard card={seat.forehead} size="lg" title={seat.forehead ? undefined : '내 이마 카드(나만 못 봐요)'} />
|
<PlayingCard card={seat.forehead} size="lg" title={seat.forehead ? undefined : '내 이마 카드(나만 못 봐요)'} />
|
||||||
<span className="small muted">이마</span>
|
<span className="small muted">이마</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{seat.hole.map((c, i) => (
|
{seat.hole.map((c, i) => (
|
||||||
<div key={`h${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }}>
|
<div key={`h${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot={c ?? `h${i}`}>
|
||||||
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
|
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
|
||||||
{(isSevenMode(v.mode) || v.mode === 'indian') && <span className="small muted">{v.mode === 'indian' ? '손' : '나만 봄'}</span>}
|
{(isSevenMode(v.mode) || v.mode === 'indian') && <span className="small muted">{v.mode === 'indian' ? '손' : '나만 봄'}</span>}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{seat.up.map((c, i) => (
|
{seat.up.map((c, i) => (
|
||||||
<div key={`u${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }}>
|
<div key={`u${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot={c ?? `u${i}`}>
|
||||||
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
|
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
|
||||||
<span className="small muted">공개</span>
|
<span className="small muted">공개</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -397,6 +650,7 @@ function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unkno
|
|||||||
const [discard, setDiscard] = useState<string | null>(null);
|
const [discard, setDiscard] = useState<string | null>(null);
|
||||||
const [open, setOpen] = useState<string | null>(null);
|
const [open, setOpen] = useState<string | null>(null);
|
||||||
const tap = (c: string) => {
|
const tap = (c: string) => {
|
||||||
|
sfx.select();
|
||||||
if (!discard) setDiscard(c);
|
if (!discard) setDiscard(c);
|
||||||
else if (c === discard) {
|
else if (c === discard) {
|
||||||
setDiscard(null);
|
setDiscard(null);
|
||||||
@@ -410,9 +664,9 @@ function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unkno
|
|||||||
<br />
|
<br />
|
||||||
<span className="small muted">버린 카드는 아무에게도 보이지 않아요. 남는 2장은 나만 봐요.</span>
|
<span className="small muted">버린 카드는 아무에게도 보이지 않아요. 남는 2장은 나만 봐요.</span>
|
||||||
</p>
|
</p>
|
||||||
<div className="pk-mine">
|
<div className="pk-mine" data-fx="poker-mine">
|
||||||
{cards.map((c) => (
|
{cards.map((c) => (
|
||||||
<span key={c} className={c === discard ? 'pk-x' : undefined}>
|
<span key={c} className={c === discard ? 'pk-x' : undefined} data-slot={c}>
|
||||||
<PlayingCard card={c} size="lg" selected={c === open} dimmed={c === discard} onClick={() => tap(c)} title={c === discard ? '버릴 카드(다시 누르면 취소)' : c === open ? '보여 줄 카드' : undefined} />
|
<PlayingCard card={c} size="lg" selected={c === open} dimmed={c === discard} onClick={() => tap(c)} title={c === discard ? '버릴 카드(다시 누르면 취소)' : c === open ? '보여 줄 카드' : undefined} />
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
@@ -457,7 +711,11 @@ function DrawPicker({ v, hole, act, pending }: { v: PokerView; hole: string[]; a
|
|||||||
</p>
|
</p>
|
||||||
<div className="pk-mine">
|
<div className="pk-mine">
|
||||||
{hole.map((c) => (
|
{hole.map((c) => (
|
||||||
<PlayingCard key={c} card={c} size="lg" selected={sel.includes(c)} onClick={() => setSel((s) => (s.includes(c) ? s.filter((x) => x !== c) : [...s, c]))} />
|
<PlayingCard key={c} card={c} size="lg" selected={sel.includes(c)} onClick={() => {
|
||||||
|
sfx.select();
|
||||||
|
setSel((s) => (s.includes(c) ? s.filter((x) => x !== c) : [...s, c]));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{tooMany && <p className="field-error" style={{ margin: 0, textAlign: 'center' }}>{limit}장까지만 바꿀 수 있어요.</p>}
|
{tooMany && <p className="field-error" style={{ margin: 0, textAlign: 'center' }}>{limit}장까지만 바꿀 수 있어요.</p>}
|
||||||
@@ -812,7 +1070,7 @@ function statusText(v: PokerView, me: string | null, players: Record<string, Pub
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- options
|
// ---------------------------------------------------------------- options
|
||||||
|
|
||||||
function Seg<T extends string | number>({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
|
function Seg<T extends string | number | null>({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
|
||||||
return (
|
return (
|
||||||
<div className="segmented">
|
<div className="segmented">
|
||||||
{options.map(([k, l]) => (
|
{options.map(([k, l]) => (
|
||||||
@@ -868,7 +1126,7 @@ function Options({ value: o, onChange }: OptionsProps<PokerOptions>) {
|
|||||||
{o.endCondition === 'hands' && <Seg value={o.handLimit} options={[[10, '10판'], [20, '20판'], [30, '30판'], [50, '50판']]} onChange={(handLimit) => set({ handLimit })} />}
|
{o.endCondition === 'hands' && <Seg value={o.handLimit} options={[[10, '10판'], [20, '20판'], [30, '30판'], [50, '50판']]} onChange={(handLimit) => set({ handLimit })} />}
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="행동 제한 시간">
|
<Field label="행동 제한 시간">
|
||||||
<Seg value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
<Seg value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||||
</Field>
|
</Field>
|
||||||
{o.mode === 'indian' && (
|
{o.mode === 'indian' && (
|
||||||
<Field label="인디언 포커">
|
<Field label="인디언 포커">
|
||||||
@@ -888,6 +1146,11 @@ function Options({ value: o, onChange }: OptionsProps<PokerOptions>) {
|
|||||||
<Seg value={o.rebuy} options={[['off', '안 함(탈락)'], ['limited', '횟수 제한'], ['unlimited', '무제한']]} onChange={(rebuy) => set({ rebuy })} />
|
<Seg value={o.rebuy} options={[['off', '안 함(탈락)'], ['limited', '횟수 제한'], ['unlimited', '무제한']]} onChange={(rebuy) => set({ rebuy })} />
|
||||||
{o.rebuy === 'limited' && <Seg value={o.rebuyLimit} options={[[1, '1번'], [2, '2번'], [3, '3번']]} onChange={(rebuyLimit) => set({ rebuyLimit })} />}
|
{o.rebuy === 'limited' && <Seg value={o.rebuyLimit} options={[[1, '1번'], [2, '2번'], [3, '3번']]} onChange={(rebuyLimit) => set({ rebuyLimit })} />}
|
||||||
</Field>
|
</Field>
|
||||||
|
{o.rebuy !== 'off' && (
|
||||||
|
<Field label="리바이 고르는 시간">
|
||||||
|
<Seg value={o.rebuySeconds} options={[[10, '10초'], [15, '15초'], [30, '30초'], [null, '무제한']]} onChange={(rebuySeconds) => set({ rebuySeconds })} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
<Field label="기본 칩 2배로 올리기">
|
<Field label="기본 칩 2배로 올리기">
|
||||||
<Seg value={o.blindUpEvery} options={[[0, '안 올림'], [5, '5판마다'], [10, '10판마다'], [15, '15판마다']]} onChange={(blindUpEvery) => set({ blindUpEvery })} />
|
<Seg value={o.blindUpEvery} options={[[0, '안 올림'], [5, '5판마다'], [10, '10판마다'], [15, '15판마다']]} onChange={(blindUpEvery) => set({ blindUpEvery })} />
|
||||||
</Field>
|
</Field>
|
||||||
@@ -933,7 +1196,7 @@ function Options({ value: o, onChange }: OptionsProps<PokerOptions>) {
|
|||||||
|
|
||||||
function optionsSummary(o: PokerOptions): string {
|
function optionsSummary(o: PokerOptions): string {
|
||||||
const bet = o.betting === 'auto' ? '' : o.betting === 'korean' ? '한국식' : o.betting === 'noLimit' ? '노리밋' : '팟리밋';
|
const bet = o.betting === 'auto' ? '' : o.betting === 'korean' ? '한국식' : o.betting === 'noLimit' ? '노리밋' : '팟리밋';
|
||||||
return [MODE_KO[o.mode], bet, `시작 ${o.startingChips.toLocaleString('ko-KR')}칩`, `기본 ${o.baseUnit}칩`, o.endCondition === 'hands' ? `${o.handLimit}판` : '최후의 1인', `${o.turnSeconds}초`]
|
return [MODE_KO[o.mode], bet, `시작 ${o.startingChips.toLocaleString('ko-KR')}칩`, `기본 ${o.baseUnit}칩`, o.endCondition === 'hands' ? `${o.handLimit}판` : '최후의 1인', o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(' · ');
|
.join(' · ');
|
||||||
}
|
}
|
||||||
@@ -974,7 +1237,11 @@ function Rules({ options }: { options?: PokerOptions }) {
|
|||||||
{o?.rebuy === 'off' ? '탈락하고 구경해요.' : '칩을 다시 받을지 고를 수 있어요. 다시 받은 만큼 최종 점수에서 빠져요.'}{' '}
|
{o?.rebuy === 'off' ? '탈락하고 구경해요.' : '칩을 다시 받을지 고를 수 있어요. 다시 받은 만큼 최종 점수에서 빠져요.'}{' '}
|
||||||
{o?.endCondition === 'lastStanding' ? '칩을 가진 사람이 한 명 남으면 끝나요.' : '정해진 판 수가 끝나면 (마지막 칩 − 시작 칩 × 다시 받은 횟수)로 순위를 정해요.'}
|
{o?.endCondition === 'lastStanding' ? '칩을 가진 사람이 한 명 남으면 끝나요.' : '정해진 판 수가 끝나면 (마지막 칩 − 시작 칩 × 다시 받은 횟수)로 순위를 정해요.'}
|
||||||
</p>
|
</p>
|
||||||
<p>시간 안에 고르지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 처리돼요. 두 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 짧아져요.</p>
|
{o?.turnSeconds === null ? (
|
||||||
|
<p>시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 자동 처리돼요. 이렇게 두 번 연속 넘어가면 '자리 비움'이 되고 짧은 제한 시간이 생겨요.</p>
|
||||||
|
) : (
|
||||||
|
<p>시간 안에 고르지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 처리돼요. 두 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 짧아져요.</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
/** 스플렌더 화면 (docs/games/splendor.md §9). Everything is drawn from the view; art is own CSS/SVG. */
|
/** 스플렌더 화면 (docs/games/splendor.md §9). Everything is drawn from the view; art is own CSS/SVG. */
|
||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||||
import type {
|
import type {
|
||||||
BuyOption,
|
BuyOption,
|
||||||
Color,
|
Color,
|
||||||
@@ -17,7 +17,8 @@ import type {
|
|||||||
import type { PublicUser } from '@bg/shared/lite';
|
import type { PublicUser } from '@bg/shared/lite';
|
||||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||||
import { TurnTimer } from '../../components/TurnTimer';
|
import { TurnTimer } from '../../components/TurnTimer';
|
||||||
import { haptic, sounds } from '../../lib/feedback';
|
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||||
|
import { bump, cssEsc, flyFrom, flyGhost, fxEl, useBanner, useChange, useNewEntries } from '../card-fx';
|
||||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||||
import { helpNow } from './help';
|
import { helpNow } from './help';
|
||||||
import { quickStart } from './quick';
|
import { quickStart } from './quick';
|
||||||
@@ -50,7 +51,6 @@ const iGa = (w: string) => {
|
|||||||
};
|
};
|
||||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
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;
|
|
||||||
const emptyTokens = (): Tokens => ({ W: 0, U: 0, G: 0, R: 0, K: 0, gold: 0 });
|
const emptyTokens = (): Tokens => ({ W: 0, U: 0, G: 0, R: 0, K: 0, gold: 0 });
|
||||||
const sum = (t: Partial<Record<TokenColor, number>>) => TOKEN_COLORS.reduce((a, c) => a + (t[c] ?? 0), 0);
|
const sum = (t: Partial<Record<TokenColor, number>>) => TOKEN_COLORS.reduce((a, c) => a + (t[c] ?? 0), 0);
|
||||||
const costText = (cost: Partial<Record<TokenColor, number>>) =>
|
const costText = (cost: Partial<Record<TokenColor, number>>) =>
|
||||||
@@ -93,8 +93,6 @@ const CSS = `
|
|||||||
.sp-card.can .sp-flag { background: var(--success); color: #fff; }
|
.sp-card.can .sp-flag { background: var(--success); color: #fff; }
|
||||||
.sp-card.gold .sp-flag { background: #a16207; color: #fff; }
|
.sp-card.gold .sp-flag { background: #a16207; color: #fff; }
|
||||||
.sp-card.empty { background: transparent; border: 2px dashed var(--border); box-shadow: none; cursor: default; display: flex; align-items: center; justify-content: center; color: var(--text-sub); font-size: .8rem; }
|
.sp-card.empty { background: transparent; border: 2px dashed var(--border); box-shadow: none; cursor: default; display: flex; align-items: center; justify-content: center; color: var(--text-sub); font-size: .8rem; }
|
||||||
.sp-card.fresh { animation: sp-in .45s ease-out; }
|
|
||||||
@keyframes sp-in { from { transform: scale(.7) rotate(-4deg); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
||||||
.sp-card.mini { --cw: 62px; --ch: 84px; border-width: 2px; }
|
.sp-card.mini { --cw: 62px; --ch: 84px; border-width: 2px; }
|
||||||
.sp-back { background: repeating-linear-gradient(45deg, #3b3157, #3b3157 6px, #4a3f6b 6px, #4a3f6b 12px); color: #fff; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; font-weight: 800; }
|
.sp-back { background: repeating-linear-gradient(45deg, #3b3157, #3b3157 6px, #4a3f6b 6px, #4a3f6b 12px); color: #fff; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; font-weight: 800; }
|
||||||
.sp-back.t1 { --bk: #2f5d46; background: repeating-linear-gradient(45deg, #2f5d46, #2f5d46 6px, #3a6d54 6px, #3a6d54 12px); }
|
.sp-back.t1 { --bk: #2f5d46; background: repeating-linear-gradient(45deg, #2f5d46, #2f5d46 6px, #3a6d54 6px, #3a6d54 12px); }
|
||||||
@@ -176,9 +174,19 @@ button.sp-noble { cursor: pointer; }
|
|||||||
.sp-mini-cols > span { display: flex; flex-direction: column; align-items: center; background: var(--surface-2); border-radius: 8px; padding: 2px 0; line-height: 1.25; }
|
.sp-mini-cols > span { display: flex; flex-direction: column; align-items: center; background: var(--surface-2); border-radius: 8px; padding: 2px 0; line-height: 1.25; }
|
||||||
.sp-badge { display: inline-block; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .74rem; line-height: 1.6; }
|
.sp-badge { display: inline-block; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .74rem; line-height: 1.6; }
|
||||||
|
|
||||||
.sp-crown { position: fixed; left: 50%; top: 38%; transform: translate(-50%, -50%); z-index: 30; pointer-events: none; font-size: 2.4rem; font-weight: 900;
|
|
||||||
color: #fde047; text-shadow: 0 3px 10px rgba(0,0,0,.6); animation: sp-pop .6s ease-out both; white-space: nowrap; }
|
/* flying copies (card-fx ghosts): gem tokens, cards, card backs, noble tiles */
|
||||||
@keyframes sp-pop { 0% { transform: translate(-50%, -50%) scale(.4); opacity: 0; } 60% { transform: translate(-50%, -50%) scale(1.12); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); } }
|
.fx-ghost.sp-fx-gem { border: 3px solid rgba(0,0,0,.35); background: var(--g); color: var(--gt); font-size: 9px; box-shadow: inset 0 0 0 3px rgba(255,255,255,.3), 0 2px 5px rgba(0,0,0,.4); }
|
||||||
|
.fx-ghost.sp-fx-W { --g: #f4f6f9; --gt: #1c1e21; border-color: #8a94a6; } .fx-ghost.sp-fx-U { --g: #2563eb; --gt: #fff; } .fx-ghost.sp-fx-G { --g: #15803d; --gt: #fff; }
|
||||||
|
.fx-ghost.sp-fx-R { --g: #c81e1e; --gt: #fff; } .fx-ghost.sp-fx-K { --g: #23262d; --gt: #fff; border-color: #6b7280; } .fx-ghost.sp-fx-gold { --g: #eab308; --gt: #2b1d00; border-color: #a16207; }
|
||||||
|
.fx-ghost.sp-fx-card { border: 2px solid #cbbf9f; border-radius: 6px; background: linear-gradient(160deg, var(--g, #e8edf3) 0%, #fffaf0 70%); color: #1c1e21;
|
||||||
|
box-shadow: 0 3px 8px rgba(0,0,0,.35); font: 900 15px/1 system-ui, sans-serif; padding: 3px 4px; }
|
||||||
|
.fx-ghost.sp-fx-b-W { --g: #e8edf3; } .fx-ghost.sp-fx-b-U { --g: #c9dcff; } .fx-ghost.sp-fx-b-G { --g: #c8efd3; } .fx-ghost.sp-fx-b-R { --g: #ffd0cc; } .fx-ghost.sp-fx-b-K { --g: #c9ccd3; }
|
||||||
|
.fx-ghost.sp-fx-t1 { background: repeating-linear-gradient(45deg, #2f5d46, #2f5d46 5px, #3a6d54 5px, #3a6d54 10px); border-color: rgba(0,0,0,.3); }
|
||||||
|
.fx-ghost.sp-fx-t2 { background: repeating-linear-gradient(45deg, #7a5a14, #7a5a14 5px, #8a6a20 5px, #8a6a20 10px); border-color: rgba(0,0,0,.3); }
|
||||||
|
.fx-ghost.sp-fx-t3 { background: repeating-linear-gradient(45deg, #34407a, #34407a 5px, #404d8c 5px, #404d8c 10px); border-color: rgba(0,0,0,.3); }
|
||||||
|
.fx-ghost.sp-fx-noble { border: 2px solid #b08d3c; border-radius: 8px; background: linear-gradient(135deg, #fff4d1, #f2d79a); box-shadow: 0 3px 10px rgba(0,0,0,.35);
|
||||||
|
display: flex; align-items: center; justify-content: center; font-size: 20px; }
|
||||||
.sp-help { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: .9rem; }
|
.sp-help { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: .9rem; }
|
||||||
.sp-help b { background: var(--primary-soft); border-radius: 8px; padding: 2px 8px; }
|
.sp-help b { background: var(--primary-soft); border-radius: 8px; padding: 2px 8px; }
|
||||||
|
|
||||||
@@ -210,7 +218,7 @@ button.sp-noble { cursor: pointer; }
|
|||||||
}
|
}
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.sp-card, .sp-token { transition: none; }
|
.sp-card, .sp-token { transition: none; }
|
||||||
.sp-card.fresh, .sp-token.shake, .sp-crown { animation: none; }
|
.sp-token.shake { animation: none; }
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -321,7 +329,7 @@ function CardBack({ tier, n, label }: { tier: Tier; n?: number; label?: string }
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function NobleTile({ noble, need, onClick, pick }: { noble: Noble; need?: number; onClick?: () => void; pick?: boolean }) {
|
function NobleTile({ noble, need, onClick, pick, fx }: { noble: Noble; need?: number; onClick?: () => void; pick?: boolean; fx?: boolean }) {
|
||||||
const name = NOBLE_NAME[noble.id] ?? `귀족 ${Number(noble.id.slice(1))}`;
|
const name = NOBLE_NAME[noble.id] ?? `귀족 ${Number(noble.id.slice(1))}`;
|
||||||
const req = COLORS.filter((c) => noble.req[c] > 0);
|
const req = COLORS.filter((c) => noble.req[c] > 0);
|
||||||
const label = `${name}, ${noble.points}점, 필요한 보너스 ${req.map((c) => `${SHORT[c]} ${noble.req[c]}`).join(' ')}${need !== undefined ? `, 남은 보너스 ${need}` : ''}`;
|
const label = `${name}, ${noble.points}점, 필요한 보너스 ${req.map((c) => `${SHORT[c]} ${noble.req[c]}`).join(' ')}${need !== undefined ? `, 남은 보너스 ${need}` : ''}`;
|
||||||
@@ -362,7 +370,7 @@ function NobleTile({ noble, need, onClick, pick }: { noble: Noble; need?: number
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<div className="sp-noble" role="img" aria-label={label}>
|
<div className="sp-noble" role="img" aria-label={label} data-fx-noble={fx ? noble.id : undefined}>
|
||||||
{body}
|
{body}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -384,7 +392,6 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
const [back, setBack] = useState<Tokens>(emptyTokens);
|
const [back, setBack] = useState<Tokens>(emptyTokens);
|
||||||
const [msg, setMsg] = useState<{ text: string; bad: boolean } | null>(null);
|
const [msg, setMsg] = useState<{ text: string; bad: boolean } | null>(null);
|
||||||
const [shake, setShake] = useState<{ c: TokenColor; n: number } | null>(null);
|
const [shake, setShake] = useState<{ c: TokenColor; n: number } | null>(null);
|
||||||
const [crown, setCrown] = useState<string | null>(null);
|
|
||||||
const [announce, setAnnounce] = useState('');
|
const [announce, setAnnounce] = useState('');
|
||||||
const [openOpp, setOpenOpp] = useState<string | null>(null);
|
const [openOpp, setOpenOpp] = useState<string | null>(null);
|
||||||
const [askPass, setAskPass] = useState(false);
|
const [askPass, setAskPass] = useState(false);
|
||||||
@@ -397,8 +404,8 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
});
|
});
|
||||||
const prevTurn = useRef(v.turnSeq);
|
const prevTurn = useRef(v.turnSeq);
|
||||||
const prevLog = useRef(v.log.at(-1)?.n ?? 0);
|
const prevLog = useRef(v.log.at(-1)?.n ?? 0);
|
||||||
const prevBoard = useRef<Record<string, string | null>>({});
|
const [banner, showBanner] = useBanner();
|
||||||
const [fresh, setFresh] = useState<Set<string>>(new Set());
|
useSplendorFx(v, me, players, showBanner);
|
||||||
|
|
||||||
// Reset local choices whenever the turn or phase moves on.
|
// Reset local choices whenever the turn or phase moves on.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -419,45 +426,16 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
}
|
}
|
||||||
}, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
}, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
// New log lines → screen reader text, sounds, noble crown.
|
// New log lines → screen reader text (sounds and motion: useSplendorFx).
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const last = prevLog.current;
|
const last = prevLog.current;
|
||||||
const news = v.log.filter((e) => e.n > last);
|
const news = v.log.filter((e) => e.n > last);
|
||||||
prevLog.current = v.log.at(-1)?.n ?? last;
|
prevLog.current = v.log.at(-1)?.n ?? last;
|
||||||
if (!news.length || last === 0) return;
|
if (!news.length || last === 0) return;
|
||||||
setAnnounce(news.map((e) => logText(e, players, me)).join(' '));
|
setAnnounce(news.map((e) => logText(e, players, me)).join(' '));
|
||||||
if (news.some((e) => e.k === 'buy' || e.k === 'take')) sounds.stone();
|
if (news.some((e) => e.k === 'noble')) haptic([60, 40, 60]);
|
||||||
const noble = news.find((e) => e.k === 'noble');
|
|
||||||
if (noble && noble.k === 'noble') {
|
|
||||||
setCrown(`👑 ${noble.p === me ? '나에게' : `${nick(players, noble.p)}님에게`} ${NOBLE_NAME[noble.nobleId] ?? '귀족'} 방문!`);
|
|
||||||
haptic([60, 40, 60]);
|
|
||||||
}
|
|
||||||
}, [v.log]); // eslint-disable-line react-hooks/exhaustive-deps
|
}, [v.log]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!crown) return;
|
|
||||||
const t = setTimeout(() => setCrown(null), reducedMotion() ? 2200 : 1500);
|
|
||||||
return () => clearTimeout(t);
|
|
||||||
}, [crown]);
|
|
||||||
|
|
||||||
// Newly revealed board cards get a short entrance animation.
|
|
||||||
useEffect(() => {
|
|
||||||
const now: Record<string, string | null> = {};
|
|
||||||
const changed = new Set<string>();
|
|
||||||
for (const t of TIERS_DOWN)
|
|
||||||
v.board[t].forEach((c, i) => {
|
|
||||||
const k = `b${t}-${i}`;
|
|
||||||
now[k] = c?.id ?? null;
|
|
||||||
if (prevBoard.current[k] !== undefined && prevBoard.current[k] !== now[k] && c) changed.add(k);
|
|
||||||
});
|
|
||||||
prevBoard.current = now;
|
|
||||||
if (changed.size) {
|
|
||||||
setFresh(changed);
|
|
||||||
const t = setTimeout(() => setFresh(new Set()), 600);
|
|
||||||
return () => clearTimeout(t);
|
|
||||||
}
|
|
||||||
}, [v.board]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!shake) return;
|
if (!shake) return;
|
||||||
const t = setTimeout(() => setShake(null), 400);
|
const t = setTimeout(() => setShake(null), 400);
|
||||||
@@ -480,18 +458,26 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
setManual(null);
|
setManual(null);
|
||||||
if (v.supply[c] <= 0) return refuse(c, '남아 있지 않은 색이에요.');
|
if (v.supply[c] <= 0) return refuse(c, '남아 있지 않은 색이에요.');
|
||||||
setMsg(null);
|
setMsg(null);
|
||||||
if (same) return setPicks([c]);
|
if (same) {
|
||||||
|
sfx.select();
|
||||||
|
return setPicks([c]);
|
||||||
|
}
|
||||||
if (picks.length === 1 && picks[0] === c) {
|
if (picks.length === 1 && picks[0] === c) {
|
||||||
if (my?.takeSame.includes(c)) {
|
if (my?.takeSame.includes(c)) {
|
||||||
|
sfx.select();
|
||||||
setPicks([c, c]);
|
setPicks([c, c]);
|
||||||
setMsg({ text: `${NAME[c]} 2개를 가져와요.`, bad: false });
|
setMsg({ text: `${NAME[c]} 2개를 가져와요.`, bad: false });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return refuse(c, '같은 색 2개는 4개 이상 남은 색에서만 가져올 수 있어요.');
|
return refuse(c, '같은 색 2개는 4개 이상 남은 색에서만 가져올 수 있어요.');
|
||||||
}
|
}
|
||||||
if (picks.includes(c)) return setPicks(picks.filter((x) => x !== c));
|
if (picks.includes(c)) {
|
||||||
|
sfx.click();
|
||||||
|
return setPicks(picks.filter((x) => x !== c));
|
||||||
|
}
|
||||||
if (takeCount === 0) return refuse(c, '서로 다른 색 보석은 가져올 수 없어요.');
|
if (takeCount === 0) return refuse(c, '서로 다른 색 보석은 가져올 수 없어요.');
|
||||||
if (picks.length >= takeCount) return refuse(c, `서로 다른 색은 ${takeCount}개까지 골라요.`);
|
if (picks.length >= takeCount) return refuse(c, `서로 다른 색은 ${takeCount}개까지 골라요.`);
|
||||||
|
sfx.select();
|
||||||
setPicks([...picks, c]);
|
setPicks([...picks, c]);
|
||||||
};
|
};
|
||||||
const take = () => {
|
const take = () => {
|
||||||
@@ -517,7 +503,10 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
setPicks([]);
|
setPicks([]);
|
||||||
setManual(null);
|
setManual(null);
|
||||||
setMsg(null);
|
setMsg(null);
|
||||||
setSel(sel && selKey(sel) === selKey(s) ? null : s);
|
const off = !!sel && selKey(sel) === selKey(s);
|
||||||
|
if (off) sfx.click();
|
||||||
|
else sfx.select();
|
||||||
|
setSel(off ? null : s);
|
||||||
};
|
};
|
||||||
const payment = manual ?? buyOpt?.payment ?? null;
|
const payment = manual ?? buyOpt?.payment ?? null;
|
||||||
const deckSel = sel?.kind === 'deck' ? sel : null;
|
const deckSel = sel?.kind === 'deck' ? sel : null;
|
||||||
@@ -558,6 +547,8 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
if (next[c] >= mine.tokens[c]) return;
|
if (next[c] >= mine.tokens[c]) return;
|
||||||
next[c]++;
|
next[c]++;
|
||||||
} else if (next[c] > 0) next[c]--;
|
} else if (next[c] > 0) next[c]--;
|
||||||
|
else return;
|
||||||
|
sfx.select();
|
||||||
setMsg(null);
|
setMsg(null);
|
||||||
setBack(next);
|
setBack(next);
|
||||||
};
|
};
|
||||||
@@ -565,7 +556,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
const cardClass = (key: string, extra = '') => {
|
const cardClass = (key: string, extra = '') => {
|
||||||
const opt = my?.buy[key];
|
const opt = my?.buy[key];
|
||||||
const hl = hints && opt && !mine?.conceded ? (opt.gold > 0 ? ' gold' : ' can') : '';
|
const hl = hints && opt && !mine?.conceded ? (opt.gold > 0 ? ' gold' : ' can') : '';
|
||||||
return `sp-card${hl}${sel && selKey(sel) === key ? ' sel' : ''}${fresh.has(key) ? ' fresh' : ''}${extra}`;
|
return `sp-card${hl}${sel && selKey(sel) === key ? ' sel' : ''}${extra}`;
|
||||||
};
|
};
|
||||||
const cardAria = (card: DevCard, key: string) => {
|
const cardAria = (card: DevCard, key: string) => {
|
||||||
const opt = my?.buy[key];
|
const opt = my?.buy[key];
|
||||||
@@ -595,7 +586,8 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
key={p}
|
key={p}
|
||||||
type="button"
|
type="button"
|
||||||
role="listitem"
|
role="listitem"
|
||||||
className={`sp-chip${v.current === p ? ' turn' : ''}`}
|
className={`sp-chip${v.current === p ? ` turn${v.phase !== 'finished' ? ' anim-glow' : ''}` : ''}`}
|
||||||
|
data-fx-seat={p}
|
||||||
aria-expanded={openOpp === p}
|
aria-expanded={openOpp === p}
|
||||||
aria-label={`${nick(players, p)} ${pv.points}점, 보석 ${pv.tokenCount}개, 카드 ${pv.cards.length}장, 예약 ${pv.reservedCount}장${v.current === p ? ', 지금 차례' : ''}. 누르면 자세히 보여요`}
|
aria-label={`${nick(players, p)} ${pv.points}점, 보석 ${pv.tokenCount}개, 카드 ${pv.cards.length}장, 예약 ${pv.reservedCount}장${v.current === p ? ', 지금 차례' : ''}. 누르면 자세히 보여요`}
|
||||||
onClick={() => setOpenOpp(openOpp === p ? null : p)}
|
onClick={() => setOpenOpp(openOpp === p ? null : p)}
|
||||||
@@ -640,9 +632,9 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="sp-table">
|
<div className="sp-table">
|
||||||
<section className="sp-nobles" aria-label={`귀족 ${v.nobles.length}명`}>
|
<section className="sp-nobles" aria-label={`귀족 ${v.nobles.length}명`} data-fx="sp-nobles">
|
||||||
{v.nobles.map((n) => (
|
{v.nobles.map((n) => (
|
||||||
<NobleTile key={n.id} noble={n} need={hints && my ? my.nobleNeed[n.id] : undefined} />
|
<NobleTile key={n.id} noble={n} need={hints && my ? my.nobleNeed[n.id] : undefined} fx />
|
||||||
))}
|
))}
|
||||||
{v.nobles.length === 0 && <span className="small muted">남은 귀족이 없어요</span>}
|
{v.nobles.length === 0 && <span className="small muted">남은 귀족이 없어요</span>}
|
||||||
</section>
|
</section>
|
||||||
@@ -652,6 +644,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={`sp-deck sp-back t${t}${sel?.kind === 'deck' && sel.tier === t ? ' sel' : ''}`}
|
className={`sp-deck sp-back t${t}${sel?.kind === 'deck' && sel.tier === t ? ' sel' : ''}`}
|
||||||
|
data-fx={`sp-deck-${t}`}
|
||||||
disabled={v.deckCounts[t] === 0}
|
disabled={v.deckCounts[t] === 0}
|
||||||
aria-label={`${t}단계 더미 ${v.deckCounts[t]}장${my?.reserveDecks.includes(t) ? '. 누르면 안 보고 예약할 수 있어요' : ''}`}
|
aria-label={`${t}단계 더미 ${v.deckCounts[t]}장${my?.reserveDecks.includes(t) ? '. 누르면 안 보고 예약할 수 있어요' : ''}`}
|
||||||
onClick={() => choose({ kind: 'deck', tier: t })}
|
onClick={() => choose({ kind: 'deck', tier: t })}
|
||||||
@@ -662,12 +655,12 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
const key = `b${t}-${i}`;
|
const key = `b${t}-${i}`;
|
||||||
if (!card)
|
if (!card)
|
||||||
return (
|
return (
|
||||||
<div key={key} className="sp-card empty" aria-label="빈 칸">
|
<div key={key} className="sp-card empty" aria-label="빈 칸" data-fx={`sp-slot-${key}`}>
|
||||||
빈 칸
|
빈 칸
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<button key={key} type="button" className={cardClass(key)} data-b={card.bonus} aria-label={cardAria(card, key)} aria-pressed={sel ? selKey(sel) === key : false} onClick={() => choose({ kind: 'board', tier: t, slot: i })}>
|
<button key={key} type="button" className={cardClass(key)} data-b={card.bonus} data-fx={`sp-slot-${key}`} aria-label={cardAria(card, key)} aria-pressed={sel ? selKey(sel) === key : false} onClick={() => choose({ kind: 'board', tier: t, slot: i })}>
|
||||||
<CardFace card={card} />
|
<CardFace card={card} />
|
||||||
{flag(key)}
|
{flag(key)}
|
||||||
</button>
|
</button>
|
||||||
@@ -687,6 +680,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
type="button"
|
type="button"
|
||||||
className={`sp-token${n === 0 ? ' out' : ''}${count ? ' picked' : ''}${count === 2 ? ' picked2' : ''}${shake?.c === c ? ' shake' : ''}`}
|
className={`sp-token${n === 0 ? ' out' : ''}${count ? ' picked' : ''}${count === 2 ? ' picked2' : ''}${shake?.c === c ? ' shake' : ''}`}
|
||||||
data-c={c}
|
data-c={c}
|
||||||
|
data-fx={`sp-bank-${c}`}
|
||||||
disabled={isGold || !acting}
|
disabled={isGold || !acting}
|
||||||
aria-pressed={!isGold && acting ? count > 0 : undefined}
|
aria-pressed={!isGold && acting ? count > 0 : undefined}
|
||||||
aria-label={`${NAME[c]} ${n}개 남음${count ? `, ${count}개 고름` : ''}${isGold ? ' (예약하면 1개 받아요)' : ''}`}
|
aria-label={`${NAME[c]} ${n}개 남음${count ? `, ${count}개 고름` : ''}${isGold ? ' (예약하면 1개 받아요)' : ''}`}
|
||||||
@@ -876,16 +870,224 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
|||||||
<p className="sr-only" aria-live="polite">
|
<p className="sr-only" aria-live="polite">
|
||||||
{announce}
|
{announce}
|
||||||
</p>
|
</p>
|
||||||
{crown && (
|
{banner}
|
||||||
<div className="sp-crown" aria-hidden>
|
|
||||||
{crown}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{askPass && <ConfirmSheet title="차례를 넘길까요?" body="지금은 할 수 있는 행동이 없어요." confirm="넘기기" onConfirm={() => act({ type: 'PASS' })} onClose={() => setAskPass(false)} />}
|
{askPass && <ConfirmSheet title="차례를 넘길까요?" body="지금은 할 수 있는 행동이 없어요." confirm="넘기기" onConfirm={() => act({ type: 'PASS' })} onClose={() => setAskPass(false)} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- motion + sound
|
||||||
|
|
||||||
|
/** 스플렌더 sounds on top of the shared palette (synthesized; `delay` in ms). */
|
||||||
|
const spSfx = {
|
||||||
|
/** Glassy gem "clink" (bank → player). */
|
||||||
|
clink: (delay = 0, i = 0) => {
|
||||||
|
const f = 2350 + (i % 4) * 170;
|
||||||
|
tone(f, 70, 'triangle', 0.08, delay);
|
||||||
|
tone(f * 1.5, 130, 'sine', 0.035, delay + 6);
|
||||||
|
},
|
||||||
|
/** Gems put back on the bank: lower and softer. */
|
||||||
|
clack: (delay = 0, i = 0) => {
|
||||||
|
tone(1500 + (i % 3) * 110, 60, 'triangle', 0.06, delay);
|
||||||
|
noise(25, 0.05, delay, 'highpass', 5000);
|
||||||
|
},
|
||||||
|
/** A development card bought: card slide + "ka-ching". */
|
||||||
|
buy: (delay = 0) => {
|
||||||
|
noise(80, 0.15, delay, 'bandpass', 1600, 0.9);
|
||||||
|
tone(784, 90, 'triangle', 0.1, delay + 40);
|
||||||
|
tone(1175, 170, 'triangle', 0.1, delay + 120);
|
||||||
|
},
|
||||||
|
/** A card put aside (reserved). */
|
||||||
|
reserve: (delay = 0) => {
|
||||||
|
noise(90, 0.14, delay, 'bandpass', 2200, 0.8);
|
||||||
|
tone(660, 90, 'triangle', 0.08, delay + 50);
|
||||||
|
tone(520, 120, 'triangle', 0.06, delay + 120);
|
||||||
|
},
|
||||||
|
gold: (delay = 0) => {
|
||||||
|
tone(1318, 70, 'square', 0.05, delay);
|
||||||
|
tone(1976, 160, 'square', 0.05, delay + 70);
|
||||||
|
},
|
||||||
|
/** New market card turned face up. */
|
||||||
|
flip: (delay = 0) => {
|
||||||
|
noise(60, 0.12, delay, 'highpass', 2500);
|
||||||
|
tone(1400, 40, 'triangle', 0.05, delay + 10);
|
||||||
|
},
|
||||||
|
/** Noble visit: a little bell chime. */
|
||||||
|
noble: (delay = 0) => [1047, 1319, 1568, 2093].forEach((f, i) => tone(f, 420, 'sine', 0.1, delay + i * 110)),
|
||||||
|
};
|
||||||
|
|
||||||
|
const isShown = (el: Element | null | undefined): el is Element => {
|
||||||
|
if (!el) return false;
|
||||||
|
const r = el.getBoundingClientRect();
|
||||||
|
return r.width > 0 || r.height > 0;
|
||||||
|
};
|
||||||
|
/** A player's place on screen: my area, else the first visible seat (side list on wide screens, chip on narrow ones). */
|
||||||
|
function seatOf(p: string, me: string | null): Element | null {
|
||||||
|
if (p === me) {
|
||||||
|
const m = fxEl('sp-mine');
|
||||||
|
if (isShown(m)) return m;
|
||||||
|
}
|
||||||
|
for (const el of document.querySelectorAll(`[data-fx-seat="${cssEsc(p)}"]`)) if (isShown(el)) return el;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
/** Where a player's colour `c` is shown (my column, an opponent's mini column), else their seat. */
|
||||||
|
function gemSpot(p: string, c: TokenColor, me: string | null): Element | null {
|
||||||
|
if (p === me) {
|
||||||
|
const el = fxEl(`sp-tok-${c}`);
|
||||||
|
if (isShown(el)) return el;
|
||||||
|
}
|
||||||
|
const seat = seatOf(p, me);
|
||||||
|
const col = seat?.querySelector(`[data-fx-tok="${c}"]`);
|
||||||
|
return isShown(col) ? col : seat;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sounds + motion for every change of the table, mine or anyone else's (new log entries and board diffs since the
|
||||||
|
* previous view). Nothing on the first render (join, reload, replay jump).
|
||||||
|
*/
|
||||||
|
function useSplendorFx(v: SplendorView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||||
|
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
|
||||||
|
// Board of the previous view (slot key → card id) to know where a bought / reserved card was.
|
||||||
|
const prevBoard = useRef<Record<string, string | null> | null>(null);
|
||||||
|
// Nobles and my reserved cards disappear from the DOM with the new view: remember their rects while the DOM still
|
||||||
|
// shows the previous view (render phase, only when the log moved).
|
||||||
|
const snap = useRef<{ n: number; rects: Map<string, DOMRect> }>({ n: -1, rects: new Map() });
|
||||||
|
const tail = v.log.at(-1)?.n ?? 0;
|
||||||
|
if (snap.current.n !== tail && typeof document !== 'undefined') {
|
||||||
|
const rects = new Map<string, DOMRect>();
|
||||||
|
document.querySelectorAll('[data-fx-noble], [data-fx="sp-reserved"] [data-fx-res]').forEach((el) => {
|
||||||
|
const id = el.getAttribute('data-fx-noble');
|
||||||
|
rects.set(id ? `n:${id}` : `r:${el.getAttribute('data-fx-res')}`, el.getBoundingClientRect());
|
||||||
|
});
|
||||||
|
snap.current = { n: tail, rects };
|
||||||
|
}
|
||||||
|
|
||||||
|
const gemsFly = (tokens: Partial<Tokens>, p: string, toBank: boolean, at: number) => {
|
||||||
|
let i = 0;
|
||||||
|
for (const c of TOKEN_COLORS) {
|
||||||
|
const n = Math.min(tokens[c] ?? 0, 6);
|
||||||
|
if (!n) continue;
|
||||||
|
const bank = fxEl(`sp-bank-${c}`);
|
||||||
|
const spot = gemSpot(p, c, me);
|
||||||
|
flyGhost(toBank ? spot : bank, toBank ? bank : spot, { kind: 'chip', count: n, gap: 80, delay: at + i * 80, ms: 420, label: SHORT[c], className: `sp-fx-gem sp-fx-${c}` });
|
||||||
|
for (let k = 0; k < n; k++) (toBank ? spSfx.clack : spSfx.clink)(at + (i + k) * 80 + (toBank ? 380 : 120), i + k);
|
||||||
|
i += n;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
};
|
||||||
|
|
||||||
|
useNewEntries(
|
||||||
|
v.log,
|
||||||
|
(e) => e.n,
|
||||||
|
(fresh) => {
|
||||||
|
const board = prevBoard.current ?? {};
|
||||||
|
const slotOf = (id: string) => Object.keys(board).find((k) => board[k] === id);
|
||||||
|
let t = 0;
|
||||||
|
for (const e of fresh) {
|
||||||
|
const at = t;
|
||||||
|
switch (e.k) {
|
||||||
|
case 'take':
|
||||||
|
gemsFly(e.tokens, e.p, false, at);
|
||||||
|
t += 200;
|
||||||
|
break;
|
||||||
|
case 'discard':
|
||||||
|
gemsFly(e.tokens, e.p, true, at);
|
||||||
|
t += 200;
|
||||||
|
break;
|
||||||
|
case 'buy': {
|
||||||
|
const bonus = e.cardId[1] as Color;
|
||||||
|
const to = gemSpot(e.p, bonus, me);
|
||||||
|
const slot = e.fromReserve ? undefined : slotOf(e.cardId);
|
||||||
|
const from: Element | DOMRect | null = slot
|
||||||
|
? fxEl(`sp-slot-${slot}`)
|
||||||
|
: e.fromReserve && e.p === me
|
||||||
|
? (snap.current.rects.get(`r:${e.cardId}`) ?? fxEl('sp-reserved'))
|
||||||
|
: seatOf(e.p, me);
|
||||||
|
flyGhost(from, to, { kind: 'card', delay: at, ms: 520, className: `sp-fx-card sp-fx-b-${bonus}` });
|
||||||
|
later(at + 480, () => bump(to));
|
||||||
|
spSfx.buy(at);
|
||||||
|
const paid = sum(e.paid);
|
||||||
|
if (paid) gemsFly(e.paid, e.p, true, at + 120);
|
||||||
|
t += 300 + Math.min(paid, 6) * 40;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'reserve': {
|
||||||
|
const slot = e.cardId ? slotOf(e.cardId) : undefined;
|
||||||
|
const from = slot ? fxEl(`sp-slot-${slot}`) : fxEl(`sp-deck-${e.tier}`);
|
||||||
|
const look = e.cardId ? `sp-fx-b-${e.cardId[1]}` : `sp-fx-t${e.tier}`;
|
||||||
|
const mineEls = e.p === me ? document.querySelectorAll('[data-fx="sp-reserved"] [data-fx-res]') : null;
|
||||||
|
const newCard = mineEls?.length ? mineEls[mineEls.length - 1] : null;
|
||||||
|
if (newCard && isShown(newCard)) flyFrom(newCard, from, { delay: at, ms: 460, rotate: -8 });
|
||||||
|
else flyGhost(from, e.p === me ? fxEl('sp-reserved') : seatOf(e.p, me), { kind: 'card', delay: at, ms: 500, className: `sp-fx-card ${look}` });
|
||||||
|
spSfx.reserve(at);
|
||||||
|
if (e.gold) {
|
||||||
|
flyGhost(fxEl('sp-bank-gold'), gemSpot(e.p, 'gold', me), { kind: 'chip', delay: at + 180, ms: 420, label: SHORT.gold, className: 'sp-fx-gem sp-fx-gold' });
|
||||||
|
spSfx.gold(at + 520);
|
||||||
|
}
|
||||||
|
t += 300;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'noble': {
|
||||||
|
const from = snap.current.rects.get(`n:${e.nobleId}`) ?? fxEl('sp-nobles');
|
||||||
|
const at2 = at + 150;
|
||||||
|
flyGhost(from, seatOf(e.p, me), { kind: 'card', delay: at2, ms: 560, label: '👑', className: 'sp-fx-noble' });
|
||||||
|
later(at2, () => showBanner('👑 귀족 방문!', 'gold', `${NOBLE_NAME[e.nobleId] ?? '귀족'} → ${e.p === me ? '나' : `${nick(players, e.p)}님`} (+3점)`));
|
||||||
|
spSfx.noble(at2);
|
||||||
|
later(at2 + 560, () => bump(seatOf(e.p, me)));
|
||||||
|
t += 700;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'end':
|
||||||
|
// The game may already be over (last turn of the round): the finish banner below covers it.
|
||||||
|
if (v.phase !== 'finished')
|
||||||
|
later(at, () => {
|
||||||
|
showBanner('🏁 마지막 라운드!', 'blue', `${e.p === me ? '내가' : `${nick(players, e.p)}님이`} ${e.points}점에 도달했어요`);
|
||||||
|
sfx.fanfare();
|
||||||
|
});
|
||||||
|
t += 900;
|
||||||
|
break;
|
||||||
|
case 'pass':
|
||||||
|
later(at, sfx.whoosh);
|
||||||
|
break;
|
||||||
|
case 'concede':
|
||||||
|
later(at, sfx.bad);
|
||||||
|
bump(seatOf(e.p, me), 'shake');
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Market refill: the new card deals in from its deck and turns face up.
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const now: Record<string, string | null> = {};
|
||||||
|
for (const t of TIERS_DOWN) v.board[t].forEach((c, i) => (now[`b${t}-${i}`] = c?.id ?? null));
|
||||||
|
const before = prevBoard.current;
|
||||||
|
prevBoard.current = now;
|
||||||
|
if (!before) return;
|
||||||
|
let n = 0;
|
||||||
|
for (const t of TIERS_DOWN)
|
||||||
|
v.board[t].forEach((c, i) => {
|
||||||
|
const k = `b${t}-${i}`;
|
||||||
|
if (!c || before[k] === c.id || before[k] === undefined) return;
|
||||||
|
const delay = 260 + n * 120;
|
||||||
|
flyFrom(fxEl(`sp-slot-${k}`), fxEl(`sp-deck-${t}`), { delay, ms: 420, rotate: 8, scale: 0.7 });
|
||||||
|
spSfx.flip(delay + 380);
|
||||||
|
n++;
|
||||||
|
});
|
||||||
|
}, [v.board]);
|
||||||
|
|
||||||
|
// Game over (results and win/lose sounds come from the room page; this is the on-board moment).
|
||||||
|
useChange(v.phase, (now) => {
|
||||||
|
if (now !== 'finished' || !v.result) return;
|
||||||
|
const w = v.result.winners;
|
||||||
|
const sub = w.length ? (w.includes(me ?? '') && w.length === 1 ? '내가 이겼어요!' : `${w.map((p) => nick(players, p)).join(', ')}님 승리`) : undefined;
|
||||||
|
later(700, () => showBanner('게임 끝', 'gold', sub));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function MyArea({
|
function MyArea({
|
||||||
v,
|
v,
|
||||||
pv,
|
pv,
|
||||||
@@ -907,7 +1109,7 @@ function MyArea({
|
|||||||
}) {
|
}) {
|
||||||
const turn = v.current === me;
|
const turn = v.current === me;
|
||||||
return (
|
return (
|
||||||
<section className="sp-mine" aria-label="내 자리" style={{ border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}>
|
<section className={`sp-mine${turn && v.phase !== 'finished' ? ' anim-glow' : ''}`} aria-label="내 자리" data-fx="sp-mine" style={{ border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}>
|
||||||
<div className="sp-mine-head">
|
<div className="sp-mine-head">
|
||||||
<strong>
|
<strong>
|
||||||
나 · <span style={{ fontSize: '1.2rem' }}>{pv.points}점</span>
|
나 · <span style={{ fontSize: '1.2rem' }}>{pv.points}점</span>
|
||||||
@@ -919,7 +1121,7 @@ function MyArea({
|
|||||||
</div>
|
</div>
|
||||||
<div className="sp-cols" role="list" aria-label="색별 보너스와 보석">
|
<div className="sp-cols" role="list" aria-label="색별 보너스와 보석">
|
||||||
{TOKEN_COLORS.map((c) => (
|
{TOKEN_COLORS.map((c) => (
|
||||||
<div key={c} className="sp-col" role="listitem" aria-label={c === 'gold' ? `황금 ${pv.tokens.gold}개` : `${NAME[c]}: 보너스 ${pv.bonuses[c as Color]}, 보석 ${pv.tokens[c]}개`}>
|
<div key={c} className="sp-col" data-fx={`sp-tok-${c}`} role="listitem" aria-label={c === 'gold' ? `황금 ${pv.tokens.gold}개` : `${NAME[c]}: 보너스 ${pv.bonuses[c as Color]}, 보석 ${pv.tokens[c]}개`}>
|
||||||
<Gem c={c} size={20} />
|
<Gem c={c} size={20} />
|
||||||
<span className="bn" aria-hidden>
|
<span className="bn" aria-hidden>
|
||||||
{c === 'gold' ? '황금' : `할인 ${pv.bonuses[c as Color]}`}
|
{c === 'gold' ? '황금' : `할인 ${pv.bonuses[c as Color]}`}
|
||||||
@@ -930,14 +1132,14 @@ function MyArea({
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="sp-reserved" role="group" aria-label={`내 예약 카드 ${pv.reservedCount}장`}>
|
<div className="sp-reserved" role="group" aria-label={`내 예약 카드 ${pv.reservedCount}장`} data-fx="sp-reserved">
|
||||||
<span className="small muted">예약 {pv.reservedCount}/3</span>
|
<span className="small muted">예약 {pv.reservedCount}/3</span>
|
||||||
{pv.reserved.map((r, i) => {
|
{pv.reserved.map((r, i) => {
|
||||||
if (r.hidden) return null;
|
if (r.hidden) return null;
|
||||||
const card = r as Extract<ReservedView, { hidden: false }>;
|
const card = r as Extract<ReservedView, { hidden: false }>;
|
||||||
const key = `r${i}`;
|
const key = `r${i}`;
|
||||||
return (
|
return (
|
||||||
<button key={key} type="button" className={cardClass(key, ' mini')} data-b={card.bonus} aria-label={`예약 카드: ${cardAria(card, key)}${card.blind ? ' (더미에서 안 보고 예약)' : ''}`} aria-pressed={sel ? selKey(sel) === key : false} onClick={() => onPick(i)}>
|
<button key={key} type="button" className={cardClass(key, ' mini')} data-b={card.bonus} data-fx-res={card.id} aria-label={`예약 카드: ${cardAria(card, key)}${card.blind ? ' (더미에서 안 보고 예약)' : ''}`} aria-pressed={sel ? selKey(sel) === key : false} onClick={() => onPick(i)}>
|
||||||
<CardFace card={card} />
|
<CardFace card={card} />
|
||||||
{flag(key)}
|
{flag(key)}
|
||||||
</button>
|
</button>
|
||||||
@@ -954,7 +1156,7 @@ function PlayerDetail({ pv, name }: { pv: SplendorPlayerView; name: string }) {
|
|||||||
<div className="stack" style={{ gap: 6 }}>
|
<div className="stack" style={{ gap: 6 }}>
|
||||||
<div className="sp-mini-cols" role="list" aria-label={`${name}의 보너스와 보석`}>
|
<div className="sp-mini-cols" role="list" aria-label={`${name}의 보너스와 보석`}>
|
||||||
{TOKEN_COLORS.map((c) => (
|
{TOKEN_COLORS.map((c) => (
|
||||||
<span key={c} role="listitem" aria-label={c === 'gold' ? `황금 ${pv.tokens.gold}개` : `${NAME[c]} 보너스 ${pv.bonuses[c as Color]}, 보석 ${pv.tokens[c]}개`}>
|
<span key={c} role="listitem" data-fx-tok={c} aria-label={c === 'gold' ? `황금 ${pv.tokens.gold}개` : `${NAME[c]} 보너스 ${pv.bonuses[c as Color]}, 보석 ${pv.tokens[c]}개`}>
|
||||||
<Gem c={c} size={15} />
|
<Gem c={c} size={15} />
|
||||||
<span aria-hidden>{c === 'gold' ? '-' : `+${pv.bonuses[c as Color]}`}</span>
|
<span aria-hidden>{c === 'gold' ? '-' : `+${pv.bonuses[c as Color]}`}</span>
|
||||||
<strong aria-hidden>{pv.tokens[c]}</strong>
|
<strong aria-hidden>{pv.tokens[c]}</strong>
|
||||||
@@ -1029,7 +1231,7 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps<Splend
|
|||||||
const pv = v.players[p]!;
|
const pv = v.players[p]!;
|
||||||
const turn = v.current === p;
|
const turn = v.current === p;
|
||||||
return (
|
return (
|
||||||
<div key={p} className={`sp-player${turn ? ' turn' : ''}${pv.conceded ? ' gone' : ''}`}>
|
<div key={p} className={`sp-player${turn ? ` turn${v.phase !== 'finished' ? ' anim-glow' : ''}` : ''}${pv.conceded ? ' gone' : ''}`} data-fx-seat={p}>
|
||||||
<div className="row" style={{ gap: 8, flexWrap: 'nowrap' }}>
|
<div className="row" style={{ gap: 8, flexWrap: 'nowrap' }}>
|
||||||
<span className="muted small" style={{ width: 14 }} title={i === 0 ? '선 플레이어' : undefined}>
|
<span className="muted small" style={{ width: 14 }} title={i === 0 ? '선 플레이어' : undefined}>
|
||||||
{i === 0 ? '선' : i + 1}
|
{i === 0 ? '선' : i + 1}
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ import type { CardFace, Color, LogEntry, SeatView, UnoCard, UnoOptions, UnoView
|
|||||||
import type { PublicUser } from '@bg/shared/lite';
|
import type { PublicUser } from '@bg/shared/lite';
|
||||||
import { Avatar, Sheet } from '../../components/ui';
|
import { Avatar, Sheet } from '../../components/ui';
|
||||||
import { TurnTimer } from '../../components/TurnTimer';
|
import { TurnTimer } from '../../components/TurnTimer';
|
||||||
import { haptic, sounds } from '../../lib/feedback';
|
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
|
||||||
|
import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useChange, useNewEntries } from '../card-fx';
|
||||||
import { useSeatRows } from '../../lib/seat-rows';
|
import { useSeatRows } from '../../lib/seat-rows';
|
||||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||||
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, patternName } from '../one-card/ColorCard';
|
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, patternName } from '../one-card/ColorCard';
|
||||||
@@ -36,6 +37,30 @@ function cardName(c: CardFace): string {
|
|||||||
|
|
||||||
const isWild = (c: CardFace) => c.kind === 'wild' || c.kind === 'wild4';
|
const isWild = (c: CardFace) => c.kind === 'wild' || c.kind === 'wild4';
|
||||||
|
|
||||||
|
/** 우노 sounds on top of the shared palette (synthesized, no files). */
|
||||||
|
const unoSfx = {
|
||||||
|
skip: () => {
|
||||||
|
tone(520, 80, 'square', 0.05);
|
||||||
|
tone(330, 140, 'square', 0.05, 80);
|
||||||
|
},
|
||||||
|
reverse: () => {
|
||||||
|
tone(420, 220, 'triangle', 0.1, 0, { slideTo: 900 });
|
||||||
|
tone(900, 220, 'triangle', 0.08, 160, { slideTo: 420 });
|
||||||
|
},
|
||||||
|
wild: () => [523, 659, 784, 1046].forEach((f, i) => tone(f, 90, 'triangle', 0.08, i * 55)),
|
||||||
|
/** Heavy "+2 / +4" thump. */
|
||||||
|
plus: () => {
|
||||||
|
tone(170, 180, 'sawtooth', 0.07, 0, { slideTo: 80 });
|
||||||
|
tone(110, 220, 'sine', 0.16);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Where my last played card was (its button is gone once the view arrives), so the pile card flies from there. */
|
||||||
|
let myPlayRect: DOMRect | null = null;
|
||||||
|
const rememberPlay = (id: string) => {
|
||||||
|
myPlayRect = document.querySelector(`.un-card[data-id="${cssEsc(id)}"]`)?.getBoundingClientRect() ?? null;
|
||||||
|
};
|
||||||
|
|
||||||
function sortHand(hand: UnoCard[], by: 'color' | 'number'): UnoCard[] {
|
function sortHand(hand: UnoCard[], by: 'color' | 'number'): UnoCard[] {
|
||||||
const col = (c: UnoCard) => ('color' in c ? COLORS.indexOf(c.color) : 9);
|
const col = (c: UnoCard) => ('color' in c ? COLORS.indexOf(c.color) : 9);
|
||||||
const num = (c: UnoCard) => (c.kind === 'num' ? c.value : c.kind === 'skip' ? 10 : c.kind === 'reverse' ? 11 : c.kind === 'draw2' ? 12 : c.kind === 'wild' ? 20 : 21);
|
const num = (c: UnoCard) => (c.kind === 'num' ? c.value : c.kind === 'skip' ? 10 : c.kind === 'reverse' ? 11 : c.kind === 'draw2' ? 12 : c.kind === 'wild' ? 20 : 21);
|
||||||
@@ -77,7 +102,6 @@ const CSS = `
|
|||||||
.un-discard { position: relative; width: calc(var(--pw) * 1.12); height: calc(var(--pw) * 1.12 * 1.4); border-radius: 12px; }
|
.un-discard { position: relative; width: calc(var(--pw) * 1.12); height: calc(var(--pw) * 1.12 * 1.4); border-radius: 12px; }
|
||||||
.un-discard::before { content: ''; position: absolute; inset: -9px; border-radius: 18px; border: 5px solid var(--cc, transparent); box-shadow: 0 0 18px var(--cc, transparent); transition: border-color .3s, box-shadow .3s; }
|
.un-discard::before { content: ''; position: absolute; inset: -9px; border-radius: 18px; border: 5px solid var(--cc, transparent); box-shadow: 0 0 18px var(--cc, transparent); transition: border-color .3s, box-shadow .3s; }
|
||||||
.un-discard > .un-face { position: absolute; inset: 0; }
|
.un-discard > .un-face { position: absolute; inset: 0; }
|
||||||
.un-discard > .un-face.top { animation: un-fly .28s ease-out; }
|
|
||||||
.un-discard[data-drop='true'] { outline: 3px dashed #fde047; outline-offset: 12px; }
|
.un-discard[data-drop='true'] { outline: 3px dashed #fde047; outline-offset: 12px; }
|
||||||
.un-info { display: flex; flex-direction: column; gap: 8px; align-items: flex-start; min-width: 0; text-shadow: 0 1px 2px rgba(0,0,0,.5); }
|
.un-info { display: flex; flex-direction: column; gap: 8px; align-items: flex-start; min-width: 0; text-shadow: 0 1px 2px rgba(0,0,0,.5); }
|
||||||
.un-info .row { gap: 6px; }
|
.un-info .row { gap: 6px; }
|
||||||
@@ -123,7 +147,6 @@ const CSS = `
|
|||||||
.un-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 240px; overflow: auto; }
|
.un-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 240px; overflow: auto; }
|
||||||
.un-rules td, .un-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); }
|
.un-rules td, .un-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); }
|
||||||
.un-rules .un-face { width: 34px; height: 48px; }
|
.un-rules .un-face { width: 34px; height: 48px; }
|
||||||
@keyframes un-fly { from { transform: translate(-40px, 30px) scale(.8); opacity: .3; } to { transform: none; opacity: 1; } }
|
|
||||||
@keyframes un-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
@keyframes un-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
||||||
@keyframes un-shake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-8deg); } 75% { transform: rotate(8deg); } }
|
@keyframes un-shake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-8deg); } 75% { transform: rotate(8deg); } }
|
||||||
@media (min-width: 720px) {
|
@media (min-width: 720px) {
|
||||||
@@ -163,7 +186,7 @@ function seatLabel(s: SeatView, players: Record<string, PublicUser>, me: string
|
|||||||
function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; next: boolean }) {
|
function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; next: boolean }) {
|
||||||
const u = userOf(players, s.id);
|
const u = userOf(players, s.id);
|
||||||
return (
|
return (
|
||||||
<li className={`un-seat${s.isTurn ? ' turn' : next ? ' next' : ''}${s.left ? ' gone' : ''}`} aria-label={seatLabel(s, players, me, v)}>
|
<li className={`un-seat${s.isTurn ? ' turn anim-glow' : next ? ' next' : ''}${s.left ? ' gone' : ''}`} data-fx-seat={s.id} aria-label={seatLabel(s, players, me, v)}>
|
||||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||||
<Avatar user={u} size={24} />
|
<Avatar user={u} size={24} />
|
||||||
<span className="nm">{u.nickname}</span>
|
<span className="nm">{u.nickname}</span>
|
||||||
@@ -199,7 +222,7 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: UnoView; pl
|
|||||||
const next = nextOf(v, v.current);
|
const next = nextOf(v, v.current);
|
||||||
return (
|
return (
|
||||||
<div className="un-table" role="region" aria-label="카드 판" style={{ '--pw': pw } as CSSProperties}>
|
<div className="un-table" role="region" aria-label="카드 판" style={{ '--pw': pw } as CSSProperties}>
|
||||||
<button type="button" className="un-pile" data-can={canDraw} disabled={!canDraw} onClick={onDraw} aria-label={`카드 더미 ${v.drawPileCount}장${canDraw ? `. 눌러서 ${drawText}` : ''}`}>
|
<button type="button" className="un-pile" data-fx="uno-deck" data-can={canDraw} disabled={!canDraw} onClick={onDraw} aria-label={`카드 더미 ${v.drawPileCount}장${canDraw ? `. 눌러서 ${drawText}` : ''}`}>
|
||||||
<Face card={null} />
|
<Face card={null} />
|
||||||
<span className="cnt" aria-hidden>
|
<span className="cnt" aria-hidden>
|
||||||
{v.drawPileCount}
|
{v.drawPileCount}
|
||||||
@@ -235,7 +258,7 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: UnoView; pl
|
|||||||
</div>
|
</div>
|
||||||
<div className="un-info">
|
<div className="un-info">
|
||||||
{v.color ? (
|
{v.color ? (
|
||||||
<span key={v.color} className="un-color" style={{ background: COLOR_HEX[v.color], color: COLOR_INK[v.color] }} aria-live="polite">
|
<span key={v.color} className="un-color anim-pop" style={{ background: COLOR_HEX[v.color], color: COLOR_INK[v.color] }} aria-live="polite">
|
||||||
<span className="sw" aria-hidden />
|
<span className="sw" aria-hidden />
|
||||||
지금 색: {COLOR_KO[v.color]}
|
지금 색: {COLOR_KO[v.color]}
|
||||||
</span>
|
</span>
|
||||||
@@ -316,7 +339,12 @@ function MyHand({ v, act, pending, players }: { v: UnoView; act: (a: unknown) =>
|
|||||||
|
|
||||||
const myTurn = v.current === v.me && (v.phase === 'turn' || v.phase === 'afterDraw' || (v.phase === 'wild4' && my.playable.length > 0));
|
const myTurn = v.current === v.me && (v.phase === 'turn' || v.phase === 'afterDraw' || (v.phase === 'wild4' && my.playable.length > 0));
|
||||||
const byId = (id: string) => my.hand.find((c) => c.id === id);
|
const byId = (id: string) => my.hand.find((c) => c.id === id);
|
||||||
|
useNewEntries(my.hand, (c) => c.id, (fresh) => {
|
||||||
|
const deck = fxEl('uno-deck');
|
||||||
|
fresh.forEach((c, i) => flyFrom(document.querySelector(`.un-card[data-id="${cssEsc(c.id)}"]`), deck, { delay: i * 70, rotate: 8 }));
|
||||||
|
}, 30);
|
||||||
const send = (id: string, extra: Record<string, unknown> = {}) => {
|
const send = (id: string, extra: Record<string, unknown> = {}) => {
|
||||||
|
rememberPlay(id);
|
||||||
act({ type: 'play', cardId: id, ...extra, ...(armed && my.hand.length === 2 ? { uno: true } : {}) });
|
act({ type: 'play', cardId: id, ...extra, ...(armed && my.hand.length === 2 ? { uno: true } : {}) });
|
||||||
setSel(null);
|
setSel(null);
|
||||||
setPick(null);
|
setPick(null);
|
||||||
@@ -336,6 +364,7 @@ function MyHand({ v, act, pending, players }: { v: UnoView; act: (a: unknown) =>
|
|||||||
}
|
}
|
||||||
setNote('');
|
setNote('');
|
||||||
setSel(c.id);
|
setSel(c.id);
|
||||||
|
sfx.select();
|
||||||
};
|
};
|
||||||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||||||
@@ -382,6 +411,7 @@ function MyHand({ v, act, pending, players }: { v: UnoView; act: (a: unknown) =>
|
|||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
ref={ref}
|
ref={ref}
|
||||||
|
data-fx="uno-hand"
|
||||||
className={`un-hand${phone ? ' wrap' : ''}`}
|
className={`un-hand${phone ? ' wrap' : ''}`}
|
||||||
role="group"
|
role="group"
|
||||||
aria-label="내 카드. 좌우 방향키로 고르고 Enter로 들어 올리거나 내요"
|
aria-label="내 카드. 좌우 방향키로 고르고 Enter로 들어 올리거나 내요"
|
||||||
@@ -625,6 +655,9 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
|
|||||||
if (lastLog && !mine) setAnnounce(logText(lastLog, players));
|
if (lastLog && !mine) setAnnounce(logText(lastLog, players));
|
||||||
}, [lastLog?.seq, lastLog?.t]); // eslint-disable-line react-hooks/exhaustive-deps
|
}, [lastLog?.seq, lastLog?.t]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
const [banner, showBanner] = useBanner();
|
||||||
|
useUnoFx(v, me, players, showBanner);
|
||||||
|
|
||||||
const myIdx = v.seats.findIndex((s) => s.id === me);
|
const myIdx = v.seats.findIndex((s) => s.id === me);
|
||||||
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
||||||
const opps = useSeatRows<HTMLUListElement>(others.length);
|
const opps = useSeatRows<HTMLUListElement>(others.length);
|
||||||
@@ -646,7 +679,10 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
|
|||||||
onDraw={() => act({ type: 'draw' })}
|
onDraw={() => act({ type: 'draw' })}
|
||||||
onDropCard={(id) => {
|
onDropCard={(id) => {
|
||||||
const c = v.my?.hand.find((x) => x.id === id);
|
const c = v.my?.hand.find((x) => x.id === id);
|
||||||
if (c && v.my!.playable.includes(id) && !isWild(c)) act({ type: 'play', cardId: id });
|
if (c && v.my!.playable.includes(id) && !isWild(c)) {
|
||||||
|
rememberPlay(id);
|
||||||
|
act({ type: 'play', cardId: id });
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<StartColorPanel v={v} act={act} pending={pending} />
|
<StartColorPanel v={v} act={act} pending={pending} />
|
||||||
@@ -662,10 +698,105 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
|
|||||||
<p className="sr-only" aria-live="polite">
|
<p className="sr-only" aria-live="polite">
|
||||||
{announce}
|
{announce}
|
||||||
</p>
|
</p>
|
||||||
|
{banner}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
|
||||||
|
function useUnoFx(v: UnoView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||||
|
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
|
||||||
|
useNewEntries(v.log, logKey, (fresh) => {
|
||||||
|
let t = 0;
|
||||||
|
for (const e of fresh) {
|
||||||
|
const at = t;
|
||||||
|
switch (e.t) {
|
||||||
|
case 'play': {
|
||||||
|
const top = document.querySelector('.un-discard .un-face.top');
|
||||||
|
flyFrom(top, e.p === me ? (myPlayRect ?? fxEl('uno-hand')) : seatEl(e.p), { ms: 340, rotate: -14 });
|
||||||
|
if (e.p === me) myPlayRect = null;
|
||||||
|
later(at, () => {
|
||||||
|
sfx.cardPlay();
|
||||||
|
if (e.card.kind === 'wild') unoSfx.wild();
|
||||||
|
if (e.card.kind === 'draw2' || e.card.kind === 'wild4') unoSfx.plus();
|
||||||
|
});
|
||||||
|
if (e.card.kind === 'wild4') showBanner('+4', 'dark', e.color ? `${COLOR_KO[e.color]}으로` : undefined);
|
||||||
|
else if (e.card.kind === 'draw2') showBanner('+2', 'red');
|
||||||
|
t += 120;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'draw': {
|
||||||
|
const n = Math.min(e.n, 8);
|
||||||
|
if (e.p !== me) flyGhost(fxEl('uno-deck'), seatEl(e.p), { count: n, gap: 80 });
|
||||||
|
later(at, () => sfx.draw(Math.min(n, 4)));
|
||||||
|
if (e.why === 'penalty' || e.why === 'challenge' || e.why === 'stack' || e.n >= 4) later(at, () => bump(seatEl(e.p), 'shake'));
|
||||||
|
t += 120;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'uno':
|
||||||
|
showBanner('우노!', 'red', e.p === me ? undefined : `${nick(players, e.p)}님`);
|
||||||
|
later(at, sfx.fanfare);
|
||||||
|
bump(seatEl(e.p));
|
||||||
|
break;
|
||||||
|
case 'caught':
|
||||||
|
showBanner('잡았다!', 'gold', `${nick(players, e.p)}님 +${e.n}장`);
|
||||||
|
later(at, sfx.alarm);
|
||||||
|
break;
|
||||||
|
case 'challenge':
|
||||||
|
showBanner(e.illegal ? '도전 성공!' : '도전 실패', e.illegal ? 'green' : 'dark');
|
||||||
|
later(at + 150, e.illegal ? sfx.good : sfx.bad);
|
||||||
|
break;
|
||||||
|
case 'skip':
|
||||||
|
later(at + 80, unoSfx.skip);
|
||||||
|
bump(seatEl(e.p), 'shake');
|
||||||
|
break;
|
||||||
|
case 'reverse':
|
||||||
|
later(at + 80, unoSfx.reverse);
|
||||||
|
bump(document.querySelector('.un-dir b'));
|
||||||
|
break;
|
||||||
|
case 'reshuffle':
|
||||||
|
later(at, sfx.shuffle);
|
||||||
|
bump(fxEl('uno-deck'), 'shake');
|
||||||
|
break;
|
||||||
|
case 'startColor':
|
||||||
|
later(at, unoSfx.wild);
|
||||||
|
break;
|
||||||
|
case 'round':
|
||||||
|
if (e.winner) {
|
||||||
|
const to = seatEl(e.winner) ?? fxEl('uno-hand');
|
||||||
|
for (const s of v.seats) if (s.id !== e.winner && !s.left) flyGhost(seatEl(s.id), to, { count: 3, gap: 60 });
|
||||||
|
later(at + 200, sfx.collect);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'timeout':
|
||||||
|
later(at, sfx.tick);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// A new round (or the very first deal): cards are dealt from the deck to everyone.
|
||||||
|
// `myHand`: only on mount — on a later round MyHand's own new-card motion already flies my cards in.
|
||||||
|
const deal = (myHand: boolean) => {
|
||||||
|
const deck = fxEl('uno-deck');
|
||||||
|
sfx.shuffle();
|
||||||
|
setTimeout(() => sfx.deal(7, 60), 300);
|
||||||
|
if (myHand) document.querySelectorAll('.un-hand .un-card').forEach((el, i) => flyFrom(el, deck, { delay: 280 + i * 60, rotate: 10 }));
|
||||||
|
for (const s of v.seats) if (s.id !== me && !s.left) flyGhost(deck, seatEl(s.id), { count: 3, gap: 90, delay: 280 });
|
||||||
|
};
|
||||||
|
useChange(v.round, () => deal(false));
|
||||||
|
const started = useRef(false);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (started.current) return;
|
||||||
|
started.current = true;
|
||||||
|
// Mounted right at the start of the game (nothing played yet): show the deal once.
|
||||||
|
if (v.round === 1 && v.discardCount <= 1 && !v.log.some((e) => e.t === 'play')) deal(true);
|
||||||
|
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
}
|
||||||
|
|
||||||
|
const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`;
|
||||||
|
|
||||||
// ---------------------------------------------------------------- side
|
// ---------------------------------------------------------------- side
|
||||||
|
|
||||||
function rulesLine(o: UnoOptions): string {
|
function rulesLine(o: UnoOptions): string {
|
||||||
@@ -733,7 +864,7 @@ function UnoSide({ view: v, me, players, deadline }: BoardProps<UnoView>) {
|
|||||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||||
<ol className="un-log">
|
<ol className="un-log">
|
||||||
{[...v.log].reverse().map((e) => (
|
{[...v.log].reverse().map((e) => (
|
||||||
<li key={`${e.seq}-${e.t}-${'p' in e ? e.p : ''}`} className="small">
|
<li key={logKey(e)} className="small">
|
||||||
{logText(e, players)}
|
{logText(e, players)}
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
@@ -777,7 +908,7 @@ function statusText(v: UnoView, me: string | null, players: Record<string, Publi
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- options
|
// ---------------------------------------------------------------- options
|
||||||
|
|
||||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="segmented" role="group" aria-label={label}>
|
<div className="segmented" role="group" aria-label={label}>
|
||||||
{options.map(([k, l]) => (
|
{options.map(([k, l]) => (
|
||||||
@@ -824,7 +955,7 @@ function Options({ value: o, onChange }: OptionsProps<UnoOptions>) {
|
|||||||
<Seg label="낼 수 있을 때까지 뽑기" value={o.drawUntilPlayable} options={onOff} onChange={(drawUntilPlayable) => set({ drawUntilPlayable })} />
|
<Seg label="낼 수 있을 때까지 뽑기" value={o.drawUntilPlayable} options={onOff} onChange={(drawUntilPlayable) => set({ drawUntilPlayable })} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="한 턴 제한 시간">
|
<Field label="한 턴 제한 시간">
|
||||||
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||||
</Field>
|
</Field>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -834,7 +965,7 @@ function optionsSummary(o: UnoOptions): string {
|
|||||||
const parts = [o.scoring === 'to500' ? '500점 먼저' : '한 판', o.wild4Rule === 'challenge' ? '+4 도전' : '+4 제한'];
|
const parts = [o.scoring === 'to500' ? '500점 먼저' : '한 판', o.wild4Rule === 'challenge' ? '+4 도전' : '+4 제한'];
|
||||||
if (o.stacking) parts.push('쌓기');
|
if (o.stacking) parts.push('쌓기');
|
||||||
if (o.drawUntilPlayable) parts.push('나올 때까지 뽑기');
|
if (o.drawUntilPlayable) parts.push('나올 때까지 뽑기');
|
||||||
parts.push(`${o.turnSeconds}초`);
|
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
|
||||||
return parts.join(' · ');
|
return parts.join(' · ');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -897,7 +1028,10 @@ function Rules({ options }: { options?: UnoOptions }) {
|
|||||||
<strong>점수</strong>: 이긴 사람은 다른 사람 손에 남은 카드 점수(숫자 그대로, 스킵·리버스·드로우2 20점, 와일드 50점)를 얻어요.
|
<strong>점수</strong>: 이긴 사람은 다른 사람 손에 남은 카드 점수(숫자 그대로, 스킵·리버스·드로우2 20점, 와일드 50점)를 얻어요.
|
||||||
{o.scoring === 'to500' ? ' 여러 판을 해서 500점에 먼저 닿으면 이겨요.' : ' 이 방은 한 판으로 끝나요.'}
|
{o.scoring === 'to500' ? ' 여러 판을 해서 500점에 먼저 닿으면 이겨요.' : ' 이 방은 한 판으로 끝나요.'}
|
||||||
</p>
|
</p>
|
||||||
<p>시간 안에 고르지 않으면 낼 수 있는 카드 하나를 자동으로 내요(와일드는 가장 많이 가진 색). 낼 카드가 없으면 1장 뽑아요.</p>
|
<p>
|
||||||
|
{o.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 낼 수 있는 카드 하나를 자동으로 내요(와일드는 가장 많이
|
||||||
|
가진 색). 낼 카드가 없으면 1장 뽑아요.
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,8 @@
|
|||||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `characterDraft` | 캐릭터 배정 방식 | `random`(1장 무작위) / `choose2`(2장 중 1장 선택) | `random` |
|
| `characterDraft` | 캐릭터 배정 방식 | `random`(1장 무작위) / `choose2`(2장 중 1장 선택) | `random` |
|
||||||
| `turnSeconds` | 내 턴 제한 시간(초) | 30 / 60 / 90 / 120 | 60 |
|
| `turnSeconds` | 내 턴 제한 시간(초) | 30 / 60 / 90 / 120 / 무제한(`null`, 캐릭터 2장 중 고르기 30초도 없앰) | 60 |
|
||||||
| `reactionSeconds` | 반응(빗나감!/맥주/결투 응수/잡화점 선택) 제한 시간(초) | 8 / 15 / 25 | 15 |
|
| `reactionSeconds` | 반응(빗나감!/맥주/결투 응수/잡화점 선택) 제한 시간(초) | 8 / 15 / 25 / 무제한(`null`) | 15 |
|
||||||
| `autoDefend` | 반응 시간 초과 시 가능한 방어 카드를 자동으로 사용 | on / off | on |
|
| `autoDefend` | 반응 시간 초과 시 가능한 방어 카드를 자동으로 사용 | on / off | on |
|
||||||
| `autoBarrel` | 술통/주르도네 판정을 묻지 않고 자동 실행 | on / off | on |
|
| `autoBarrel` | 술통/주르도네 판정을 묻지 않고 자동 실행 | on / off | on |
|
||||||
| `revealRoleOnDeath` | 사망 시 역할 공개(원작 규칙) | on 고정 | on |
|
| `revealRoleOnDeath` | 사망 시 역할 공개(원작 규칙) | on 고정 | on |
|
||||||
@@ -140,7 +140,7 @@
|
|||||||
패닉!/캣 벌루 대상은 "다른 플레이어"로 한정한다(자기 자신 불가, 결정 사항).
|
패닉!/캣 벌루 대상은 "다른 플레이어"로 한정한다(자기 자신 불가, 결정 사항).
|
||||||
|
|
||||||
### 5.4 반응 창(Reaction window)
|
### 5.4 반응 창(Reaction window)
|
||||||
턴 진행은 다음 반응이 모두 끝날 때까지 멈춘다. 각 반응에는 `reactionSeconds` 타이머가 있다.
|
턴 진행은 다음 반응이 모두 끝날 때까지 멈춘다. 각 반응에는 `reactionSeconds` 타이머가 있다(무제한이면 타이머가 없다. 자리 비움인 사람만 5초. 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 처리).
|
||||||
- **뱅! 반응**: 대상에게 `missedNeeded`(기본 1, 슬랩의 뱅!은 2). 순서: (1) 술통 판정(실제 술통, 주르도네 능력 각각 1회, `autoBarrel`이면 자동) → 성공마다 needed -1. (2) 남은 needed만큼 빗나감!(캘러미티는 뱅!도) 제출 또는 포기. 포기/시간 초과 시 생명 1 손실.
|
- **뱅! 반응**: 대상에게 `missedNeeded`(기본 1, 슬랩의 뱅!은 2). 순서: (1) 술통 판정(실제 술통, 주르도네 능력 각각 1회, `autoBarrel`이면 자동) → 성공마다 needed -1. (2) 남은 needed만큼 빗나감!(캘러미티는 뱅!도) 제출 또는 포기. 포기/시간 초과 시 생명 1 손실.
|
||||||
- 슬랩 상대로 빗나감!이 1장뿐이면 내 봐야 소용없으므로 UI에서 "막을 수 없음"을 안내하되 낼 수는 있다(효과 없음 → 실제로는 막지 못함). 엔진은 needed를 모두 채울 때만 카드 제출을 받는다(부분 제출 금지, 결정 사항).
|
- 슬랩 상대로 빗나감!이 1장뿐이면 내 봐야 소용없으므로 UI에서 "막을 수 없음"을 안내하되 낼 수는 있다(효과 없음 → 실제로는 막지 못함). 엔진은 needed를 모두 채울 때만 카드 제출을 받는다(부분 제출 금지, 결정 사항).
|
||||||
- **개틀링 / 인디언!**: 대상 전원에게 동시에 반응 창을 연다. 각자의 응답은 도착 순서대로 개별 처리된다.
|
- **개틀링 / 인디언!**: 대상 전원에게 동시에 반응 창을 연다. 각자의 응답은 도착 순서대로 개별 처리된다.
|
||||||
@@ -281,6 +281,8 @@ interface BangResult {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## 9. UI/UX
|
## 9. UI/UX
|
||||||
|
|
||||||
|
- 소리·움직임(2026-10-13): 카드 내기 = 낸 자리에서 버린 더미(파란 카드·감옥은 그 자리)로 날아가며 소리, 뱅! = 💥가 쏜 사람에서 맞는 사람으로 날아가고 총소리·자리 흔들림(내가 맞으면 "뱅!" 배너), 개틀링·인디언·결투 배너와 소리, 빗나감!·술통 = 튕기는 소리, 생명 잃기 = 맞는 소리와 흔들림, 맥주 = 꿀꺽 소리, 판정 카드 = 더미에서 뒤집히며 날아감, 다이너마이트 폭발 "펑!", 감옥 철컹, 뽑기 = 더미에서 자리로, 쓰러짐 = 역할 공개 배너, 게임 끝 = 이긴 편 배너. 내 행동과 남(컴퓨터 포함)의 행동 모두 view 변화에 반응하고, 처음 들어올 때·새로고침·다시 보기 건너뛰기에는 나지 않는다. 움직임은 0.2~0.6초, 날아가는 카드는 클릭을 막지 않는다. 소리는 사이트 음량을 따르고 합성음만 쓴다(파일 없음). 차례인 자리는 테두리가 은은하게 빛난다.
|
||||||
- 모바일 세로: 상단 원형 테이블(플레이어 아바타 + 생명 탄환 아이콘 + 장착 카드 축소판 + 손패 장수), 하단 손패 가로 스크롤(카드 높이 120px 이상), 그 사이 행동 버튼(턴 종료 등 48px 이상).
|
- 모바일 세로: 상단 원형 테이블(플레이어 아바타 + 생명 탄환 아이콘 + 장착 카드 축소판 + 손패 장수), 하단 손패 가로 스크롤(카드 높이 120px 이상), 그 사이 행동 버튼(턴 종료 등 48px 이상).
|
||||||
- 카드를 탭하면 쓸 수 있는 대상 플레이어가 초록 테두리로 강조되고 사거리 밖은 회색 + "거리 3 / 사거리 2" 표시. 쓸 수 없는 카드는 흐리게 + 이유 툴팁.
|
- 카드를 탭하면 쓸 수 있는 대상 플레이어가 초록 테두리로 강조되고 사거리 밖은 회색 + "거리 3 / 사거리 2" 표시. 쓸 수 없는 카드는 흐리게 + 이유 툴팁.
|
||||||
- 반응 창: 화면 중앙 큰 모달 "뱅! 공격을 받았습니다 — [빗나감! 내기] [맞기]" + 원형 타이머. 슬랩 상대 시 "빗나감! 2장 필요" 문구.
|
- 반응 창: 화면 중앙 큰 모달 "뱅! 공격을 받았습니다 — [빗나감! 내기] [맞기]" + 원형 타이머. 슬랩 상대 시 "빗나감! 2장 필요" 문구.
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `loseCount` | 같은 종류가 몇 장 쌓이면 패배 | 3 / 4 / 5 | 3~6인 4, 2인 5(원작) |
|
| `loseCount` | 같은 종류가 몇 장 쌓이면 패배 | 3 / 4 / 5 | 3~6인 4, 2인 5(원작) |
|
||||||
| `turnSeconds` | 카드 건네기/판단 제한 시간 | 15 / 30 / 60 | 30 |
|
| `turnSeconds` | 카드 건네기/판단 제한 시간 | 15 / 30 / 60 / 무제한(`null`) | 30 |
|
||||||
| `showSeenBy` | 현재 카드를 이미 본 사람 표시 | on 고정 | on |
|
| `showSeenBy` | 현재 카드를 이미 본 사람 표시 | on 고정 | on |
|
||||||
| `claimHistory` | 이번 라운드의 주장 이력(누가 무엇이라 했는지) 표시 | on / off | on |
|
| `claimHistory` | 이번 라운드의 주장 이력(누가 무엇이라 했는지) 표시 | on / off | on |
|
||||||
| `quickChat` | 정해진 문구 버튼("정말이야!", "의심스러운데?") | on / off | on |
|
| `quickChat` | 정해진 문구 버튼("정말이야!", "의심스러운데?") | on / off | on |
|
||||||
@@ -158,6 +158,8 @@ interface CockroachResult {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## 9. UI/UX
|
## 9. UI/UX
|
||||||
|
|
||||||
|
- 소리·움직임(2026-10-13): 건네기·넘기기 = 뒷면 카드가 건넨 자리에서 받은 자리로 날아가며 사각사각 소리, 몰래 보기 = 뒤집는 소리, 판정 = "진짜!"/"거짓말!" 배너와 맞힘(좋은 소리)/틀림(시무룩한 소리), 카드가 가져가는 사람 자리로 날아가 흔들림, 한 장만 더 오면 질 때 경고음, 빠른 말 = 뿅 소리, 게임 끝 = 패배 배너. 내 행동과 남(컴퓨터 포함)의 행동 모두 view 변화에 반응하고, 처음 들어올 때·새로고침·다시 보기 건너뛰기에는 나지 않는다. 움직임은 0.2~0.6초, 날아가는 카드는 클릭을 막지 않는다. 소리는 사이트 음량을 따르고 합성음만 쓴다(파일 없음). 차례인 자리는 테두리가 은은하게 빛난다.
|
||||||
- 모바일 세로: 상단 상대 플레이어 카드(아바타 + 손패 장수 + 앞마당 종류별 개수 배지, 3장째부터 노란색 경고, 위험 종류는 빨간색). 가운데 "건네지는 카드" 애니메이션과 말풍선 주장("이건 쥐야!"). 하단 내 손패(종류별 묶음 + 개수 배지, 탭으로 선택).
|
- 모바일 세로: 상단 상대 플레이어 카드(아바타 + 손패 장수 + 앞마당 종류별 개수 배지, 3장째부터 노란색 경고, 위험 종류는 빨간색). 가운데 "건네지는 카드" 애니메이션과 말풍선 주장("이건 쥐야!"). 하단 내 손패(종류별 묶음 + 개수 배지, 탭으로 선택).
|
||||||
- 건네기 흐름: 카드 선택 → 받을 사람 탭(건넬 수 없는 사람은 회색) → 8종 그림 버튼 중 주장 선택(그림 + 글자, 각 64px 이상) → 확인.
|
- 건네기 흐름: 카드 선택 → 받을 사람 탭(건넬 수 없는 사람은 회색) → 8종 그림 버튼 중 주장 선택(그림 + 글자, 각 64px 이상) → 확인.
|
||||||
- 판정 화면: 큰 버튼 두 개 "진짜!"(초록), "거짓말!"(빨강) + "몰래 보고 넘기기"(파랑, 넘길 사람이 없으면 비활성 + 이유).
|
- 판정 화면: 큰 버튼 두 개 "진짜!"(초록), "거짓말!"(빨강) + "몰래 보고 넘기기"(파랑, 넘길 사람이 없으면 비활성 + 이유).
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
| `jesterTaxable` | 세금 낼 때 광대도 "좋은 카드"로 내야 하나 | on / off | off |
|
| `jesterTaxable` | 세금 낼 때 광대도 "좋은 카드"로 내야 하나 | on / off | off |
|
||||||
| `passLocksOut` | 한 번 패스하면 그 트릭에서 다시 못 냄(하우스 룰) | on / off(원작) | off |
|
| `passLocksOut` | 한 번 패스하면 그 트릭에서 다시 못 냄(하우스 룰) | on / off(원작) | off |
|
||||||
| `removeHighCards` | 9~12 카드를 빼고 하기(손패가 많을 때, 나무위키 언급) | on / off | off |
|
| `removeHighCards` | 9~12 카드를 빼고 하기(손패가 많을 때, 나무위키 언급) | on / off | off |
|
||||||
| `turnSeconds` | 턴 제한 시간 | 15 / 20 / 30 / 45 | 20 |
|
| `turnSeconds` | 턴 제한 시간 | 15 / 20 / 30 / 45 / 무제한(`null`) | 20 |
|
||||||
|
|
||||||
## 3. 구성물
|
## 3. 구성물
|
||||||
- 숫자 카드 78장: 숫자 n인 카드가 n장이다(1이 1장, 2가 2장, …, 12가 12장).
|
- 숫자 카드 78장: 숫자 n인 카드가 n장이다(1이 1장, 2가 2장, …, 12가 12장).
|
||||||
@@ -182,7 +182,7 @@ interface DalmutiState {
|
|||||||
- 그 외 없음(세금 자동 선택은 숫자 → 카드 ID 순으로 결정적).
|
- 그 외 없음(세금 자동 선택은 숫자 → 카드 ID 순으로 결정적).
|
||||||
|
|
||||||
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
||||||
- 마감: `revolutionCheck` 20초, `taxReturn` 30초, 플레이 `turnSeconds`.
|
- 마감: `revolutionCheck` 20초, `taxReturn` 30초, 플레이 `turnSeconds`. 무제한(`null`)이면 세 단계 모두 마감이 없다(기다리는 사람이 모두 자리 비움이면 5초). 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 행동.
|
||||||
- `onTimeout`
|
- `onTimeout`
|
||||||
- `revolutionCheck`: `confirmHand { declareRevolution: false }`. 자동으로 혁명을 선언하지 않는다.
|
- `revolutionCheck`: `confirmHand { declareRevolution: false }`. 자동으로 혁명을 선언하지 않는다.
|
||||||
- `taxReturn`: 숫자가 가장 큰(가장 나쁜) 숫자 카드부터 필요한 장수만큼 돌려준다(광대 제외).
|
- `taxReturn`: 숫자가 가장 큰(가장 나쁜) 숫자 카드부터 필요한 장수만큼 돌려준다(광대 제외).
|
||||||
@@ -201,6 +201,8 @@ interface GameResult {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## 9. UI/UX
|
## 9. UI/UX
|
||||||
|
|
||||||
|
- 소리·움직임(2026-10-13): 카드 내기 = 낸 자리에서 바닥으로 장수만큼 날아가며 "착착", 패스 = 두 번 두드림과 자리 흐려짐, 트릭 끝 = 바닥 카드가 다음 선에게 쓸려 감, 등수 확정 배너, 혁명·대혁명 배너와 북소리, 세금·돌려주기 = 카드가 자리 사이를 날아감, 라운드 시작 = 섞고 나눠 주기. 내 행동과 남(컴퓨터 포함)의 행동 모두 view 변화에 반응하고, 처음 들어올 때·새로고침·다시 보기 건너뛰기에는 나지 않는다. 움직임은 0.2~0.6초, 날아가는 카드는 클릭을 막지 않는다. 소리는 사이트 음량을 따르고 합성음만 쓴다(파일 없음). 차례인 자리는 테두리가 은은하게 빛난다.
|
||||||
- 모바일 세로 화면
|
- 모바일 세로 화면
|
||||||
- 위: 신분 순서대로 상대를 원형으로 배치한다. 각자 왕관/모자 아이콘(신분), 손패 장수, 패스 말풍선을 표시한다.
|
- 위: 신분 순서대로 상대를 원형으로 배치한다. 각자 왕관/모자 아이콘(신분), 손패 장수, 패스 말풍선을 표시한다.
|
||||||
- 가운데: 현재 트릭 바닥 묶음(마지막 묶음을 크게, 이전 묶음은 겹쳐서 작게). "지금 기준: 5 × 2장"을 큰 글자로 보여 준다.
|
- 가운데: 현재 트릭 바닥 묶음(마지막 묶음을 크게, 이전 묶음은 겹쳐서 작게). "지금 기준: 5 × 2장"을 큰 글자로 보여 준다.
|
||||||
|
|||||||
@@ -38,8 +38,8 @@
|
|||||||
| `gwangPrice` | 광팔기 1장당 값 | 1 / 2 / 3 | 1 |
|
| `gwangPrice` | 광팔기 1장당 값 | 1 / 2 / 3 | 1 |
|
||||||
| `gwangPayer` | 광값 내는 사람 | `nonDealerPlayers`(선 제외 참가자 각자) / `allPlayers`(참가자 3명 각자) | `nonDealerPlayers` |
|
| `gwangPayer` | 광값 내는 사람 | `nonDealerPlayers`(선 제외 참가자 각자) / `allPlayers`(참가자 3명 각자) | `nonDealerPlayers` |
|
||||||
| `gwangSellCards` | 팔 수 있는 패 | `gwang`(광만) / `gwangPlus`(광 + 쌍피·국진·보너스) | `gwang` |
|
| `gwangSellCards` | 팔 수 있는 패 | `gwang`(광만) / `gwangPlus`(광 + 쌍피·국진·보너스) | `gwang` |
|
||||||
| `turnSeconds` | 1턴 제한 시간 | 5~60 | 15 |
|
| `turnSeconds` | 1턴 제한 시간 | 5~60 / 무제한(`null`) | 15 |
|
||||||
| `decisionSeconds` | 고/스톱·선택 제한 시간 | 5~30 | 10 |
|
| `decisionSeconds` | 고/스톱·선택 제한 시간 | 5~30 / 무제한(`null`) | 10 |
|
||||||
| `hints` | 먹을 수 있는 패·족보 진행 힌트 | true / false | true |
|
| `hints` | 먹을 수 있는 패·족보 진행 힌트 | true / false | true |
|
||||||
|
|
||||||
모드(맞고/고스톱)는 `setup`의 인원 수로 정한다. 2명이면 맞고 기본값, 3~5명이면 고스톱 기본값을 쓴다.
|
모드(맞고/고스톱)는 `setup`의 인원 수로 정한다. 2명이면 맞고 기본값, 3~5명이면 고스톱 기본값을 쓴다.
|
||||||
@@ -342,7 +342,7 @@ interface GostopState {
|
|||||||
- 그 밖에는 RNG를 쓰지 않는다. 자동 행동은 결정적이다.
|
- 그 밖에는 RNG를 쓰지 않는다. 자동 행동은 결정적이다.
|
||||||
|
|
||||||
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
||||||
- `deadline`: 턴(`play`) = `turnSeconds`, 선택 단계(`chooseFlip`, `goStop`, `chongtong`, `sell`, `gukjin`) = `decisionSeconds`, 결과 화면 = 10초.
|
- `deadline`: 턴(`play`) = `turnSeconds`, 선택 단계(`chooseFlip`, `goStop`, `chongtong`, `sell`, `gukjin`) = `decisionSeconds`, 결과 화면 = 10초. 무제한(`null`)이면 그 단계에 마감이 없다(autoPilot이면 2초). 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 행동.
|
||||||
- `onTimeout(state, player)` (모두 결정적):
|
- `onTimeout(state, player)` (모두 결정적):
|
||||||
- `play`: 빈패가 있으면 빈패를 낸다. 없으면 보너스패가 있으면 그것부터. 그 밖에는 바닥과 맞는 패 중 가져올 바닥 패 가치가 가장 큰 것(광 > 열끗 > 띠 > 쌍피 > 피, 같으면 낮은 ID), 맞는 패가 없으면 손패 중 가치가 가장 낮은 패(같으면 낮은 ID). target은 가치 큰 쪽. 흔들기·폭탄은 선언하지 않는다.
|
- `play`: 빈패가 있으면 빈패를 낸다. 없으면 보너스패가 있으면 그것부터. 그 밖에는 바닥과 맞는 패 중 가져올 바닥 패 가치가 가장 큰 것(광 > 열끗 > 띠 > 쌍피 > 피, 같으면 낮은 ID), 맞는 패가 없으면 손패 중 가치가 가장 낮은 패(같으면 낮은 ID). target은 가치 큰 쪽. 흔들기·폭탄은 선언하지 않는다.
|
||||||
- `chooseFlip`: 가치 큰 쪽.
|
- `chooseFlip`: 가치 큰 쪽.
|
||||||
@@ -368,6 +368,8 @@ interface GostopResult {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## 9. UI/UX
|
## 9. UI/UX
|
||||||
|
|
||||||
|
- 소리·움직임(2026-10-13): 판 시작 = 섞고 더미에서 바닥·손으로 패가 날아감, 패 내기 = "탁" 소리와 함께 바닥으로, 더미 뒤집기 = 뒤집히며 날아감, 먹기 = 바닥에서 먹은 사람 패 더미로 "착착", 피 뺏기 = 상대 더미에서 날아오고 상대 자리 흔들림, 뻑·따닥·쪽·싹쓸이·폭탄·흔들기·보너스패 배너와 소리, N고 배너(고마다 한 음씩 높아짐), 광 팔기, 판 끝 = 스톱!/총통!/나가리 배너와 점수 표시가 진 자리에서 이긴 자리로. 내 행동과 남(컴퓨터 포함)의 행동 모두 view 변화에 반응하고, 처음 들어올 때·새로고침·다시 보기 건너뛰기에는 나지 않는다. 움직임은 0.2~0.6초, 날아가는 카드는 클릭을 막지 않는다. 소리는 사이트 음량을 따르고 합성음만 쓴다(파일 없음). 차례인 자리는 테두리가 은은하게 빛난다.
|
||||||
- 모바일 세로 배치(위 → 아래)
|
- 모바일 세로 배치(위 → 아래)
|
||||||
- 상대 영역: 이름, 방 점수, 손패 장수(뒷면), 먹은 패를 종류별로 겹친 묶음(광/열끗/띠/피, 탭하면 펼침), 현재 점수 배지, 고 횟수 배지.
|
- 상대 영역: 이름, 방 점수, 손패 장수(뒷면), 먹은 패를 종류별로 겹친 묶음(광/열끗/띠/피, 탭하면 펼침), 현재 점수 배지, 고 횟수 배지.
|
||||||
- 바닥: 월별로 묶어 3x4 격자에 배치(같은 월은 겹침). 뻑 무더기는 빨간 테두리. 더미는 가운데 옆에 남은 장수와 함께.
|
- 바닥: 월별로 묶어 3x4 격자에 배치(같은 월은 겹침). 뻑 무더기는 빨간 테두리. 더미는 가운데 옆에 남은 장수와 함께.
|
||||||
|
|||||||
@@ -42,7 +42,7 @@
|
|||||||
| `jokerRange` | (`kr-product`) 조커로 부를 수 있는 범위 | `60-99`(원작) / `0-99` | `60-99` |
|
| `jokerRange` | (`kr-product`) 조커로 부를 수 있는 범위 | `60-99`(원작) / `0-99` | `60-99` |
|
||||||
| `aceHigh` | (`classic`) A의 큰 값 | 10(나무위키) / 11(Bicycle) | 11 |
|
| `aceHigh` | (`classic`) A의 큰 값 | 10(나무위키) / 11(Bicycle) | 11 |
|
||||||
| `deckCount` | (`classic`) 덱 수 | `auto`(7인 이상 2벌) / 1 / 2 | `auto` |
|
| `deckCount` | (`classic`) 덱 수 | `auto`(7인 이상 2벌) / 1 / 2 | `auto` |
|
||||||
| `turnSeconds` | 턴 제한 시간 | 10 / 15 / 20 / 30 | 15 |
|
| `turnSeconds` | 턴 제한 시간 | 10 / 15 / 20 / 30 / 무제한(`null`) | 15 |
|
||||||
|
|
||||||
## 3. 구성물
|
## 3. 구성물
|
||||||
`kr-product` (기본값 기준 91장)
|
`kr-product` (기본값 기준 91장)
|
||||||
@@ -213,7 +213,7 @@ interface NinetyNineState {
|
|||||||
- 라운드 재시작(목숨 모드, `reset`) 때 다시 섞기.
|
- 라운드 재시작(목숨 모드, `reset`) 때 다시 섞기.
|
||||||
|
|
||||||
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
||||||
- `deadline = turnStartedAt + turnSeconds*1000`.
|
- `deadline = turnStartedAt + turnSeconds*1000`. 무제한(`null`)이면 마감 없음(자리 비움만 3초). 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 행동.
|
||||||
- `onTimeout(state, p)`: 합법인 (카드, 선택값) 조합 중 결과 합계 S'가 가장 작은 것을 고른다.
|
- `onTimeout(state, p)`: 합법인 (카드, 선택값) 조합 중 결과 합계 S'가 가장 작은 것을 고른다.
|
||||||
- 같으면 우선순위: 0/4/9(변화 없음) → 일반 숫자 카드 → ±카드 → K/조커. 그래도 같으면 카드 ID 순.
|
- 같으면 우선순위: 0/4/9(변화 없음) → 일반 숫자 카드 → ±카드 → K/조커. 그래도 같으면 카드 ID 순.
|
||||||
- `kr-product`의 0은 방향을 그대로 두는 쪽으로 낸다.
|
- `kr-product`의 0은 방향을 그대로 두는 쪽으로 낸다.
|
||||||
@@ -233,6 +233,8 @@ interface GameResult {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## 9. UI/UX
|
## 9. UI/UX
|
||||||
|
|
||||||
|
- 소리·움직임(2026-10-13): 카드 내기 = 낸 자리에서 합계 다이얼로 카드가 날아가며 소리, 합계 다이얼이 튀고 90 이상이면 흔들리며 두근 소리, 바로 99 = "99!" 배너와 사이렌, 방향 바뀜 = 화살표 튐과 올라갔다 내려가는 소리, 홀드·0 = 똑딱, 보충 = 더미에서 자리로, 낼 카드 없음·목숨 잃기·탈락 배너와 소리, 새 판 = 섞고 나눠 주기. 내 행동과 남(컴퓨터 포함)의 행동 모두 view 변화에 반응하고, 처음 들어올 때·새로고침·다시 보기 건너뛰기에는 나지 않는다. 움직임은 0.2~0.6초, 날아가는 카드는 클릭을 막지 않는다. 소리는 사이트 음량을 따르고 합성음만 쓴다(파일 없음). 차례인 자리는 테두리가 은은하게 빛난다.
|
||||||
- 모바일 세로 화면
|
- 모바일 세로 화면
|
||||||
- 가운데: 현재 합계를 아주 크게(예: 72pt) 보여 준다. 99에 가까울수록 색이 초록 → 노랑 → 빨강으로 바뀌는 게이지 링을 두른다.
|
- 가운데: 현재 합계를 아주 크게(예: 72pt) 보여 준다. 99에 가까울수록 색이 초록 → 노랑 → 빨강으로 바뀌는 게이지 링을 두른다.
|
||||||
- 위: 상대 아바타(손패 장수, 목숨 하트, 차례 표시), 진행 방향 화살표.
|
- 위: 상대 아바타(손패 장수, 목숨 하트, 차례 표시), 진행 방향 화살표.
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
## 2. 모드와 옵션
|
## 2. 모드와 옵션
|
||||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `turnSeconds` | 한 번 뽑는 제한 시간 | 10 / 20 / 30 / 60초 | 20초 |
|
| `turnSeconds` | 한 번 뽑는 제한 시간 | 10 / 20 / 30 / 60초 / 무제한(`null`) | 20초 |
|
||||||
|
|
||||||
일부러 넣지 않은 것: 짝 직접 버리기(항상 자동), 퀸 빼기(올드 메이드) 방식, 상대가 고르는 카드를 실시간으로 보여 주는 표시, "한 장 살짝 올려 보이기" 손장난. 규칙을 단순하게 두려고 뺐다. 손장난은 [섞기] 하나로 대신한다.
|
일부러 넣지 않은 것: 짝 직접 버리기(항상 자동), 퀸 빼기(올드 메이드) 방식, 상대가 고르는 카드를 실시간으로 보여 주는 표시, "한 장 살짝 올려 보이기" 손장난. 규칙을 단순하게 두려고 뺐다. 손장난은 [섞기] 하나로 대신한다.
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ A [♥2, ♥3], B [♠2, 조커], C [♠3]. A 차례: B의 첫 카드(♠2)를
|
|||||||
### 8.1 상태(State)
|
### 8.1 상태(State)
|
||||||
```ts
|
```ts
|
||||||
interface OldMaidState {
|
interface OldMaidState {
|
||||||
options: { turnSeconds: 10 | 20 | 30 | 60 };
|
options: { turnSeconds: 10 | 20 | 30 | 60 | null };
|
||||||
order: PlayerId[];
|
order: PlayerId[];
|
||||||
hands: Record<PlayerId, string[]>; // 들고 있는 순서 그대로(왼쪽부터)
|
hands: Record<PlayerId, string[]>; // 들고 있는 순서 그대로(왼쪽부터)
|
||||||
discards: Record<PlayerId, string[]>; // 버린 짝(공개)
|
discards: Record<PlayerId, string[]>; // 버린 짝(공개)
|
||||||
@@ -79,7 +79,7 @@ interface OldMaidState {
|
|||||||
- 덱 섞기, 첫 사람, 뽑은 카드를 넣을 자리, 섞기, 시간 초과 때 뽑을 자리, 나간 사람 카드 섞기와 넣을 자리. 모두 `ctx.rng`.
|
- 덱 섞기, 첫 사람, 뽑은 카드를 넣을 자리, 섞기, 시간 초과 때 뽑을 자리, 나간 사람 카드 섞기와 넣을 자리. 모두 `ctx.rng`.
|
||||||
|
|
||||||
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
||||||
- 차례마다 `turnSeconds`. 넘기면 지금 뽑을 사람의 **무작위 자리 한 장**을 뽑는다(자동 짝 버리기 포함). 3번 연속이면 "자리 비움"으로 제한 시간 5초, 직접 뽑으면 풀린다.
|
- 차례마다 `turnSeconds`(무제한 `null`이면 시계 없음, 자리 비움만 5초, 연결이 끊긴 사람은 방의 유예 시간 뒤 자동으로 뽑음). 넘기면 지금 뽑을 사람의 **무작위 자리 한 장**을 뽑는다(자동 짝 버리기 포함). 3번 연속이면 "자리 비움"으로 제한 시간 5초, 직접 뽑으면 풀린다.
|
||||||
- 섞기는 차례 시계를 다시 시작하지 않는다.
|
- 섞기는 차례 시계를 다시 시작하지 않는다.
|
||||||
- **나가기(공정 처리)**: 카드를 든 사람이 나가면 그 카드를 섞어, 남아 있는 사람들에게 **나간 사람의 다음 자리부터 한 장씩 돌아가며** 나눠 준다(각자 손패 무작위 자리에). 받은 사람은 짝을 자동으로 버리고, 그걸로 0장이 되면 빠진다. 조커가 있었다면 누구에게 갈지 무작위라 특정 사람만 손해 보지 않는다. 나간 사람은 맨 아래 순위. 그 결과 카드 든 사람이 한 명 이하가 되면 **도둑 없이** 끝난다(`reason: resign`, 남은 사람이 나간 사람보다 위). 나간 사람이 차례였으면 다음 자리로 넘어간다.
|
- **나가기(공정 처리)**: 카드를 든 사람이 나가면 그 카드를 섞어, 남아 있는 사람들에게 **나간 사람의 다음 자리부터 한 장씩 돌아가며** 나눠 준다(각자 손패 무작위 자리에). 받은 사람은 짝을 자동으로 버리고, 그걸로 0장이 되면 빠진다. 조커가 있었다면 누구에게 갈지 무작위라 특정 사람만 손해 보지 않는다. 나간 사람은 맨 아래 순위. 그 결과 카드 든 사람이 한 명 이하가 되면 **도둑 없이** 끝난다(`reason: resign`, 남은 사람이 나간 사람보다 위). 나간 사람이 차례였으면 다음 자리로 넘어간다.
|
||||||
- 이미 다 턴 사람이 나가면 아무 변화도 없다(`onLeave` = null, 순위 유지).
|
- 이미 다 턴 사람이 나가면 아무 변화도 없다(`onLeave` = null, 순위 유지).
|
||||||
@@ -88,6 +88,8 @@ interface OldMaidState {
|
|||||||
- 카드를 든 사람이 1명 이하가 되는 순간 끝. `ranking` = 다 턴 그룹들 + [도둑] + [나간 사람들]. `scoreText`는 6절. `reason`은 보통 `normal`, 나가서 끝나면 `resign`.
|
- 카드를 든 사람이 1명 이하가 되는 순간 끝. `ranking` = 다 턴 그룹들 + [도둑] + [나간 사람들]. `scoreText`는 6절. `reason`은 보통 `normal`, 나가서 끝나면 `resign`.
|
||||||
|
|
||||||
## 9. UI/UX
|
## 9. UI/UX
|
||||||
|
|
||||||
|
- 소리·움직임(2026-10-13): 뽑기 = 뽑힌 자리에서 뽑는 자리로 카드가 날아가며 소리, 짝 버리기 = 버린 짝 더미로, 손패 다 털기 = 등수 배너, 섞기 = 섞는 소리, 게임 끝 = "🃏 도둑!" 배너, 시작 = 나눠 주기. 내 행동과 남(컴퓨터 포함)의 행동 모두 view 변화에 반응하고, 처음 들어올 때·새로고침·다시 보기 건너뛰기에는 나지 않는다. 움직임은 0.2~0.6초, 날아가는 카드는 클릭을 막지 않는다. 소리는 사이트 음량을 따르고 합성음만 쓴다(파일 없음). 차례인 자리는 테두리가 은은하게 빛난다.
|
||||||
- 위: 다른 사람 자리 카드(내 다음 자리부터, 즉 내가 뽑을 사람이 맨 앞). 장수(작은 뒷면 묶음), 버린 짝 수, "뽑는 중"/"뽑히는 중"/"🎉 N등"/"🃏 도둑" 배지, 섞으면 "🔀 섞었어요" 말풍선.
|
- 위: 다른 사람 자리 카드(내 다음 자리부터, 즉 내가 뽑을 사람이 맨 앞). 장수(작은 뒷면 묶음), 버린 짝 수, "뽑는 중"/"뽑히는 중"/"🎉 N등"/"🃏 도둑" 배지, 섞으면 "🔀 섞었어요" 말풍선.
|
||||||
- 가운데 초록 테이블: "A ← B의 카드 N장"과 뽑힐 사람의 뒷면 카드를 펼쳐 보여 준다(자리 번호 표시, 많으면 작게 여러 줄). 내 차례면 카드가 버튼이 된다. 터치 기기에서 "두 번 눌러 확인"(설정 `tapConfirm`)이 켜져 있으면 첫 탭은 고르기(카드가 위로), 두 번째 탭에 뽑는다. PC 마우스는 한 번에 뽑는다. 키보드는 좌우 방향키로 고르고 Enter. 뽑힐 사람이 섞으면 펼친 카드가 흔들리고 고른 것이 풀린다.
|
- 가운데 초록 테이블: "A ← B의 카드 N장"과 뽑힐 사람의 뒷면 카드를 펼쳐 보여 준다(자리 번호 표시, 많으면 작게 여러 줄). 내 차례면 카드가 버튼이 된다. 터치 기기에서 "두 번 눌러 확인"(설정 `tapConfirm`)이 켜져 있으면 첫 탭은 고르기(카드가 위로), 두 번째 탭에 뽑는다. PC 마우스는 한 번에 뽑는다. 키보드는 좌우 방향키로 고르고 Enter. 뽑힐 사람이 섞으면 펼친 카드가 흔들리고 고른 것이 풀린다.
|
||||||
- 지난 뽑기: 누가 누구의 몇 번째를 뽑았는지, 짝이 나면 두 장을 앞면으로. 내가 뽑은 카드는 나에게만 앞면으로("뽑은 카드 ♠9 · 짝이 없어서 손에 넣었어요", "앗, 조커를 뽑았어요!"). 최근 버린 짝 6쌍.
|
- 지난 뽑기: 누가 누구의 몇 번째를 뽑았는지, 짝이 나면 두 장을 앞면으로. 내가 뽑은 카드는 나에게만 앞면으로("뽑은 카드 ♠9 · 짝이 없어서 손에 넣었어요", "앗, 조커를 뽑았어요!"). 최근 버린 짝 6쌍.
|
||||||
|
|||||||
@@ -45,7 +45,7 @@
|
|||||||
| `blindUpEvery` | N핸드마다 기본 단위 2배(0=안 올림) | 0 / 5 / 10 / 15 | 0 (`lastStanding` 선택 시 UI가 10을 추천) |
|
| `blindUpEvery` | N핸드마다 기본 단위 2배(0=안 올림) | 0 / 5 / 10 / 15 | 0 (`lastStanding` 선택 시 UI가 10을 추천) |
|
||||||
| `rebuy` | 리바이(재충전) | `off` / `limited` / `unlimited` | `unlimited` (`lastStanding` 선택 시 UI가 `off`를 추천) |
|
| `rebuy` | 리바이(재충전) | `off` / `limited` / `unlimited` | `unlimited` (`lastStanding` 선택 시 UI가 `off`를 추천) |
|
||||||
| `rebuyLimit` | `limited`일 때 1인당 횟수 | 1 / 2 / 3 | 1 |
|
| `rebuyLimit` | `limited`일 때 1인당 횟수 | 1 / 2 / 3 | 1 |
|
||||||
| `turnSeconds` | 행동 제한 시간(초) | 15 / 20 / 30 / 60 | 20 |
|
| `turnSeconds` | 행동 제한 시간(초) | 15 / 20 / 30 / 60 / 무제한(`null`) | 20 |
|
||||||
| `dealerRule` | 다음 핸드 딜러(선) 결정 | `rotate`(시계 방향 회전) / `winner`(직전 승자) | `rotate` |
|
| `dealerRule` | 다음 핸드 딜러(선) 결정 | `rotate`(시계 방향 회전) / `winner`(직전 승자) | `rotate` |
|
||||||
| `hints` | 현재 족보 표시·추천 행동 하이라이트 | 켬 / 끔 | 켬 |
|
| `hints` | 현재 족보 표시·추천 행동 하이라이트 | 켬 / 끔 | 켬 |
|
||||||
| `hiLoLow` | 하이로우 로우 판정 방식 | `korean`(스트레이트·플러시 불인정, 최고 로우 A-2-3-4-6) / `aceToFive`(스트레이트·플러시 무시, 최고 로우 A-2-3-4-5) | `korean` |
|
| `hiLoLow` | 하이로우 로우 판정 방식 | `korean`(스트레이트·플러시 불인정, 최고 로우 A-2-3-4-6) / `aceToFive`(스트레이트·플러시 무시, 최고 로우 A-2-3-4-5) | `korean` |
|
||||||
@@ -227,7 +227,7 @@
|
|||||||
|
|
||||||
- 핸드 종료 후 칩이 0인 플레이어는 `busted`.
|
- 핸드 종료 후 칩이 0인 플레이어는 `busted`.
|
||||||
- `rebuy=off`: 즉시 탈락(`eliminated`), 관전 화면으로 전환되지만 결과 순위에는 남는다.
|
- `rebuy=off`: 즉시 탈락(`eliminated`), 관전 화면으로 전환되지만 결과 순위에는 남는다.
|
||||||
- `rebuy=limited/unlimited`(남은 횟수 있음): 리바이 단계에서 "칩 다시 받기 / 그만하기"를 고른다(제한 시간 15초, 시간 초과는 그만하기). 받으면 `startingChips`로 채우고 `rebuys += 1`. `endCondition=hands`에서 마지막 핸드가 끝난 직후에는 리바이를 묻지 않는다.
|
- `rebuy=limited/unlimited`(남은 횟수 있음): 리바이 단계에서 "칩 다시 받기 / 그만하기"를 고른다(제한 시간 `rebuySeconds` 10/15/30초 또는 무제한, 기본 15초, 시간 초과는 그만하기). 받으면 `startingChips`로 채우고 `rebuys += 1`. `endCondition=hands`에서 마지막 핸드가 끝난 직후에는 리바이를 묻지 않는다.
|
||||||
- 칩이 남아 있어도 앤티/블라인드보다 적으면 그대로 참가하고 강제 베팅에서 올인된다(리바이는 0일 때만).
|
- 칩이 남아 있어도 앤티/블라인드보다 적으면 그대로 참가하고 강제 베팅에서 올인된다(리바이는 0일 때만).
|
||||||
- 리바이는 실제 재화와 무관한 방 내부 칩 보충이다.
|
- 리바이는 실제 재화와 무관한 방 내부 칩 보충이다.
|
||||||
|
|
||||||
@@ -391,7 +391,7 @@ interface PokerOptions {
|
|||||||
blindUpEvery: 0 | 5 | 10 | 15;
|
blindUpEvery: 0 | 5 | 10 | 15;
|
||||||
rebuy: 'off' | 'limited' | 'unlimited';
|
rebuy: 'off' | 'limited' | 'unlimited';
|
||||||
rebuyLimit: 1 | 2 | 3;
|
rebuyLimit: 1 | 2 | 3;
|
||||||
turnSeconds: 15 | 20 | 30 | 60;
|
turnSeconds: 15 | 20 | 30 | 60 | null;
|
||||||
dealerRule: 'rotate' | 'winner';
|
dealerRule: 'rotate' | 'winner';
|
||||||
hints: boolean;
|
hints: boolean;
|
||||||
hiLoLow: 'korean' | 'aceToFive';
|
hiLoLow: 'korean' | 'aceToFive';
|
||||||
@@ -556,8 +556,8 @@ interface PokerState {
|
|||||||
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
||||||
|
|
||||||
`deadline(state)`:
|
`deadline(state)`:
|
||||||
- 베팅: `turnSeconds`(자리 비움이면 5초).
|
- 베팅: `turnSeconds`(자리 비움이면 5초). 무제한(`null`)이면 시계 없음(자리 비움만 짧은 시계). 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 행동.
|
||||||
- 7포커 초이스·교환·선언: `turnSeconds + 10`초(동시 단계, 모두에게 같은 마감).
|
- 7포커 초이스·교환·선언: `turnSeconds + 10`초(동시 단계, 모두에게 같은 마감). 무제한이면 마감 없음(기다리는 사람이 모두 자리 비움일 때만 짧은 시계).
|
||||||
- `handEnd`: 4초. 리바이 결정: 15초.
|
- `handEnd`: 4초. 리바이 결정: 15초.
|
||||||
|
|
||||||
`onTimeout(state, player)`:
|
`onTimeout(state, player)`:
|
||||||
@@ -600,6 +600,8 @@ interface PokerResult /* extends GameResult */ {
|
|||||||
|
|
||||||
## 9. UI/UX
|
## 9. UI/UX
|
||||||
|
|
||||||
|
- 소리·움직임(2026-10-13): 새 판 = 섞고 기본 칩이 가운데로, 카드가 가운데에서 모두에게, 베팅 = 칩이 자리에서 가운데로(금액만큼 개수), 체크 = 두드림, 다이 = 카드가 가운데로 밀려남, 올인 배너, 카드 바꾸기 = 버리고 새로 받음, 공용 카드·쇼다운 = 한 장씩 뒤집힘, 모인 칩 = 이긴 사람에게 날아가며 모으는 소리, 칩 다시 받기 = 동전. 내 행동과 남(컴퓨터 포함)의 행동 모두 view 변화에 반응하고, 처음 들어올 때·새로고침·다시 보기 건너뛰기에는 나지 않는다. 움직임은 0.2~0.6초, 날아가는 카드는 클릭을 막지 않는다. 소리는 사이트 음량을 따르고 합성음만 쓴다(파일 없음). 차례인 자리는 테두리가 은은하게 빛난다.
|
||||||
|
|
||||||
화면 배치(모바일 세로):
|
화면 배치(모바일 세로):
|
||||||
- 위쪽 2/3: 테이블. 상대 플레이어는 위·양옆 호 모양으로 배치(닉네임, 스택, 이번 라운드 베팅액, 오픈 카드 축소판, 상태 뱃지 "다이"/"올인"/"자리 비움"). 10명이면 2줄 축소 배치.
|
- 위쪽 2/3: 테이블. 상대 플레이어는 위·양옆 호 모양으로 배치(닉네임, 스택, 이번 라운드 베팅액, 오픈 카드 축소판, 상태 뱃지 "다이"/"올인"/"자리 비움"). 10명이면 2줄 축소 배치.
|
||||||
- 가운데: 판돈 큰 숫자, 사이드 팟은 작은 칩 더미와 금액, 공용 카드 5칸(홀덤·오마하).
|
- 가운데: 판돈 큰 숫자, 사이드 팟은 작은 칩 더미와 금액, 공용 카드 5칸(홀덤·오마하).
|
||||||
|
|||||||
@@ -265,6 +265,8 @@ interface SplendorResult {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## 9. UI/UX
|
## 9. UI/UX
|
||||||
|
|
||||||
|
- 소리·움직임(2026-10-13): 보석 가져오기 = 은행 칩이 그 색 칸으로 날아가며 보석 소리, 10개 넘어 돌려주기 = 은행으로, 카드 사기 = 시장(또는 예약)에서 그 사람 색 칸으로 날아가고 낸 보석은 은행으로, 시장 채우기 = 더미에서 새 카드가 날아옴, 예약 = 카드와 황금 칩, 귀족 방문 = 귀족 타일이 날아가며 "👑 귀족 방문!" 배너와 종소리, 목표 점수 = "🏁 마지막 라운드!" 배너, 게임 끝 배너. 내 행동과 남(컴퓨터 포함)의 행동 모두 view 변화에 반응하고, 처음 들어올 때·새로고침·다시 보기 건너뛰기에는 나지 않는다. 움직임은 0.2~0.6초, 날아가는 카드는 클릭을 막지 않는다. 소리는 사이트 음량을 따르고 합성음만 쓴다(파일 없음). 차례인 자리는 테두리가 은은하게 빛난다.
|
||||||
- 모바일 세로: 맨 위 귀족 줄(작은 타일, 요구 보너스 아이콘), 그 아래 3단계 → 1단계 순 카드 3줄(줄마다 더미 + 공개 4장, 가로 폭에 맞춘 카드 최소 72px 너비), 그 아래 공급처 토큰 6개(원형 56px), 맨 아래 내 영역(보너스·토큰·예약 카드·점수). 다른 플레이어는 상단 탭/요약 칩으로, 누르면 펼침.
|
- 모바일 세로: 맨 위 귀족 줄(작은 타일, 요구 보너스 아이콘), 그 아래 3단계 → 1단계 순 카드 3줄(줄마다 더미 + 공개 4장, 가로 폭에 맞춘 카드 최소 72px 너비), 그 아래 공급처 토큰 6개(원형 56px), 맨 아래 내 영역(보너스·토큰·예약 카드·점수). 다른 플레이어는 상단 탭/요약 칩으로, 누르면 펼침.
|
||||||
- 조작: 토큰을 차례로 누르면 선택 바구니에 담기고 "가져오기" 버튼 활성(같은 색 두 번 누르면 2개 가져오기로 자동 전환, 불가하면 흔들림 + 이유 표시). 카드를 누르면 "구매 / 예약" 큰 버튼 두 개가 뜨고, 구매 시 자동 지불 내역 미리보기(황금 사용 수 표시), "지불 방법 바꾸기"로 수동 조정.
|
- 조작: 토큰을 차례로 누르면 선택 바구니에 담기고 "가져오기" 버튼 활성(같은 색 두 번 누르면 2개 가져오기로 자동 전환, 불가하면 흔들림 + 이유 표시). 카드를 누르면 "구매 / 예약" 큰 버튼 두 개가 뜨고, 구매 시 자동 지불 내역 미리보기(황금 사용 수 표시), "지불 방법 바꾸기"로 수동 조정.
|
||||||
- 합법 수 하이라이트: 지금 살 수 있는 카드에 초록 테두리, 황금을 써야 살 수 있으면 금색 테두리. 귀족 타일에 "남은 보너스 2" 표시.
|
- 합법 수 하이라이트: 지금 살 수 있는 카드에 초록 테두리, 황금을 써야 살 수 있으면 금색 테두리. 귀족 타일에 "남은 보너스 2" 표시.
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
| `wild4Rule` | 와일드 드로우4 | `challenge`(공식: 몰래 낼 수 있고 다음 사람이 도전) / `strict`(쉬운 규칙: 지금 색 카드가 있으면 못 냄, 도전 없음) | `challenge` |
|
| `wild4Rule` | 와일드 드로우4 | `challenge`(공식: 몰래 낼 수 있고 다음 사람이 도전) / `strict`(쉬운 규칙: 지금 색 카드가 있으면 못 냄, 도전 없음) | `challenge` |
|
||||||
| `stacking` | (하우스 룰) 드로우 카드 쌓기 | on / off | off |
|
| `stacking` | (하우스 룰) 드로우 카드 쌓기 | on / off | off |
|
||||||
| `drawUntilPlayable` | (하우스 룰) 낼 수 있을 때까지 뽑기 | on / off | off |
|
| `drawUntilPlayable` | (하우스 룰) 낼 수 있을 때까지 뽑기 | on / off | off |
|
||||||
| `turnSeconds` | 턴 제한 시간 | 10 / 15 / 20 / 30 / 60초 | 20 |
|
| `turnSeconds` | 턴 제한 시간 | 10 / 15 / 20 / 30 / 60초 / 무제한(`null`) | 20 |
|
||||||
|
|
||||||
- 손패는 공식대로 7장 고정, "우노" 벌칙은 공식대로 2장 고정이다.
|
- 손패는 공식대로 7장 고정, "우노" 벌칙은 공식대로 2장 고정이다.
|
||||||
- 일부러 넣지 않은 것: 7-0 규칙(7로 손패 교환, 0으로 모두 돌리기), 점프인, 쇼앰 노머시 카드, 낮은 점수 방식(각자 자기 남은 점수를 쌓는 변형), 팀전.
|
- 일부러 넣지 않은 것: 7-0 규칙(7로 손패 교환, 0으로 모두 돌리기), 점프인, 쇼앰 노머시 카드, 낮은 점수 방식(각자 자기 남은 점수를 쌓는 변형), 팀전.
|
||||||
@@ -145,7 +145,7 @@ interface UnoState {
|
|||||||
- `setup`: 첫 사람(`rng.int`) → 덱 섞기 → 시작 드로우4면 다시 섞기.
|
- `setup`: 첫 사람(`rng.int`) → 덱 섞기 → 시작 드로우4면 다시 섞기.
|
||||||
- 더미가 비었을 때 버린 카드 섞기, 다음 판 덱 섞기. 모두 `ctx.rng`.
|
- 더미가 비었을 때 버린 카드 섞기, 다음 판 덱 섞기. 모두 `ctx.rng`.
|
||||||
### 8.5 타이머·시간 초과·연결 끊김
|
### 8.5 타이머·시간 초과·연결 끊김
|
||||||
- 제한 시간 = `turnSeconds`(시작 색·도전 답도 같음). 판 사이 8초. 시간 초과가 3번 이어지면 "자리 비움"이 되어 5초만 기다린다(직접 행동하면 풀림).
|
- 제한 시간 = `turnSeconds`(시작 색·도전 답도 같음). 무제한(`null`)이면 차례 시계가 없고 타이머도 안 보인다. 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 행동(아래 자리 비움 포함)이 그대로 적용된다. 판 사이 8초. 시간 초과가 3번 이어지면 "자리 비움"이 되어 5초만 기다린다(직접 행동하면 풀림).
|
||||||
- 시간 초과 자동 행동(원카드 관례: 낼 수 있으면 낸다)
|
- 시간 초과 자동 행동(원카드 관례: 낼 수 있으면 낸다)
|
||||||
- `turn`: 쌓인 드로우가 있으면 다 먹는다(자동으로 쌓지 않음). 아니면 낼 수 있는 카드 중 색 카드를 먼저(손패 순서 첫 장), 없으면 와일드, 그다음 규칙에 맞는 와일드 드로우4를 낸다. 와일드 색은 남은 손패에 가장 많은 색(같으면 빨강·노랑·초록·파랑 순). 낼 카드가 없으면 1장(하우스 룰이면 나올 때까지) 뽑고, 뽑은 카드가 맞으면 바로 낸다.
|
- `turn`: 쌓인 드로우가 있으면 다 먹는다(자동으로 쌓지 않음). 아니면 낼 수 있는 카드 중 색 카드를 먼저(손패 순서 첫 장), 없으면 와일드, 그다음 규칙에 맞는 와일드 드로우4를 낸다. 와일드 색은 남은 손패에 가장 많은 색(같으면 빨강·노랑·초록·파랑 순). 낼 카드가 없으면 1장(하우스 룰이면 나올 때까지) 뽑고, 뽑은 카드가 맞으면 바로 낸다.
|
||||||
- `afterDraw`: 뽑은 카드가 규칙에 맞으면 내고, 아니면(어긋난 드로우4) 넘긴다.
|
- `afterDraw`: 뽑은 카드가 규칙에 맞으면 내고, 아니면(어긋난 드로우4) 넘긴다.
|
||||||
@@ -164,6 +164,7 @@ interface UnoState {
|
|||||||
- 오른쪽: 규칙 요약 한 줄, 자리 목록, 최종 순위, 기록, 특수 카드 표.
|
- 오른쪽: 규칙 요약 한 줄, 자리 목록, 최종 순위, 기록, 특수 카드 표.
|
||||||
- 도움말: 30초 요약 3장(맞추기, 특수 카드, 우노!), [?] 지금 할 수 있는 것.
|
- 도움말: 30초 요약 3장(맞추기, 특수 카드, 우노!), [?] 지금 할 수 있는 것.
|
||||||
- 카드 그림은 원카드 색깔 카드 그림을 그대로 쓴다(흰 마름모, 색마다 무늬). 와일드 카드 아래 글자는 "색 바꾸기"로 나온다.
|
- 카드 그림은 원카드 색깔 카드 그림을 그대로 쓴다(흰 마름모, 색마다 무늬). 와일드 카드 아래 글자는 "색 바꾸기"로 나온다.
|
||||||
|
- 소리·움직임(2026-10-13, 내 행동과 남의 행동 모두 view 변화에 반응, 처음 들어올 때·다시 보기 건너뛰기에는 안 남): 카드 내기 = 낸 사람 자리(내 카드는 누른 자리)에서 버린 더미로 날아가며 "착" 소리, 와일드는 아르페지오, 드로우2·드로우4는 낮은 "쿵"과 "+2"/"+4" 배너. 뽑기 = 더미에서 내 손패/상대 자리로 카드가 날아가고 뽑는 소리, 벌칙·쌓인 장수를 먹으면 자리가 흔들림. 우노! = 큰 "우노!" 배너와 팡파르, 잡기 = "잡았다!" 배너와 경고음, 도전 성공/실패 배너. 스킵 = 건너뛴 자리 흔들림, 리버스 = 방향 화살표가 튀며 올라갔다 내려가는 소리, 더미 다시 섞기 = 섞는 소리. 판 시작 = 섞고 돌리는 소리와 함께 카드가 더미에서 모두에게, 판 끝 = 다른 자리 카드가 이긴 사람에게 모이며 모으는 소리. 차례인 자리는 테두리가 은은하게 빛나고, 바뀐 지금 색 칩은 튀어나온다. 소리는 사이트 음량을 따르고, 움직임 줄이기 설정이면 움직임은 생략된다.
|
||||||
|
|
||||||
### 9.1 컴퓨터 상대 (`packages/games/src/uno/bot.ts`)
|
### 9.1 컴퓨터 상대 (`packages/games/src/uno/bot.ts`)
|
||||||
- 공통: 낼 수 있는 카드 중 점수를 매겨 고른다(`humanBest`로 레벨만큼 가끔 실수). 와일드는 아끼고, 같은 색이 많이 남는 카드, 높은 숫자를 먼저 낸다. 다음 사람이 2장 이하면 스킵·리버스·드로우2·드로우4를 먼저 쓴다. 고르는 색은 남은 손패에 가장 많은 색(같으면 무작위).
|
- 공통: 낼 수 있는 카드 중 점수를 매겨 고른다(`humanBest`로 레벨만큼 가끔 실수). 와일드는 아끼고, 같은 색이 많이 남는 카드, 높은 숫자를 먼저 낸다. 다음 사람이 2장 이하면 스킵·리버스·드로우2·드로우4를 먼저 쓴다. 고르는 색은 남은 손패에 가장 많은 색(같으면 무작위).
|
||||||
|
|||||||
@@ -2254,7 +2254,8 @@ const PLANS: Record<string, Plan> = {
|
|||||||
players: 3,
|
players: 3,
|
||||||
lobby: async (host) => {
|
lobby: async (host) => {
|
||||||
await host.getByRole('group', { name: '같은 벌레 몇 장이면 패배' }).getByRole('button', { name: '3장(짧게)' }).click();
|
await host.getByRole('group', { name: '같은 벌레 몇 장이면 패배' }).getByRole('button', { name: '3장(짧게)' }).click();
|
||||||
await host.getByText(/같은 벌레 3장이면 패배/).first().waitFor();
|
await host.getByRole('group', { name: '건네기·판정 제한 시간' }).getByRole('button', { name: '무제한' }).click();
|
||||||
|
await host.getByText(/같은 벌레 3장이면 패배.*시간 무제한/).first().waitFor();
|
||||||
},
|
},
|
||||||
drive: async (pages) => {
|
drive: async (pages) => {
|
||||||
const [host, guest] = pages as [Page, Page, Page];
|
const [host, guest] = pages as [Page, Page, Page];
|
||||||
@@ -2303,16 +2304,16 @@ const PLANS: Record<string, Plan> = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
'ninety-nine': {
|
'ninety-nine': {
|
||||||
// PC host + 2 phones, 전용 카드 with 6 of each special card and 30-second turns. Real turns through the UI until the
|
// PC host + 2 phones, 전용 카드 with 6 of each special card and no turn clock (무제한: no timer anywhere). Real turns through the UI until the
|
||||||
// game ends: joker via the number dial (quick 99, then −1), ± cards via their +/− buttons, 0 with its keep/reverse
|
// game ends: joker via the number dial (quick 99, then −1), ± cards via their +/− buttons, 0 with its keep/reverse
|
||||||
// direction buttons, otherwise a number card (PC: keyboard Enter twice, phones: tap twice). 3 players start at 20
|
// direction buttons, otherwise a number card (PC: keyboard Enter twice, phones: tap twice). 3 players start at 20
|
||||||
// with 5 cards each (official rules). Players run out of cards and are eliminated.
|
// with 5 cards each (official rules). Players run out of cards and are eliminated.
|
||||||
players: 3,
|
players: 3,
|
||||||
lobby: async (host) => {
|
lobby: async (host) => {
|
||||||
await host.getByRole('group', { name: '한 턴 제한 시간' }).getByRole('button', { name: '30초' }).click();
|
await host.getByRole('group', { name: '한 턴 제한 시간' }).getByRole('button', { name: '무제한' }).click();
|
||||||
await host.getByRole('button', { name: '▼ 자세한 설정' }).click();
|
await host.getByRole('button', { name: '▼ 자세한 설정' }).click();
|
||||||
await host.getByRole('group', { name: '특수 카드 장수' }).getByRole('button', { name: '6장' }).click();
|
await host.getByRole('group', { name: '특수 카드 장수' }).getByRole('button', { name: '6장' }).click();
|
||||||
await host.getByText(/^전용 카드 · 손패 5장 · 목숨 없음 · 30초/).first().waitFor();
|
await host.getByText(/^전용 카드 · 손패 5장 · 목숨 없음 · 시간 무제한/).first().waitFor();
|
||||||
},
|
},
|
||||||
drive: async (pages) => {
|
drive: async (pages) => {
|
||||||
const [host, guest] = pages as [Page, Page, Page];
|
const [host, guest] = pages as [Page, Page, Page];
|
||||||
@@ -2333,6 +2334,7 @@ const PLANS: Record<string, Plan> = {
|
|||||||
if (!shot && turns >= 5) {
|
if (!shot && turns >= 5) {
|
||||||
shot = true;
|
shot = true;
|
||||||
await host.waitForTimeout(500);
|
await host.waitForTimeout(500);
|
||||||
|
for (const p of pages) if (await p.getByRole('timer').count()) throw new Error('무제한 room still shows a turn timer');
|
||||||
await host.screenshot({ path: join(SHOTS, 'ninety-nine-mid-pc.png') });
|
await host.screenshot({ path: join(SHOTS, 'ninety-nine-mid-pc.png') });
|
||||||
await guest.screenshot({ path: join(SHOTS, 'ninety-nine-mid-phone.png') });
|
await guest.screenshot({ path: join(SHOTS, 'ninety-nine-mid-phone.png') });
|
||||||
await guest.screenshot({ path: join(SHOTS, 'ninety-nine-mid-phone-full.png'), fullPage: true });
|
await guest.screenshot({ path: join(SHOTS, 'ninety-nine-mid-phone-full.png'), fullPage: true });
|
||||||
|
|||||||
@@ -1053,7 +1053,7 @@ describe('시간 초과·자리 비움·나가기 (§8.5)', () => {
|
|||||||
const c = pool();
|
const c = pool();
|
||||||
const g = c('gatling');
|
const g = c('gatling');
|
||||||
let s = rig({ players: basic({ A: { hand: [g] }, B: { life: 1, hand: [c('beer')] } }) });
|
let s = rig({ players: basic({ A: { hand: [g] }, B: { life: 1, hand: [c('beer')] } }) });
|
||||||
const before = s.turn.deadline;
|
const before = s.turn.deadline!;
|
||||||
s = play(s, 'A', g);
|
s = play(s, 'A', g);
|
||||||
const paused = clock;
|
const paused = clock;
|
||||||
s = act(s, 'B', { type: 'takeHit' });
|
s = act(s, 'B', { type: 'takeHit' });
|
||||||
@@ -1083,7 +1083,7 @@ describe('시간 초과·자리 비움·나가기 (§8.5)', () => {
|
|||||||
// Next time it is A's turn the limit is 5 s.
|
// Next time it is A's turn the limit is 5 s.
|
||||||
for (const p of ['B', 'C', 'D']) x = act(x, p, { type: 'timeout' });
|
for (const p of ['B', 'C', 'D']) x = act(x, p, { type: 'timeout' });
|
||||||
expect(x.turn.player).toBe('A');
|
expect(x.turn.player).toBe('A');
|
||||||
expect(x.turn.deadline - clock).toBe(5000);
|
expect(x.turn.deadline! - clock).toBe(5000);
|
||||||
x = act(x, 'A', { type: 'endPlay' });
|
x = act(x, 'A', { type: 'endPlay' });
|
||||||
expect(pl(x, 'A').away).toBe(false);
|
expect(pl(x, 'A').away).toBe(false);
|
||||||
});
|
});
|
||||||
@@ -1111,6 +1111,73 @@ describe('시간 초과·자리 비움·나가기 (§8.5)', () => {
|
|||||||
expect(s.reactions.map((r) => (r.kind === 'indians' ? r.target : ''))).toEqual(['B', 'D']);
|
expect(s.reactions.map((r) => (r.kind === 'indians' ? r.target : ''))).toEqual(['B', 'D']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('무제한 (turnSeconds·reactionSeconds null): 시계 없음, 연결이 끊긴 사람은 여전히 자동 처리, 자리 비움은 5초', () => {
|
||||||
|
const shape = (bang.optionsSchema as unknown as { shape: Record<string, { meta(): { labels?: Record<string, string> } | undefined }> }).shape;
|
||||||
|
expect(shape.turnSeconds!.meta()?.labels?.null).toBe('무제한');
|
||||||
|
expect(shape.reactionSeconds!.meta()?.labels?.null).toBe('무제한');
|
||||||
|
expect(bang.optionsSchema.safeParse({ turnSeconds: null, reactionSeconds: null }).success).toBe(true);
|
||||||
|
expect(bang.defaultOptions).toMatchObject({ turnSeconds: 60, reactionSeconds: 15 });
|
||||||
|
const options = { turnSeconds: null, reactionSeconds: null };
|
||||||
|
const c = pool();
|
||||||
|
const ind = c('indians');
|
||||||
|
const bg = c('bang');
|
||||||
|
let s = rig({ players: basic({ A: { hand: [ind, bg, c('mustang'), c('scope'), c('barrel'), c('jail'), c('volcanic'), c('beer'), c('beer')] }, C: { hand: [c('bang')] } }), options });
|
||||||
|
s.turn.deadline = null;
|
||||||
|
expect(bang.deadline!(s)).toBeNull();
|
||||||
|
expect(bang.timeoutPlayers!(s)).toEqual(['A']);
|
||||||
|
expect(bang.view(s, 'A')).toMatchObject({ turnDeadline: null, deadlineTotalMs: 5000, reactionTotalMs: 5000 });
|
||||||
|
// 인디언: every reaction is unclocked, so every responder is listed (the room's disconnect grace times each one out).
|
||||||
|
s = play(s, 'A', ind);
|
||||||
|
expect(s.reactions.map((r) => r.deadline)).toEqual([null, null, null]);
|
||||||
|
expect(bang.deadline!(s)).toBeNull();
|
||||||
|
expect(bang.timeoutPlayers!(s).sort()).toEqual(['B', 'C', 'D']);
|
||||||
|
expect(bang.view(s, 'B').reactions.every((r) => r.deadline === null)).toBe(true);
|
||||||
|
expect(JSON.parse(JSON.stringify(s))).toEqual(s);
|
||||||
|
s = act(s, 'C', { type: 'timeout' });
|
||||||
|
expect(s.log.some((e) => e.t === 'respond' && e.p === 'C' && e.why === 'indians')).toBe(true);
|
||||||
|
s = act(s, 'B', { type: 'timeout' });
|
||||||
|
expect(pl(s, 'B').life).toBe(pl(s, 'B').maxLife - 1);
|
||||||
|
s = act(s, 'D', { type: 'takeHit' });
|
||||||
|
// The turn clock stays off after the reactions (pause arithmetic skips null).
|
||||||
|
expect(s.reactions).toEqual([]);
|
||||||
|
expect(s.turn).toMatchObject({ deadline: null, pausedAt: null });
|
||||||
|
// 뱅! at an away player: only that reaction has a clock (5 s), so only they are timed.
|
||||||
|
pl(s, 'B').away = true;
|
||||||
|
s = play(s, 'A', bg, { target: 'B' });
|
||||||
|
expect(s.reactions[0]!.deadline).toBe(clock + 5000);
|
||||||
|
expect(bang.deadline!(s)).toBe(clock + 5000);
|
||||||
|
expect(bang.timeoutPlayers!(s)).toEqual(['B']);
|
||||||
|
s = act(s, 'B', { type: 'timeout' });
|
||||||
|
// Hand over the limit → discard phase, still unclocked; a timeout discards at random.
|
||||||
|
s = act(s, 'A', { type: 'endPlay' });
|
||||||
|
expect(s.turn).toMatchObject({ phase: 'discard', deadline: null });
|
||||||
|
s = act(s, 'A', { type: 'timeout' });
|
||||||
|
expect(s.turn.player).toBe('B');
|
||||||
|
// B is away → the short clock on its own turn; C (not away) gets no clock.
|
||||||
|
expect(s.turn.deadline! - clock).toBe(5000);
|
||||||
|
expect(bang.deadline!(s)).toBe(s.turn.deadline);
|
||||||
|
s = act(s, 'B', { type: 'timeout' });
|
||||||
|
expect(s.turn.player).toBe('C');
|
||||||
|
expect(s.turn.deadline).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('무제한: choose2 캐릭터 고르기도 시계 없음, 시간 초과(연결 끊김) 시 첫 번째 카드', () => {
|
||||||
|
const players = ['A', 'B', 'C', 'D'];
|
||||||
|
let s = bang.setup({ players, options: bang.optionsSchema.parse({ characterDraft: 'choose2', turnSeconds: null }), rng: SeededRng.fromSeed(seedN(5)), now: 0 });
|
||||||
|
expect(s.reactions.every((r) => r.kind === 'choose2' && r.deadline === null)).toBe(true);
|
||||||
|
expect(bang.deadline!(s)).toBeNull();
|
||||||
|
expect(bang.timeoutPlayers!(s).sort()).toEqual(players);
|
||||||
|
const offer = pl(s, 'B').characterOffer!;
|
||||||
|
s = act(s, 'B', { type: 'timeout' });
|
||||||
|
expect(pl(s, 'B').character).toBe(offer[0]!);
|
||||||
|
for (const p of ['A', 'C', 'D']) s = act(s, p, { type: 'timeout' });
|
||||||
|
expect(s.turn.phase).not.toBe('draft');
|
||||||
|
expect(s.turn.deadline).toBeNull();
|
||||||
|
// Timed draft keeps its 30 s clock.
|
||||||
|
const t = bang.setup({ players, options: bang.optionsSchema.parse({ characterDraft: 'choose2' }), rng: SeededRng.fromSeed(seedN(5)), now: 0 });
|
||||||
|
expect(bang.deadline!(t)).toBe(30_000);
|
||||||
|
});
|
||||||
|
|
||||||
test('onTimeout은 모든 상태에서 합법 행동', () => {
|
test('onTimeout은 모든 상태에서 합법 행동', () => {
|
||||||
for (let seed = 1; seed <= 40; seed++) {
|
for (let seed = 1; seed <= 40; seed++) {
|
||||||
const players = ['A', 'B', 'C', 'D', 'E'];
|
const players = ['A', 'B', 'C', 'D', 'E'];
|
||||||
@@ -1261,6 +1328,7 @@ const PRESETS: Partial<BangOptions>[] = [
|
|||||||
{ autoDefend: false, drawBeforeDeath: true },
|
{ autoDefend: false, drawBeforeDeath: true },
|
||||||
{ beerAtFullHealth: true, selfTargetCatBalou: true, deputyCount7: true },
|
{ beerAtFullHealth: true, selfTargetCatBalou: true, deputyCount7: true },
|
||||||
{ characterDraft: 'choose2', autoBarrel: false, autoDefend: false, reactionSeconds: 8 },
|
{ characterDraft: 'choose2', autoBarrel: false, autoDefend: false, reactionSeconds: 8 },
|
||||||
|
{ characterDraft: 'choose2', turnSeconds: null, reactionSeconds: null },
|
||||||
];
|
];
|
||||||
|
|
||||||
const SEEDS = playoutSeeds(1000);
|
const SEEDS = playoutSeeds(1000);
|
||||||
@@ -1297,6 +1365,7 @@ describe(`무작위 대국 (시드 ${SEEDS}개, 4~7명)`, () => {
|
|||||||
[5, { characterDraft: 'choose2' }],
|
[5, { characterDraft: 'choose2' }],
|
||||||
[6, { autoBarrel: false }],
|
[6, { autoBarrel: false }],
|
||||||
[7, { drawBeforeDeath: true }],
|
[7, { drawBeforeDeath: true }],
|
||||||
|
[5, { turnSeconds: null, reactionSeconds: null, characterDraft: 'choose2' }],
|
||||||
] as const)('randomPlayout with the engine per-step leak / round-trip checks: %i players', (n, opts) => {
|
] as const)('randomPlayout with the engine per-step leak / round-trip checks: %i players', (n, opts) => {
|
||||||
const players = Array.from({ length: n }, (_, k) => `P${k}`);
|
const players = Array.from({ length: n }, (_, k) => `P${k}`);
|
||||||
const options = bang.optionsSchema.parse(opts);
|
const options = bang.optionsSchema.parse(opts);
|
||||||
|
|||||||
@@ -71,12 +71,15 @@ export function clockwiseFrom(s: BangState, from: PlayerId): PlayerId[] {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function reactionMs(s: BangState, p: PlayerState): number {
|
/** Clock lengths in ms; null = 무제한 (an away player still gets the short clock). */
|
||||||
return p.away ? AWAY_MS : s.options.reactionSeconds * 1000;
|
export function reactionMs(s: BangState, p: PlayerState): number | null {
|
||||||
|
return p.away ? AWAY_MS : s.options.reactionSeconds === null ? null : s.options.reactionSeconds * 1000;
|
||||||
}
|
}
|
||||||
export function turnMs(s: BangState, p: PlayerState): number {
|
export function turnMs(s: BangState, p: PlayerState): number | null {
|
||||||
return p.away ? AWAY_MS : s.options.turnSeconds * 1000;
|
return p.away ? AWAY_MS : s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000;
|
||||||
}
|
}
|
||||||
|
/** Absolute deadline `ms` from now; null stays null (never Infinity — state is JSON). */
|
||||||
|
export const after = (ctx: Ctx, ms: number | null): number | null => (ms === null ? null : ctx.now + ms);
|
||||||
|
|
||||||
/** Cards kept inside reactions (general store, Kit Carlson) — counted for conservation. */
|
/** Cards kept inside reactions (general store, Kit Carlson) — counted for conservation. */
|
||||||
export function limboCards(s: BangState): string[] {
|
export function limboCards(s: BangState): string[] {
|
||||||
@@ -211,7 +214,7 @@ export function maxRecovery(s: BangState, p: PlayerState): number {
|
|||||||
|
|
||||||
function openDying(s: BangState, ctx: Ctx, t: PlayerState, killer: PlayerId | null, lost: number): void {
|
function openDying(s: BangState, ctx: Ctx, t: PlayerState, killer: PlayerId | null, lost: number): void {
|
||||||
if (maxRecovery(s, t) >= 1 - t.life) {
|
if (maxRecovery(s, t) >= 1 - t.life) {
|
||||||
s.reactions.push({ kind: 'dying', player: t.id, killer, lost, source: killer, deadline: ctx.now + reactionMs(s, t) });
|
s.reactions.push({ kind: 'dying', player: t.id, killer, lost, source: killer, deadline: after(ctx, reactionMs(s, t)) });
|
||||||
} else {
|
} else {
|
||||||
eliminate(s, ctx, t.id, killer);
|
eliminate(s, ctx, t.id, killer);
|
||||||
}
|
}
|
||||||
@@ -351,7 +354,7 @@ function finish(s: BangState, ctx: Ctx, team: Team): void {
|
|||||||
export function startTurn(s: BangState, ctx: Ctx, id: PlayerId): void {
|
export function startTurn(s: BangState, ctx: Ctx, id: PlayerId): void {
|
||||||
const p = P(s, id);
|
const p = P(s, id);
|
||||||
if (p.role === 'sheriff') s.round += 1;
|
if (p.role === 'sheriff') s.round += 1;
|
||||||
s.turn = { player: id, phase: 'start', bangsPlayed: 0, deadline: ctx.now + turnMs(s, p), pausedAt: null, dynamiteChecked: false, jailChecked: false };
|
s.turn = { player: id, phase: 'start', bangsPlayed: 0, deadline: after(ctx, turnMs(s, p)), pausedAt: null, dynamiteChecked: false, jailChecked: false };
|
||||||
log(s, ctx, { t: 'turn', p: id, round: s.round });
|
log(s, ctx, { t: 'turn', p: id, round: s.round });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -428,7 +431,7 @@ export function doDraw(s: BangState, ctx: Ctx, a: { jesseFrom?: PlayerId; pedroD
|
|||||||
p.hand.push(...options);
|
p.hand.push(...options);
|
||||||
if (options.length) log(s, ctx, { t: 'draw', p: p.id, n: options.length, why: 'kit' });
|
if (options.length) log(s, ctx, { t: 'draw', p: p.id, n: options.length, why: 'kit' });
|
||||||
} else {
|
} else {
|
||||||
s.reactions.push({ kind: 'kitKeep', player: p.id, options, deadline: ctx.now + reactionMs(s, p) });
|
s.reactions.push({ kind: 'kitKeep', player: p.id, options, deadline: after(ctx, reactionMs(s, p)) });
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -471,7 +474,7 @@ export function settle(s: BangState, ctx: Ctx): void {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (s.turn.pausedAt !== null) {
|
if (s.turn.pausedAt !== null) {
|
||||||
s.turn.deadline += ctx.now - s.turn.pausedAt;
|
if (s.turn.deadline !== null) s.turn.deadline += ctx.now - s.turn.pausedAt;
|
||||||
s.turn.pausedAt = null;
|
s.turn.pausedAt = null;
|
||||||
}
|
}
|
||||||
const p = P(s, s.turn.player);
|
const p = P(s, s.turn.player);
|
||||||
@@ -514,7 +517,7 @@ function openBang(s: BangState, ctx: Ctx, source: PlayerId, target: PlayerId, vi
|
|||||||
needed: via === 'bang' && is(P(s, source), 'slab') ? 2 : 1,
|
needed: via === 'bang' && is(P(s, source), 'slab') ? 2 : 1,
|
||||||
barrelTried: false,
|
barrelTried: false,
|
||||||
jourTried: false,
|
jourTried: false,
|
||||||
deadline: ctx.now + reactionMs(s, t),
|
deadline: after(ctx, reactionMs(s, t)),
|
||||||
};
|
};
|
||||||
if (s.options.autoBarrel) {
|
if (s.options.autoBarrel) {
|
||||||
while (r.needed > 0 && tryBarrel(s, ctx, r));
|
while (r.needed > 0 && tryBarrel(s, ctx, r));
|
||||||
@@ -582,7 +585,7 @@ export function storeAdvance(s: BangState, ctx: Ctx, r: Extract<Reaction, { kind
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
r.picker = next;
|
r.picker = next;
|
||||||
r.deadline = ctx.now + reactionMs(s, p);
|
r.deadline = after(ctx, reactionMs(s, p));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -661,13 +664,13 @@ export function playCard(s: BangState, ctx: Ctx, actor: PlayerId, a: PlayAction)
|
|||||||
}
|
}
|
||||||
case 'duel': {
|
case 'duel': {
|
||||||
const t = P(s, a.target!);
|
const t = P(s, a.target!);
|
||||||
s.reactions.push({ kind: 'duel', actor: t.id, other: actor, source: actor, deadline: ctx.now + reactionMs(s, t) });
|
s.reactions.push({ kind: 'duel', actor: t.id, other: actor, source: actor, deadline: after(ctx, reactionMs(s, t)) });
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'indians':
|
case 'indians':
|
||||||
for (const id of clockwiseFrom(s, actor)) {
|
for (const id of clockwiseFrom(s, actor)) {
|
||||||
if (id === actor) continue;
|
if (id === actor) continue;
|
||||||
s.reactions.push({ kind: 'indians', target: id, source: actor, deadline: ctx.now + reactionMs(s, P(s, id)) });
|
s.reactions.push({ kind: 'indians', target: id, source: actor, deadline: after(ctx, reactionMs(s, P(s, id))) });
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 'gatling':
|
case 'gatling':
|
||||||
@@ -700,7 +703,7 @@ export function respond(s: BangState, ctx: Ctx, actor: PlayerId, cardIds: string
|
|||||||
const next = r.other;
|
const next = r.other;
|
||||||
r.other = r.actor;
|
r.other = r.actor;
|
||||||
r.actor = next;
|
r.actor = next;
|
||||||
r.deadline = ctx.now + reactionMs(s, P(s, next));
|
r.deadline = after(ctx, reactionMs(s, P(s, next)));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'dying':
|
case 'dying':
|
||||||
@@ -793,7 +796,7 @@ export function endPlay(s: BangState, ctx: Ctx, actor: PlayerId): void {
|
|||||||
const p = P(s, actor);
|
const p = P(s, actor);
|
||||||
if (p.hand.length > p.life) {
|
if (p.hand.length > p.life) {
|
||||||
s.turn.phase = 'discard';
|
s.turn.phase = 'discard';
|
||||||
s.turn.deadline = Math.max(s.turn.deadline, ctx.now + DISCARD_MIN_MS);
|
if (s.turn.deadline !== null) s.turn.deadline = Math.max(s.turn.deadline, ctx.now + DISCARD_MIN_MS);
|
||||||
} else s.turn.phase = 'ended';
|
} else s.turn.phase = 'ended';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { CARDS, CHARACTER_IDS, CHARACTER_LIFE, cardById, kindOf, rolesFor } from
|
|||||||
import { distance, rangeOf } from './distance';
|
import { distance, rangeOf } from './distance';
|
||||||
import {
|
import {
|
||||||
AWAY_AFTER,
|
AWAY_AFTER,
|
||||||
|
AWAY_MS,
|
||||||
P,
|
P,
|
||||||
autoSave,
|
autoSave,
|
||||||
discardDown,
|
discardDown,
|
||||||
@@ -71,17 +72,24 @@ export function allCards(s: BangState): string[] {
|
|||||||
return [...s.deck, ...s.discard, ...s.players.flatMap((p) => [...p.hand, ...p.inPlay]), ...limboCards(s)];
|
return [...s.deck, ...s.discard, ...s.players.flatMap((p) => [...p.hand, ...p.inPlay]), ...limboCards(s)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Earliest clock; reactions with no clock (무제한) are skipped, null when nothing is timed. */
|
||||||
function deadlineOf(s: BangState): number | null {
|
function deadlineOf(s: BangState): number | null {
|
||||||
if (s.winner) return null;
|
if (s.winner) return null;
|
||||||
if (s.reactions.length) return Math.min(...s.reactions.map((r) => r.deadline));
|
if (s.reactions.length) {
|
||||||
|
const ds = s.reactions.flatMap((r) => (r.deadline === null ? [] : [r.deadline]));
|
||||||
|
return ds.length ? Math.min(...ds) : null;
|
||||||
|
}
|
||||||
return s.turn.deadline;
|
return s.turn.deadline;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Responders whose own deadline is the earliest (a later reaction must not be cut short). */
|
/**
|
||||||
|
* Responders whose own deadline is the earliest (a later reaction must not be cut short).
|
||||||
|
* When no reaction has a clock (무제한), every responder is listed so the room's disconnect grace can still time each one out.
|
||||||
|
*/
|
||||||
function timed(s: BangState): PlayerId[] {
|
function timed(s: BangState): PlayerId[] {
|
||||||
if (s.winner) return [];
|
if (s.winner) return [];
|
||||||
if (!s.reactions.length) return [s.turn.player];
|
if (!s.reactions.length) return [s.turn.player];
|
||||||
const d = deadlineOf(s)!;
|
const d = deadlineOf(s);
|
||||||
return [...new Set(s.reactions.filter((r) => r.deadline === d).map(responder))];
|
return [...new Set(s.reactions.filter((r) => r.deadline === d).map(responder))];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,7 +186,8 @@ export const bang: Def = {
|
|||||||
deck: rng.shuffle(CARDS.map((c) => c.id)),
|
deck: rng.shuffle(CARDS.map((c) => c.id)),
|
||||||
discard: [],
|
discard: [],
|
||||||
turn: { player: ps.find((p) => p.role === 'sheriff')!.id, phase: 'draft', bangsPlayed: 0, deadline: now, pausedAt: null, dynamiteChecked: false, jailChecked: false },
|
turn: { player: ps.find((p) => p.role === 'sheriff')!.id, phase: 'draft', bangsPlayed: 0, deadline: now, pausedAt: null, dynamiteChecked: false, jailChecked: false },
|
||||||
reactions: draft ? ps.map((p) => ({ kind: 'choose2' as const, player: p.id, deadline: now + 30_000 })) : [],
|
// The draft pick has its own 30 s clock, none when the turn clock is 무제한.
|
||||||
|
reactions: draft ? ps.map((p) => ({ kind: 'choose2' as const, player: p.id, deadline: options.turnSeconds === null ? null : now + 30_000 })) : [],
|
||||||
lastCheck: null,
|
lastCheck: null,
|
||||||
winner: null,
|
winner: null,
|
||||||
deathOrder: [],
|
deathOrder: [],
|
||||||
@@ -318,8 +327,9 @@ export const bang: Def = {
|
|||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
turnDeadline: s.turn.deadline,
|
turnDeadline: s.turn.deadline,
|
||||||
deadlineTotalMs: s.options.turnSeconds * 1000,
|
// 무제한: only an away player's short clock can run, so the ring is sized for it.
|
||||||
reactionTotalMs: s.options.reactionSeconds * 1000,
|
deadlineTotalMs: s.options.turnSeconds === null ? AWAY_MS : s.options.turnSeconds * 1000,
|
||||||
|
reactionTotalMs: s.options.reactionSeconds === null ? AWAY_MS : s.options.reactionSeconds * 1000,
|
||||||
log: s.log.slice(-LOG_VIEW).map((e) => stripPrivate(e, me, over)),
|
log: s.log.slice(-LOG_VIEW).map((e) => stripPrivate(e, me, over)),
|
||||||
winner: s.winner,
|
winner: s.winner,
|
||||||
result: s.final,
|
result: s.final,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { z } from 'zod';
|
|||||||
import type { PlayerId } from '@bg/engine';
|
import type { PlayerId } from '@bg/engine';
|
||||||
import { CHARACTER_IDS, type Card, type CardFace, type CardKind, type CharacterId, type Role } from './cards';
|
import { CHARACTER_IDS, type Card, type CardFace, type CardKind, type CharacterId, type Role } from './cards';
|
||||||
|
|
||||||
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>[]]);
|
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||||
|
|
||||||
export const bangOptionsSchema = z.object({
|
export const bangOptionsSchema = z.object({
|
||||||
@@ -11,12 +11,14 @@ export const bangOptionsSchema = z.object({
|
|||||||
.enum(['random', 'choose2'])
|
.enum(['random', 'choose2'])
|
||||||
.default('random')
|
.default('random')
|
||||||
.meta({ title: '캐릭터 정하기', labels: { random: '무작위 1장', choose2: '2장 중 1장 고르기' } }),
|
.meta({ title: '캐릭터 정하기', labels: { random: '무작위 1장', choose2: '2장 중 1장 고르기' } }),
|
||||||
turnSeconds: lit(30, 60, 90, 120)
|
/** null = 무제한 (also for the choose2 draft pick). A dropped connection still gets auto moves after the room's grace time. */
|
||||||
|
turnSeconds: lit(30, 60, 90, 120, null)
|
||||||
.default(60)
|
.default(60)
|
||||||
.meta({ title: '내 턴 제한 시간', labels: { 30: '30초', 60: '60초', 90: '90초', 120: '120초' } }),
|
.meta({ title: '내 턴 제한 시간', labels: { 30: '30초', 60: '60초', 90: '90초', 120: '120초', null: '무제한' } }),
|
||||||
reactionSeconds: lit(8, 15, 25)
|
/** null = 무제한 (away players still get the short clock). */
|
||||||
|
reactionSeconds: lit(8, 15, 25, null)
|
||||||
.default(15)
|
.default(15)
|
||||||
.meta({ title: '반응 제한 시간(빗나감!·맥주·결투·잡화점)', labels: { 8: '8초', 15: '15초', 25: '25초' } }),
|
.meta({ title: '반응 제한 시간(빗나감!·맥주·결투·잡화점)', labels: { 8: '8초', 15: '15초', 25: '25초', null: '무제한' } }),
|
||||||
autoDefend: z.boolean().default(true).meta({ title: '반응 시간이 지나면 막을 카드를 자동으로 내기' }),
|
autoDefend: z.boolean().default(true).meta({ title: '반응 시간이 지나면 막을 카드를 자동으로 내기' }),
|
||||||
autoBarrel: z.boolean().default(true).meta({ title: '술통·주르도네 판정을 묻지 않고 자동으로 하기' }),
|
autoBarrel: z.boolean().default(true).meta({ title: '술통·주르도네 판정을 묻지 않고 자동으로 하기' }),
|
||||||
showDistanceHelper: z.boolean().default(true).meta({ title: '다른 사람까지 거리와 사거리 표시' }),
|
showDistanceHelper: z.boolean().default(true).meta({ title: '다른 사람까지 거리와 사거리 표시' }),
|
||||||
@@ -70,15 +72,16 @@ export interface PlayerState {
|
|||||||
away: boolean;
|
away: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** `deadline: null` = 무제한 (no clock; only the room's disconnect grace applies). Never Infinity (state is JSON). */
|
||||||
export type Reaction =
|
export type Reaction =
|
||||||
| { kind: 'bang'; target: PlayerId; source: PlayerId; via: 'bang' | 'gatling'; needed: number; barrelTried: boolean; jourTried: boolean; deadline: number }
|
| { kind: 'bang'; target: PlayerId; source: PlayerId; via: 'bang' | 'gatling'; needed: number; barrelTried: boolean; jourTried: boolean; deadline: number | null }
|
||||||
| { kind: 'indians'; target: PlayerId; source: PlayerId; deadline: number }
|
| { kind: 'indians'; target: PlayerId; source: PlayerId; deadline: number | null }
|
||||||
| { kind: 'duel'; actor: PlayerId; other: PlayerId; source: PlayerId; deadline: number }
|
| { kind: 'duel'; actor: PlayerId; other: PlayerId; source: PlayerId; deadline: number | null }
|
||||||
| { kind: 'store'; picker: PlayerId; order: PlayerId[]; revealed: string[]; source: PlayerId; deadline: number }
|
| { kind: 'store'; picker: PlayerId; order: PlayerId[]; revealed: string[]; source: PlayerId; deadline: number | null }
|
||||||
/** `lost` / `source`: the life loss that caused it (Bart / El Gringo trigger after surviving, §5.5). */
|
/** `lost` / `source`: the life loss that caused it (Bart / El Gringo trigger after surviving, §5.5). */
|
||||||
| { kind: 'dying'; player: PlayerId; killer: PlayerId | null; lost: number; source: PlayerId | null; deadline: number }
|
| { kind: 'dying'; player: PlayerId; killer: PlayerId | null; lost: number; source: PlayerId | null; deadline: number | null }
|
||||||
| { kind: 'kitKeep'; player: PlayerId; options: string[]; deadline: number }
|
| { kind: 'kitKeep'; player: PlayerId; options: string[]; deadline: number | null }
|
||||||
| { kind: 'choose2'; player: PlayerId; deadline: number };
|
| { kind: 'choose2'; player: PlayerId; deadline: number | null };
|
||||||
export type ReactionKind = Reaction['kind'];
|
export type ReactionKind = Reaction['kind'];
|
||||||
|
|
||||||
export type TurnPhase = 'draft' | 'start' | 'draw' | 'play' | 'discard' | 'ended';
|
export type TurnPhase = 'draft' | 'start' | 'draw' | 'play' | 'discard' | 'ended';
|
||||||
@@ -87,7 +90,8 @@ export interface TurnState {
|
|||||||
player: PlayerId;
|
player: PlayerId;
|
||||||
phase: TurnPhase;
|
phase: TurnPhase;
|
||||||
bangsPlayed: number;
|
bangsPlayed: number;
|
||||||
deadline: number;
|
/** null = 무제한. */
|
||||||
|
deadline: number | null;
|
||||||
/** Turn timer is paused while reactions run during the play phase. */
|
/** Turn timer is paused while reactions run during the play phase. */
|
||||||
pausedAt: number | null;
|
pausedAt: number | null;
|
||||||
dynamiteChecked: boolean;
|
dynamiteChecked: boolean;
|
||||||
@@ -217,7 +221,7 @@ export interface ReactionView {
|
|||||||
via?: 'bang' | 'gatling';
|
via?: 'bang' | 'gatling';
|
||||||
needed?: number;
|
needed?: number;
|
||||||
revealed?: Card[];
|
revealed?: Card[];
|
||||||
deadline: number;
|
deadline: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BangView {
|
export interface BangView {
|
||||||
@@ -246,7 +250,9 @@ export interface BangView {
|
|||||||
canSidHeal: boolean;
|
canSidHeal: boolean;
|
||||||
prompt: Prompt | null;
|
prompt: Prompt | null;
|
||||||
} | null;
|
} | null;
|
||||||
turnDeadline: number;
|
/** null = 무제한 (no clock shown). */
|
||||||
|
turnDeadline: number | null;
|
||||||
|
/** Full clock lengths for the timer ring (the short away clock when the option is 무제한). */
|
||||||
deadlineTotalMs: number;
|
deadlineTotalMs: number;
|
||||||
reactionTotalMs: number;
|
reactionTotalMs: number;
|
||||||
log: LogEntry[];
|
log: LogEntry[];
|
||||||
|
|||||||
@@ -389,6 +389,23 @@ describe('시간 초과 (§8.5)', () => {
|
|||||||
expect(game.deadline!(back)! - back.turnStartedAt).toBe(30_000);
|
expect(game.deadline!(back)! - back.turnStartedAt).toBe(30_000);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('무제한 (turnSeconds null): 마감 없음, 그래도 시간 초과(연결 끊김)는 대신 두고 자리 비움이면 5초', () => {
|
||||||
|
expect(game.optionsSchema.safeParse({ turnSeconds: null }).success).toBe(true);
|
||||||
|
const t0 = rigged({ A: ['rat', 'fly'], B: ['bat'], C: ['toad'] }, { turnSeconds: null });
|
||||||
|
expect(game.deadline!(t0)).toBeNull();
|
||||||
|
expect(game.view(t0, 'A').turnMs).toBe(0);
|
||||||
|
const third = actE({ ...t0, timeoutsInRow: { A: 2, B: 0, C: 0 } }, 'A', { type: 'timeout' });
|
||||||
|
expect(third.events.map((e) => e.type)).toEqual(['timeout', 'away', 'offer']);
|
||||||
|
// B (not away) now holds the card: still no clock.
|
||||||
|
expect(game.deadline!(third.state)).toBeNull();
|
||||||
|
const w = { ...t0, away: { A: true, B: false, C: false } };
|
||||||
|
expect(game.deadline!(w)! - w.turnStartedAt).toBe(5000);
|
||||||
|
expect(game.view(w, 'A').turnMs).toBe(5000);
|
||||||
|
const back = act(w, 'A', { type: 'offer', cardId: 'rat-0', to: 'B', claim: 'rat' });
|
||||||
|
expect(back.away.A).toBe(false);
|
||||||
|
expect(game.deadline!(back)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
test('모두 무응답이어도 게임이 끝남; 매 상태에서 onTimeout이 합법', () => {
|
test('모두 무응답이어도 게임이 끝남; 매 상태에서 onTimeout이 합법', () => {
|
||||||
for (let seed = 1; seed <= 40; seed++) {
|
for (let seed = 1; seed <= 40; seed++) {
|
||||||
const n = 2 + (seed % 5);
|
const n = 2 + (seed % 5);
|
||||||
@@ -538,7 +555,7 @@ function cfg(i: number): { players: string[]; options: CockroachOptions } {
|
|||||||
claimHistory: i % 3 !== 0,
|
claimHistory: i % 3 !== 0,
|
||||||
eightKindsRule: i % 7 === 0,
|
eightKindsRule: i % 7 === 0,
|
||||||
twoPlayerPass: i % 2 === 0,
|
twoPlayerPass: i % 2 === 0,
|
||||||
turnSeconds: ([15, 30, 60] as const)[i % 3],
|
turnSeconds: ([15, 30, 60, null] as const)[i % 4],
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,10 +45,11 @@ export const cockroachOptionsSchema = z.object({
|
|||||||
.union([z.literal('auto'), z.literal(3), z.literal(4), z.literal(5)])
|
.union([z.literal('auto'), z.literal(3), z.literal(4), z.literal(5)])
|
||||||
.default('auto')
|
.default('auto')
|
||||||
.meta({ title: '같은 벌레가 몇 장 모이면 패배', labels: { auto: '자동(2명 5장, 3~6명 4장)', 3: '3장(짧은 게임)', 4: '4장', 5: '5장' } }),
|
.meta({ title: '같은 벌레가 몇 장 모이면 패배', labels: { auto: '자동(2명 5장, 3~6명 4장)', 3: '3장(짧은 게임)', 4: '4장', 5: '5장' } }),
|
||||||
|
/** null = 무제한 (no clock; a dropped connection still gets an auto move after the room's grace time). */
|
||||||
turnSeconds: z
|
turnSeconds: z
|
||||||
.union([z.literal(15), z.literal(30), z.literal(60)])
|
.union([z.literal(15), z.literal(30), z.literal(60), z.literal(null)])
|
||||||
.default(30)
|
.default(30)
|
||||||
.meta({ title: '건네기·판정 제한 시간', labels: { 15: '15초', 30: '30초', 60: '60초' } }),
|
.meta({ title: '건네기·판정 제한 시간', labels: { 15: '15초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||||
claimHistory: z.boolean().default(true).meta({ title: '이번 라운드 주장 기록 보이기' }),
|
claimHistory: z.boolean().default(true).meta({ title: '이번 라운드 주장 기록 보이기' }),
|
||||||
quickChat: z.boolean().default(true).meta({ title: '빠른 말 버튼("정말이야!", "의심스러운데?")' }),
|
quickChat: z.boolean().default(true).meta({ title: '빠른 말 버튼("정말이야!", "의심스러운데?")' }),
|
||||||
eightKindsRule: z.boolean().default(false).meta({ title: '앞마당에 8종을 모두 모아도 패배(하우스 룰)' }),
|
eightKindsRule: z.boolean().default(false).meta({ title: '앞마당에 8종을 모두 모아도 패배(하우스 룰)' }),
|
||||||
@@ -200,6 +201,7 @@ export interface CockroachView {
|
|||||||
said: Said[];
|
said: Said[];
|
||||||
removedCount: number;
|
removedCount: number;
|
||||||
turnStartedAt: number;
|
turnStartedAt: number;
|
||||||
|
/** Clock length in ms; 0 = 무제한 (no clock). */
|
||||||
turnMs: number;
|
turnMs: number;
|
||||||
seq: number;
|
seq: number;
|
||||||
final: CockroachFinal | null;
|
final: CockroachFinal | null;
|
||||||
@@ -266,9 +268,11 @@ function peekBlock(s: CockroachState): string | null {
|
|||||||
return passTargets(s, r.holder!).length === 0 ? '모두 이 카드를 이미 봐서 넘길 사람이 없어요. 진짜인지 거짓인지 골라 주세요.' : null;
|
return passTargets(s, r.holder!).length === 0 ? '모두 이 카드를 이미 봐서 넘길 사람이 없어요. 진짜인지 거짓인지 골라 주세요.' : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function turnMs(s: CockroachState): number {
|
/** Clock for the waiting player in ms; null = 무제한 (an away player still gets the short clock). */
|
||||||
|
function turnMs(s: CockroachState): number | null {
|
||||||
const p = waiting(s)[0];
|
const p = waiting(s)[0];
|
||||||
return p && s.away[p] ? AWAY_MS : s.options.turnSeconds * 1000;
|
if (p && s.away[p]) return AWAY_MS;
|
||||||
|
return s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
function newRound(s: CockroachState, starter: PlayerId): void {
|
function newRound(s: CockroachState, starter: PlayerId): void {
|
||||||
@@ -576,7 +580,7 @@ export const cockroachPoker: GameDefinition<CockroachState, CockroachAction, Coc
|
|||||||
said: s.said,
|
said: s.said,
|
||||||
removedCount: s.removed.length,
|
removedCount: s.removed.length,
|
||||||
turnStartedAt: s.turnStartedAt,
|
turnStartedAt: s.turnStartedAt,
|
||||||
turnMs: turnMs(s),
|
turnMs: turnMs(s) ?? 0,
|
||||||
seq: s.seq,
|
seq: s.seq,
|
||||||
final: s.final,
|
final: s.final,
|
||||||
revealed: over ? { hands: s.hands, removed: s.removed } : null,
|
revealed: over ? { hands: s.hands, removed: s.removed } : null,
|
||||||
@@ -586,7 +590,8 @@ export const cockroachPoker: GameDefinition<CockroachState, CockroachAction, Coc
|
|||||||
activePlayers: waiting,
|
activePlayers: waiting,
|
||||||
|
|
||||||
deadline(s) {
|
deadline(s) {
|
||||||
return finished(s) ? null : s.turnStartedAt + turnMs(s);
|
const ms = turnMs(s);
|
||||||
|
return finished(s) || ms === null ? null : s.turnStartedAt + ms;
|
||||||
},
|
},
|
||||||
|
|
||||||
timeoutPlayers: waiting,
|
timeoutPlayers: waiting,
|
||||||
|
|||||||
@@ -475,6 +475,30 @@ describe('시간 초과와 나가기 (§8.5)', () => {
|
|||||||
expect(s.away.B).toBe(false);
|
expect(s.away.B).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('무제한 (turnSeconds null): no clock for turns, hand check or tax return; timeouts still work and away keeps the 5 s clock', () => {
|
||||||
|
expect(dalmuti.optionsSchema.safeParse({ turnSeconds: null }).success).toBe(true);
|
||||||
|
// Hand check and tax return have no clock either.
|
||||||
|
let c = make({ turnSeconds: null });
|
||||||
|
expect(c.phase.kind).toBe('revolutionCheck');
|
||||||
|
expect(dalmuti.deadline!(c)).toBeNull();
|
||||||
|
expect(dalmuti.view(c, 'A').deadlineTotalMs).toBe(0);
|
||||||
|
for (const p of c.players) c = act(c, p, { type: 'timeout' });
|
||||||
|
expect(c.phase.kind).toBe('taxReturn');
|
||||||
|
expect(dalmuti.deadline!(c)).toBeNull();
|
||||||
|
// Playing: no turn clock; a dropped connection's timeouts still play and lead to away.
|
||||||
|
let s = rig(make({ turnSeconds: null }), { order: P5, hands: { A: [C(1, 1), C(9, 1), C(9, 2), C(9, 3)], B: [C(12, 1), C(12, 2)], C: [C(12, 3)], D: [C(12, 4)], E: [C(12, 5)] } });
|
||||||
|
s.timeoutsInRow.B = 2;
|
||||||
|
s = play(s, 'A', [C(9, 1)]);
|
||||||
|
expect(dalmuti.deadline!(s)).toBeNull();
|
||||||
|
s = act(s, 'B', { type: 'timeout' });
|
||||||
|
expect(s.away.B).toBe(true);
|
||||||
|
for (const p of ['C', 'D', 'E']) s = pass(s, p);
|
||||||
|
s = play(s, 'A', [C(9, 2)]);
|
||||||
|
expect(s.current).toBe('B');
|
||||||
|
expect(dalmuti.deadline!(s)).toBe(s.turnStartedAt + 5000);
|
||||||
|
expect(dalmuti.view(s, 'A').deadlineTotalMs).toBe(5000);
|
||||||
|
});
|
||||||
|
|
||||||
test('leaving does not eliminate: the seat stays, marked away, and keeps being auto-played', () => {
|
test('leaving does not eliminate: the seat stays, marked away, and keeps being auto-played', () => {
|
||||||
let s = rig(make(), { order: P5, hands: { A: [C(9, 1)], B: [C(12, 1), C(5, 1)], C: [C(12, 3)], D: [C(12, 4)], E: [C(12, 5)] } });
|
let s = rig(make(), { order: P5, hands: { A: [C(9, 1)], B: [C(12, 1), C(5, 1)], C: [C(12, 3)], D: [C(12, 4)], E: [C(12, 5)] } });
|
||||||
expect(dalmuti.onLeave!(s, 'B')).toEqual({ type: 'leave' });
|
expect(dalmuti.onLeave!(s, 'B')).toEqual({ type: 'leave' });
|
||||||
|
|||||||
@@ -437,18 +437,20 @@ function waiting(s: DalmutiState): PlayerId[] {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Clock in ms; null = 무제한 (`turnSeconds` null: no clock for any decision, but away players keep the short one). */
|
||||||
function deadlineMs(s: DalmutiState): number | null {
|
function deadlineMs(s: DalmutiState): number | null {
|
||||||
const w = waiting(s);
|
const w = waiting(s);
|
||||||
const allAway = w.length > 0 && w.every((p) => s.away[p]);
|
const allAway = w.length > 0 && w.every((p) => s.away[p]);
|
||||||
|
if (s.phase.kind === 'finished') return null;
|
||||||
|
if (allAway) return AWAY_MS;
|
||||||
|
if (s.options.turnSeconds === null) return null;
|
||||||
switch (s.phase.kind) {
|
switch (s.phase.kind) {
|
||||||
case 'revolutionCheck':
|
case 'revolutionCheck':
|
||||||
return allAway ? AWAY_MS : REVOLUTION_MS;
|
return REVOLUTION_MS;
|
||||||
case 'taxReturn':
|
case 'taxReturn':
|
||||||
return allAway ? AWAY_MS : TAX_MS;
|
return TAX_MS;
|
||||||
case 'playing':
|
case 'playing':
|
||||||
return allAway ? AWAY_MS : s.options.turnSeconds * 1000;
|
return s.options.turnSeconds * 1000;
|
||||||
case 'finished':
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ export function deckFor(removeHighCards: boolean): DCard[] {
|
|||||||
|
|
||||||
// ---------------------------------------------------------------- options / actions
|
// ---------------------------------------------------------------- options / actions
|
||||||
|
|
||||||
const lit = <T extends string | number>(...vals: T[]) =>
|
const lit = <T extends string | number | null>(...vals: T[]) =>
|
||||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||||
|
|
||||||
export const dalmutiOptionsSchema = z.object({
|
export const dalmutiOptionsSchema = z.object({
|
||||||
@@ -66,9 +66,13 @@ export const dalmutiOptionsSchema = z.object({
|
|||||||
jesterTaxable: z.boolean().default(false).meta({ title: '세금 낼 때 광대도 좋은 카드로 내기' }),
|
jesterTaxable: z.boolean().default(false).meta({ title: '세금 낼 때 광대도 좋은 카드로 내기' }),
|
||||||
passLocksOut: z.boolean().default(false).meta({ title: '한 번 패스하면 그 트릭에서 다시 못 내기' }),
|
passLocksOut: z.boolean().default(false).meta({ title: '한 번 패스하면 그 트릭에서 다시 못 내기' }),
|
||||||
removeHighCards: z.boolean().default(false).meta({ title: '9~12 카드를 빼고 하기(38장)' }),
|
removeHighCards: z.boolean().default(false).meta({ title: '9~12 카드를 빼고 하기(38장)' }),
|
||||||
turnSeconds: lit<15 | 20 | 30 | 45>(15, 20, 30, 45)
|
/**
|
||||||
|
* null = 무제한: no clock for turns, the hand check and the tax return either (a dropped connection still gets
|
||||||
|
* automatic moves after the room's grace time, and away players keep the short clock).
|
||||||
|
*/
|
||||||
|
turnSeconds: lit<15 | 20 | 30 | 45 | null>(15, 20, 30, 45, null)
|
||||||
.default(20)
|
.default(20)
|
||||||
.meta({ title: '한 턴 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 45: '45초' } }),
|
.meta({ title: '한 턴 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 45: '45초', null: '무제한' } }),
|
||||||
});
|
});
|
||||||
export type DalmutiOptions = z.infer<typeof dalmutiOptionsSchema>;
|
export type DalmutiOptions = z.infer<typeof dalmutiOptionsSchema>;
|
||||||
|
|
||||||
|
|||||||
@@ -776,6 +776,29 @@ describe('시간 초과·연결 끊김 (§8.5)', () => {
|
|||||||
s = act(s, 'A', play(gostop.view(s, 'A').myHand![0]!.card.id), 14_000);
|
s = act(s, 'A', play(gostop.view(s, 'A').myHand![0]!.card.id), 14_000);
|
||||||
expect(s.autoPilot[0]).toBe(false);
|
expect(s.autoPilot[0]).toBe(false);
|
||||||
});
|
});
|
||||||
|
test('무제한 (turnSeconds·decisionSeconds null): 마감 없음, 그래도 시간 초과(연결 끊김)는 처리되고 2회면 autoPilot 2초', () => {
|
||||||
|
expect(gostop.optionsSchema.safeParse({ turnSeconds: null, decisionSeconds: null }).success).toBe(true);
|
||||||
|
expect(gostop.optionsSchema.safeParse({ turnSeconds: 7 }).success).toBe(false);
|
||||||
|
let s = rigged(2, { hands: [[2, 6, 10], [11, 15, 19]], floor: [20], deck: [24, 36, 37, 38, 39, 42, 43] }, { turnSeconds: null, decisionSeconds: null });
|
||||||
|
expect(gostop.deadline!(s)).toBeNull();
|
||||||
|
expect(gostop.view(s, 'A').deadline).toBeNull();
|
||||||
|
s = act(s, 'A', { type: 'timeout' }, 10_000);
|
||||||
|
expect(s.autoPilot[0]).toBe(false);
|
||||||
|
expect(s.deadline).toBeNull();
|
||||||
|
s = act(s, 'B', play(11), 11_000);
|
||||||
|
s = act(s, 'A', { type: 'timeout' }, 12_000);
|
||||||
|
expect(s.autoPilot[0]).toBe(true);
|
||||||
|
s = act(s, 'B', play(15), 13_000);
|
||||||
|
expect(s.deadline).toBe(13_000 + 2_000);
|
||||||
|
s = act(s, 'A', play(gostop.view(s, 'A').myHand![0]!.card.id), 14_000);
|
||||||
|
expect(s.autoPilot[0]).toBe(false);
|
||||||
|
// 고·스톱 같은 선택 단계도 마감이 없어요.
|
||||||
|
const g = rigged(2, { hands: [[25, 2], [11, 15]], floor: [24], deck: [36, 37, 38], captured: [[0, 8, 28, 1, 5, 9, 13, 33], [44]] }, { decisionSeconds: null });
|
||||||
|
const after = act(g, 'A', play(25), 20_000);
|
||||||
|
expect(after.round!.step).toBe('goStop');
|
||||||
|
expect(after.deadline).toBeNull();
|
||||||
|
expect(act(after, 'A', { type: 'timeout' }).round!.outcome?.type).toBe('stop');
|
||||||
|
});
|
||||||
test('나가기: autoPilot, 끊긴 사람 차례 마감 2초, 결과 화면 준비에서 빠짐', () => {
|
test('나가기: autoPilot, 끊긴 사람 차례 마감 2초, 결과 화면 준비에서 빠짐', () => {
|
||||||
let s = rigged(2, { hands: [[2, 6], [11, 15]], floor: [20], deck: [24, 36, 37, 38] });
|
let s = rigged(2, { hands: [[2, 6], [11, 15]], floor: [20], deck: [24, 36, 37, 38] });
|
||||||
s = act(s, 'A', { type: 'leave' }, 5000);
|
s = act(s, 'A', { type: 'leave' }, 5000);
|
||||||
|
|||||||
@@ -89,7 +89,9 @@ function deadlineMs(s: GostopState): number | null {
|
|||||||
if (w.length === 0) return null;
|
if (w.length === 0) return null;
|
||||||
if (w.every((i) => s.autoPilot[i])) return AUTO_MS;
|
if (w.every((i) => s.autoPilot[i])) return AUTO_MS;
|
||||||
const step = s.round!.step;
|
const step = s.round!.step;
|
||||||
return (step === 'play' ? s.rules.turnSeconds : s.rules.decisionSeconds) * 1000;
|
const sec = step === 'play' ? s.rules.turnSeconds : s.rules.decisionSeconds;
|
||||||
|
// 무제한: no clock (the room still times out a dropped connection after its grace time).
|
||||||
|
return sec === null ? null : sec * 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
function refreshDeadline(s: GostopState, now: number): void {
|
function refreshDeadline(s: GostopState, now: number): void {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { z } from 'zod';
|
|||||||
import type { PlayerId } from '@bg/engine';
|
import type { PlayerId } from '@bg/engine';
|
||||||
import type { BonusSetting, CardId, CardView } from './cards';
|
import type { BonusSetting, CardId, CardView } from './cards';
|
||||||
|
|
||||||
const lit = <T extends string | number>(...vals: T[]) =>
|
const lit = <T extends string | number | null>(...vals: T[]) =>
|
||||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||||
|
|
||||||
export const gostopOptionsSchema = z.object({
|
export const gostopOptionsSchema = z.object({
|
||||||
@@ -58,12 +58,14 @@ export const gostopOptionsSchema = z.object({
|
|||||||
.enum(['gwang', 'gwangPlus'])
|
.enum(['gwang', 'gwangPlus'])
|
||||||
.default('gwang')
|
.default('gwang')
|
||||||
.meta({ title: '팔 수 있는 패', labels: { gwang: '광만', gwangPlus: '광 + 쌍피·국진·보너스' } }),
|
.meta({ title: '팔 수 있는 패', labels: { gwang: '광만', gwangPlus: '광 + 쌍피·국진·보너스' } }),
|
||||||
turnSeconds: lit(5, 10, 15, 20, 30, 60)
|
/** null = 무제한 (no clock; a dropped connection still gets auto moves after the room's grace time, autoPilot keeps 2초). */
|
||||||
|
turnSeconds: lit(5, 10, 15, 20, 30, 60, null)
|
||||||
.default(15)
|
.default(15)
|
||||||
.meta({ title: '한 턴 제한 시간', labels: { 5: '5초', 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }),
|
.meta({ title: '한 턴 제한 시간', labels: { 5: '5초', 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||||
decisionSeconds: lit(5, 10, 15, 20, 30)
|
/** null = 무제한 (고·스톱, 뒤집은 패 고르기, 총통, 광팔기, 국진). */
|
||||||
|
decisionSeconds: lit(5, 10, 15, 20, 30, null)
|
||||||
.default(10)
|
.default(10)
|
||||||
.meta({ title: '고·스톱·선택 제한 시간', labels: { 5: '5초', 10: '10초', 15: '15초', 20: '20초', 30: '30초' } }),
|
.meta({ title: '고·스톱·선택 제한 시간', labels: { 5: '5초', 10: '10초', 15: '15초', 20: '20초', 30: '30초', null: '무제한' } }),
|
||||||
hints: z.boolean().default(true).meta({ title: '먹을 수 있는 패·족보 힌트' }),
|
hints: z.boolean().default(true).meta({ title: '먹을 수 있는 패·족보 힌트' }),
|
||||||
});
|
});
|
||||||
export type GostopOptions = z.infer<typeof gostopOptionsSchema>;
|
export type GostopOptions = z.infer<typeof gostopOptionsSchema>;
|
||||||
|
|||||||
@@ -256,9 +256,11 @@ function validatePlay(s: NinetyNineState, actor: PlayerId, a: PlayAction): Valid
|
|||||||
return r.ok ? ok : fail(r.reason);
|
return r.ok ? ok : fail(r.reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Turn clock in ms; null = 무제한 (away players still get the short clock). */
|
||||||
function deadlineMs(s: NinetyNineState): number | null {
|
function deadlineMs(s: NinetyNineState): number | null {
|
||||||
if (s.phase !== 'playing') return null;
|
if (s.phase !== 'playing') return null;
|
||||||
return s.away[s.current] ? AWAY_MS : s.options.turnSeconds * 1000;
|
if (s.away[s.current]) return AWAY_MS;
|
||||||
|
return s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handView(s: NinetyNineState, p: PlayerId, myTurn: boolean): HandCardView[] {
|
function handView(s: NinetyNineState, p: PlayerId, myTurn: boolean): HandCardView[] {
|
||||||
|
|||||||
@@ -463,6 +463,20 @@ describe('시간 초과, 연결 끊김, 나가기 (§8.5)', () => {
|
|||||||
expect([t.away.A, t.timeoutsInRow.A]).toEqual([false, 0]);
|
expect([t.away.A, t.timeoutsInRow.A]).toEqual([false, 0]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('무제한 (turnSeconds null): no turn clock, but timeouts (dropped connection) still play and lead to away (3 s clock)', () => {
|
||||||
|
expect(ninetyNine.optionsSchema.safeParse({ turnSeconds: null }).success).toBe(true);
|
||||||
|
let s = rig(make({ turnSeconds: null }), { hands: { A: ['1', '2', '3', '4'], B: ['1', '2', '3', '4'], C: ['1', '2', '3', '4'] }, total: 10 });
|
||||||
|
expect(ninetyNine.deadline!(s)).toBeNull();
|
||||||
|
expect(ninetyNine.view(s, 'A').deadlineTotalMs).toBe(0);
|
||||||
|
s.timeoutsInRow.A = 2;
|
||||||
|
s = act(s, 'A', { type: 'timeout' });
|
||||||
|
expect(s.away.A).toBe(true);
|
||||||
|
expect(s.total).toBeGreaterThan(10);
|
||||||
|
expect(ninetyNine.deadline!(s)).toBeNull();
|
||||||
|
s.current = 'A';
|
||||||
|
expect(ninetyNine.deadline!(s)).toBe(s.turnStartedAt + 3000);
|
||||||
|
});
|
||||||
|
|
||||||
test('leaving: the current player leaving passes the turn with the same total; 2 players → the other wins', () => {
|
test('leaving: the current player leaving passes the turn with the same total; 2 players → the other wins', () => {
|
||||||
let s = rig(make({ lives: 3 }), { hands: { A: ['1'], B: ['2'], C: ['3'] }, total: 40 });
|
let s = rig(make({ lives: 3 }), { hands: { A: ['1'], B: ['2'], C: ['3'] }, total: 40 });
|
||||||
expect(ninetyNine.onLeave!(s, 'A')).toEqual({ type: 'leave' });
|
expect(ninetyNine.onLeave!(s, 'A')).toEqual({ type: 'leave' });
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import type { PlayerId } from '@bg/engine';
|
import type { PlayerId } from '@bg/engine';
|
||||||
|
|
||||||
const lit = <T extends string | number>(...vals: T[]) =>
|
const lit = <T extends string | number | null>(...vals: T[]) =>
|
||||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||||
|
|
||||||
export const ninetyNineOptionsSchema = z.object({
|
export const ninetyNineOptionsSchema = z.object({
|
||||||
@@ -47,9 +47,10 @@ export const ninetyNineOptionsSchema = z.object({
|
|||||||
deckCount: lit<'auto' | 1 | 2>('auto', 1, 2)
|
deckCount: lit<'auto' | 1 | 2>('auto', 1, 2)
|
||||||
.default('auto')
|
.default('auto')
|
||||||
.meta({ title: '(트럼프) 덱 수', labels: { auto: '자동(7명부터 2벌)', 1: '1벌', 2: '2벌' } }),
|
.meta({ title: '(트럼프) 덱 수', labels: { auto: '자동(7명부터 2벌)', 1: '1벌', 2: '2벌' } }),
|
||||||
turnSeconds: lit(10, 15, 20, 30)
|
/** null = 무제한 (no turn clock; a dropped connection still gets auto moves after the room's grace time). */
|
||||||
|
turnSeconds: lit(10, 15, 20, 30, null)
|
||||||
.default(15)
|
.default(15)
|
||||||
.meta({ title: '한 턴 제한 시간', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초' } }),
|
.meta({ title: '한 턴 제한 시간', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초', null: '무제한' } }),
|
||||||
});
|
});
|
||||||
export type NNOptions = z.infer<typeof ninetyNineOptionsSchema>;
|
export type NNOptions = z.infer<typeof ninetyNineOptionsSchema>;
|
||||||
export type NNMode = NNOptions['mode'];
|
export type NNMode = NNOptions['mode'];
|
||||||
|
|||||||
@@ -54,8 +54,10 @@ function waiting(s: OldMaidState): PlayerId[] {
|
|||||||
return finished(s) || !s.turn ? [] : [s.turn];
|
return finished(s) || !s.turn ? [] : [s.turn];
|
||||||
}
|
}
|
||||||
|
|
||||||
function turnMs(s: OldMaidState): number {
|
/** Turn clock in ms; null = 무제한 (an away player still gets the short clock). */
|
||||||
return s.turn && s.away[s.turn] ? AWAY_MS : s.options.turnSeconds * 1000;
|
function turnMs(s: OldMaidState): number | null {
|
||||||
|
if (s.turn && s.away[s.turn]) return AWAY_MS;
|
||||||
|
return s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
function pushLog(s: OldMaidState, e: LogEntry): void {
|
function pushLog(s: OldMaidState, e: LogEntry): void {
|
||||||
@@ -342,7 +344,7 @@ export const oldMaid: GameDefinition<OldMaidState, OldMaidAction, OldMaidView, O
|
|||||||
logCount: s.logCount,
|
logCount: s.logCount,
|
||||||
away: { ...s.away },
|
away: { ...s.away },
|
||||||
turnStartedAt: s.turnStartedAt,
|
turnStartedAt: s.turnStartedAt,
|
||||||
turnMs: turnMs(s),
|
turnMs: turnMs(s) ?? 0,
|
||||||
seq: s.seq,
|
seq: s.seq,
|
||||||
final: s.final,
|
final: s.final,
|
||||||
revealed: over ? per((p) => [...s.hands[p]!]) : null,
|
revealed: over ? per((p) => [...s.hands[p]!]) : null,
|
||||||
@@ -352,7 +354,8 @@ export const oldMaid: GameDefinition<OldMaidState, OldMaidAction, OldMaidView, O
|
|||||||
activePlayers: waiting,
|
activePlayers: waiting,
|
||||||
|
|
||||||
deadline(s) {
|
deadline(s) {
|
||||||
return finished(s) || !s.turn ? null : s.turnStartedAt + turnMs(s);
|
const ms = turnMs(s);
|
||||||
|
return finished(s) || !s.turn || ms === null ? null : s.turnStartedAt + ms;
|
||||||
},
|
},
|
||||||
|
|
||||||
timeoutPlayers: waiting,
|
timeoutPlayers: waiting,
|
||||||
|
|||||||
@@ -240,6 +240,28 @@ describe('시간 초과·나가기 (§8.5)', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('무제한 (turnSeconds null): 제한 시간 없음, 그래도 시간 초과(연결 끊김)는 뽑고 자리 비움이면 5초', () => {
|
||||||
|
expect(game.optionsSchema.safeParse({ turnSeconds: null }).success).toBe(true);
|
||||||
|
let s = rigged({ A: ['2H', '3H', '4H', '5H'], B: ['6H', '7H', '8H', '9H', X()], C: ['2S', '3S', '4S', '5S', '6S', '7S', '8S', '9S'] });
|
||||||
|
s.options = game.optionsSchema.parse({ turnSeconds: null });
|
||||||
|
expect(game.deadline!(s)).toBeNull();
|
||||||
|
expect(game.view(s, 'A').turnMs).toBe(0);
|
||||||
|
s = act(s, 'A', { type: 'timeout' });
|
||||||
|
expect(s.lastDraw).toMatchObject({ drawer: 'A', from: 'B', auto: true });
|
||||||
|
expect(game.deadline!(s)).toBeNull();
|
||||||
|
// A is away after 3 timeouts in a row: the short clock comes back for A only.
|
||||||
|
s.timeoutsInRow.A = 2;
|
||||||
|
s.turn = 'A';
|
||||||
|
s = act(s, 'A', { type: 'timeout' });
|
||||||
|
expect(s.away.A).toBe(true);
|
||||||
|
if (!s.final) {
|
||||||
|
expect(game.deadline!(s)).toBeNull();
|
||||||
|
s.turn = 'A';
|
||||||
|
expect(game.deadline!(s)).toBe(s.turnStartedAt + 5000);
|
||||||
|
expect(game.view(s, 'A').turnMs).toBe(5000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('모두 시간 초과만 해도 끝나고, 모든 상태에서 onTimeout이 합법', () => {
|
test('모두 시간 초과만 해도 끝나고, 모든 상태에서 onTimeout이 합법', () => {
|
||||||
for (const n of [2, 5, 8]) {
|
for (const n of [2, 5, 8]) {
|
||||||
let s = setup(Array.from({ length: n }, (_, i) => `P${i}`), n);
|
let s = setup(Array.from({ length: n }, (_, i) => `P${i}`), n);
|
||||||
|
|||||||
@@ -13,10 +13,11 @@ export const LOG_KEEP = 30;
|
|||||||
// ---------------------------------------------------------------- options
|
// ---------------------------------------------------------------- options
|
||||||
|
|
||||||
export const oldMaidOptionsSchema = z.object({
|
export const oldMaidOptionsSchema = z.object({
|
||||||
|
/** null = 무제한 (no turn clock; a dropped connection still gets an auto draw after the room's grace time). */
|
||||||
turnSeconds: z
|
turnSeconds: z
|
||||||
.union([z.literal(10), z.literal(20), z.literal(30), z.literal(60)])
|
.union([z.literal(10), z.literal(20), z.literal(30), z.literal(60), z.literal(null)])
|
||||||
.default(20)
|
.default(20)
|
||||||
.meta({ title: '한 번 뽑는 제한 시간', labels: { 10: '10초', 20: '20초', 30: '30초', 60: '60초' } }),
|
.meta({ title: '한 번 뽑는 제한 시간', labels: { 10: '10초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||||
});
|
});
|
||||||
export type OldMaidOptions = z.infer<typeof oldMaidOptionsSchema>;
|
export type OldMaidOptions = z.infer<typeof oldMaidOptionsSchema>;
|
||||||
|
|
||||||
@@ -120,6 +121,7 @@ export interface OldMaidView {
|
|||||||
logCount: number;
|
logCount: number;
|
||||||
away: Record<PlayerId, boolean>;
|
away: Record<PlayerId, boolean>;
|
||||||
turnStartedAt: number;
|
turnStartedAt: number;
|
||||||
|
/** Turn clock length in ms; 0 = 무제한 (no clock). */
|
||||||
turnMs: number;
|
turnMs: number;
|
||||||
seq: number;
|
seq: number;
|
||||||
final: OldMaidFinal | null;
|
final: OldMaidFinal | null;
|
||||||
|
|||||||
@@ -739,22 +739,29 @@ export function deadlineSig(s: PokerState): string {
|
|||||||
return `${h.phase}:${h.no}:${h.step}`;
|
return `${h.phase}:${h.no}:${h.step}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Length of the current deadline window in ms (§8.5), or 0 for none. */
|
/** Length of the current deadline window in ms (§8.5), or 0 for none.
|
||||||
|
* 무제한 (turnSeconds/rebuySeconds null): no clock, except the short away clock when everyone we wait for is away
|
||||||
|
* (a shared deadline would also time out the players who are not away). */
|
||||||
export function deadlineWindow(s: PokerState): number {
|
export function deadlineWindow(s: PokerState): number {
|
||||||
const o = s.options;
|
const o = s.options;
|
||||||
if (s.phase === 'finished') return 0;
|
if (s.phase === 'finished') return 0;
|
||||||
if (s.phase === 'rebuy') return o.rebuySeconds * 1000;
|
const isAway = (id: PlayerId) => (seatOf(s, id)?.timeoutsInRow ?? 0) >= 2;
|
||||||
|
const unlimited = (): number => {
|
||||||
|
const w = waitingFor(s);
|
||||||
|
return w.length > 0 && w.every(isAway) ? o.awaySeconds * 1000 : 0;
|
||||||
|
};
|
||||||
|
if (s.phase === 'rebuy') return o.rebuySeconds === null ? unlimited() : o.rebuySeconds * 1000;
|
||||||
const h = s.hand!;
|
const h = s.hand!;
|
||||||
switch (h.phase) {
|
switch (h.phase) {
|
||||||
case 'betting': {
|
case 'betting': {
|
||||||
if (h.bet.turn === null) return 0;
|
if (h.bet.turn === null) return 0;
|
||||||
const seat = seatOf(s, h.order[h.bet.turn]!)!;
|
if (isAway(h.order[h.bet.turn]!)) return o.awaySeconds * 1000;
|
||||||
return (seat.timeoutsInRow >= 2 ? o.awaySeconds : o.turnSeconds) * 1000;
|
return o.turnSeconds === null ? 0 : o.turnSeconds * 1000;
|
||||||
}
|
}
|
||||||
case 'choice':
|
case 'choice':
|
||||||
case 'draw':
|
case 'draw':
|
||||||
case 'declare':
|
case 'declare':
|
||||||
return (o.turnSeconds + 10) * 1000;
|
return o.turnSeconds === null ? unlimited() : (o.turnSeconds + 10) * 1000;
|
||||||
case 'handEnd':
|
case 'handEnd':
|
||||||
return o.handEndSeconds * 1000;
|
return o.handEndSeconds * 1000;
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ export const MODE_KO: Record<PokerMode, string> = {
|
|||||||
indian: '인디언 포커',
|
indian: '인디언 포커',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
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 pokerOptionsSchema = z
|
export const pokerOptionsSchema = z
|
||||||
.object({
|
.object({
|
||||||
mode: z.enum(MODES).default('sevenPoker').meta({ title: '게임 모드', labels: MODE_KO }),
|
mode: z.enum(MODES).default('sevenPoker').meta({ title: '게임 모드', labels: MODE_KO }),
|
||||||
@@ -54,10 +57,10 @@ export const pokerOptionsSchema = z
|
|||||||
.union([z.literal(1), z.literal(2), z.literal(3)])
|
.union([z.literal(1), z.literal(2), z.literal(3)])
|
||||||
.default(1)
|
.default(1)
|
||||||
.meta({ title: '리바이 횟수(횟수 제한일 때)', labels: { 1: '1번', 2: '2번', 3: '3번' } }),
|
.meta({ title: '리바이 횟수(횟수 제한일 때)', labels: { 1: '1번', 2: '2번', 3: '3번' } }),
|
||||||
turnSeconds: z
|
/** null = 무제한 (no clock for betting or the simultaneous steps; a dropped connection still gets auto moves after the room's grace time). */
|
||||||
.union([z.literal(15), z.literal(20), z.literal(30), z.literal(60)])
|
turnSeconds: lit(15, 20, 30, 60, null)
|
||||||
.default(20)
|
.default(20)
|
||||||
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }),
|
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||||
dealerRule: z
|
dealerRule: z
|
||||||
.enum(['rotate', 'winner'])
|
.enum(['rotate', 'winner'])
|
||||||
.default('rotate')
|
.default('rotate')
|
||||||
@@ -100,10 +103,10 @@ export const pokerOptionsSchema = z
|
|||||||
.union([z.literal(3), z.literal(4), z.literal(6), z.literal(10)])
|
.union([z.literal(3), z.literal(4), z.literal(6), z.literal(10)])
|
||||||
.default(4)
|
.default(4)
|
||||||
.meta({ title: '판 결과 보여 주는 시간', labels: { 3: '3초', 4: '4초', 6: '6초', 10: '10초' } }),
|
.meta({ title: '판 결과 보여 주는 시간', labels: { 3: '3초', 4: '4초', 6: '6초', 10: '10초' } }),
|
||||||
rebuySeconds: z
|
/** null = 무제한 (same rule as turnSeconds). */
|
||||||
.union([z.literal(10), z.literal(15), z.literal(30)])
|
rebuySeconds: lit(10, 15, 30, null)
|
||||||
.default(15)
|
.default(15)
|
||||||
.meta({ title: '리바이 고르는 시간', labels: { 10: '10초', 15: '15초', 30: '30초' } }),
|
.meta({ title: '리바이 고르는 시간', labels: { 10: '10초', 15: '15초', 30: '30초', null: '무제한' } }),
|
||||||
awaySeconds: z
|
awaySeconds: z
|
||||||
.union([z.literal(3), z.literal(5), z.literal(10)])
|
.union([z.literal(3), z.literal(5), z.literal(10)])
|
||||||
.default(5)
|
.default(5)
|
||||||
|
|||||||
@@ -180,6 +180,54 @@ describe('korean betting (§5.2)', () => {
|
|||||||
s = act(s, 'A', { type: 'k.check' });
|
s = act(s, 'A', { type: 'k.check' });
|
||||||
expect(view(s, null).seats[0]!.away).toBe(false);
|
expect(view(s, null).seats[0]!.away).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('poker 무제한: no clock for turns, simultaneous steps and the rebuy choice; timeout still works, away keeps the short clock', () => {
|
||||||
|
expect(poker.optionsSchema.parse({ turnSeconds: null, rebuySeconds: null })).toMatchObject({ turnSeconds: null, rebuySeconds: null });
|
||||||
|
expect(poker.optionsSchema.parse({})).toMatchObject({ turnSeconds: 20, rebuySeconds: 15 });
|
||||||
|
let s = mk({ mode: 'badugi', turnSeconds: null }, 3, { dealerSeat: 2 });
|
||||||
|
expect(s.deadlineAt).toBeNull();
|
||||||
|
expect(poker.deadline!(s)).toBeNull();
|
||||||
|
expect(view(s, null).deadlineTotalMs).toBe(0);
|
||||||
|
s = act(s, 'A', { type: 'timeout' }); // the room still times out a dropped player → auto check
|
||||||
|
expect(s.hand!.players.A!.lastAction).toBe('체크');
|
||||||
|
expect(s.deadlineAt).toBeNull();
|
||||||
|
s = act(s, 'B', { type: 'k.check' });
|
||||||
|
s = act(s, 'C', { type: 'k.check' });
|
||||||
|
expect(s.hand!.phase).toBe('draw');
|
||||||
|
expect(s.deadlineAt).toBeNull(); // simultaneous step: no clock either
|
||||||
|
s = act(s, 'A', { type: 'timeout' });
|
||||||
|
expect(view(s, null).seats[0]!.away).toBe(true);
|
||||||
|
expect(s.deadlineAt).toBeNull(); // B and C are not away → still no shared clock
|
||||||
|
s = act(s, 'B', { type: 'draw', cardIds: [] });
|
||||||
|
s = act(s, 'C', { type: 'draw', cardIds: [] });
|
||||||
|
expect(toAct(s)).toBe('A');
|
||||||
|
expect(s.deadlineAt! - clock).toBe(5_000); // away player's betting turn: short clock
|
||||||
|
s = act(s, 'A', { type: 'k.check' });
|
||||||
|
expect(view(s, null).seats[0]!.away).toBe(false);
|
||||||
|
expect(s.deadlineAt).toBeNull();
|
||||||
|
|
||||||
|
// simultaneous step where everyone we wait for is away → short clock
|
||||||
|
let d = mk({ mode: 'badugi', turnSeconds: null }, 2, { dealerSeat: 1 });
|
||||||
|
for (const id of ['A', 'B']) d.seats.find((x) => x.id === id)!.timeoutsInRow = 2;
|
||||||
|
d = act(d, toAct(d)!, { type: 'timeout' });
|
||||||
|
d = act(d, toAct(d)!, { type: 'timeout' });
|
||||||
|
expect(d.hand!.phase).toBe('draw');
|
||||||
|
expect(d.deadlineAt! - clock).toBe(5_000);
|
||||||
|
|
||||||
|
// rebuy choice: no clock; a timeout still declines
|
||||||
|
let t = mk({ mode: 'indian', rebuySeconds: null }, 3, { dealerSeat: 2, deck: deckOf('2S TS 3S', deckD20()) });
|
||||||
|
expect(t.deadlineAt! - clock).toBe(20_000);
|
||||||
|
t = act(t, 'A', { type: 'nl.allIn' });
|
||||||
|
t = act(t, 'B', { type: 'nl.fold' });
|
||||||
|
t = act(t, 'C', { type: 'nl.call' });
|
||||||
|
expect(t.deadlineAt! - clock).toBe(4_000); // result screen keeps its clock
|
||||||
|
t = readyAll(t);
|
||||||
|
expect(t.phase).toBe('rebuy');
|
||||||
|
expect(t.deadlineAt).toBeNull();
|
||||||
|
expect(poker.timeoutPlayers!(t)).toEqual(['A']);
|
||||||
|
t = act(t, 'A', { type: 'timeout' });
|
||||||
|
expect(t.seats[0]!.status).toBe('eliminated');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ------------------------------------------------------------------ 7포커
|
// ------------------------------------------------------------------ 7포커
|
||||||
|
|||||||
@@ -571,14 +571,17 @@ function validatePlay(s: UnoState, actor: PlayerId, a: PlayAction): Validation {
|
|||||||
return ok;
|
return ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Turn clock in ms; null = 무제한 (away players still get the short clock). */
|
||||||
|
const turnMs = (s: UnoState, p: PlayerId): number | null => (s.away[p] ? AWAY_MS : s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000);
|
||||||
|
|
||||||
function deadlineMs(s: UnoState): number | null {
|
function deadlineMs(s: UnoState): number | null {
|
||||||
switch (s.phase.kind) {
|
switch (s.phase.kind) {
|
||||||
case 'startColor':
|
case 'startColor':
|
||||||
case 'turn':
|
case 'turn':
|
||||||
case 'afterDraw':
|
case 'afterDraw':
|
||||||
return s.away[s.current] ? AWAY_MS : s.options.turnSeconds * 1000;
|
return turnMs(s, s.current);
|
||||||
case 'wild4':
|
case 'wild4':
|
||||||
return s.away[s.phase.target] ? AWAY_MS : s.options.turnSeconds * 1000;
|
return turnMs(s, s.phase.target);
|
||||||
case 'roundEnd':
|
case 'roundEnd':
|
||||||
return ROUND_END_MS;
|
return ROUND_END_MS;
|
||||||
case 'finished':
|
case 'finished':
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { z } from 'zod';
|
|||||||
import type { PlayerId } from '@bg/engine';
|
import type { PlayerId } from '@bg/engine';
|
||||||
import type { Color, UnoCard } from '../one-card/cards';
|
import type { Color, UnoCard } from '../one-card/cards';
|
||||||
|
|
||||||
const lit = <T extends string | number>(...vals: T[]) =>
|
const lit = <T extends string | number | null>(...vals: T[]) =>
|
||||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||||
|
|
||||||
const colorSchema = z.enum(['R', 'Y', 'G', 'B']);
|
const colorSchema = z.enum(['R', 'Y', 'G', 'B']);
|
||||||
@@ -22,9 +22,10 @@ export const unoOptionsSchema = z.object({
|
|||||||
}),
|
}),
|
||||||
stacking: z.boolean().default(false).meta({ title: '(하우스 룰) 드로우 카드 쌓기' }),
|
stacking: z.boolean().default(false).meta({ title: '(하우스 룰) 드로우 카드 쌓기' }),
|
||||||
drawUntilPlayable: z.boolean().default(false).meta({ title: '(하우스 룰) 낼 수 있을 때까지 뽑기' }),
|
drawUntilPlayable: z.boolean().default(false).meta({ title: '(하우스 룰) 낼 수 있을 때까지 뽑기' }),
|
||||||
turnSeconds: lit(10, 15, 20, 30, 60)
|
/** null = 무제한 (no turn clock; a dropped connection still gets auto moves after the room's grace time). */
|
||||||
|
turnSeconds: lit(10, 15, 20, 30, 60, null)
|
||||||
.default(20)
|
.default(20)
|
||||||
.meta({ title: '한 턴 제한 시간', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }),
|
.meta({ title: '한 턴 제한 시간', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||||
});
|
});
|
||||||
export type UnoOptions = z.infer<typeof unoOptionsSchema>;
|
export type UnoOptions = z.infer<typeof unoOptionsSchema>;
|
||||||
|
|
||||||
|
|||||||
@@ -461,6 +461,22 @@ describe('시간 초과와 나가기 (§8.5)', () => {
|
|||||||
expect(s.away.A).toBe(false);
|
expect(s.away.A).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('무제한 (turnSeconds null): no turn clock, but timeouts (dropped connection) still play and lead to away', () => {
|
||||||
|
expect(uno.optionsSchema.safeParse({ turnSeconds: null }).success).toBe(true);
|
||||||
|
let s = rig(make({ turnSeconds: null }), { hands: { A: ['B9a', 'B8a', 'B7a', 'B6a'], B: ['G2a', 'G3a', 'G4a'], C: ['Y3a', 'Y4a', 'Y5a'] }, discard: ['R5a'] });
|
||||||
|
expect(uno.deadline!(s)).toBeNull();
|
||||||
|
expect(uno.view(s, 'A').deadlineTotalMs).toBe(0);
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
s.current = 'A';
|
||||||
|
s.phase = { kind: 'turn' };
|
||||||
|
s = act(s, 'A', { type: 'timeout' });
|
||||||
|
}
|
||||||
|
expect(s.away.A).toBe(true);
|
||||||
|
s.current = 'A';
|
||||||
|
s.phase = { kind: 'turn' };
|
||||||
|
expect(uno.deadline!(s)).toBe(s.turnStartedAt + 5000);
|
||||||
|
});
|
||||||
|
|
||||||
test('leaving: the hand goes under the draw pile, the turn moves on; the last one left wins', () => {
|
test('leaving: the hand goes under the draw pile, the turn moves on; the last one left wins', () => {
|
||||||
let s = rig(make(), { hands: { A: ['R1a', 'R2a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
let s = rig(make(), { hands: { A: ['R1a', 'R2a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||||||
expect(uno.onLeave!(s, 'A')).toEqual({ type: 'leave' });
|
expect(uno.onLeave!(s, 'A')).toEqual({ type: 'leave' });
|
||||||
|
|||||||
Reference in New Issue
Block a user