카드 게임 시간 무제한(우노·뱅!·달무티·고스톱·도둑잡기·포커·바퀴벌레 포커·99), 공통 카드 움직임(card-fx), 우노·달무티·도둑잡기·포커 소리·애니메이션

- 무제한(null): 차례 시계·타임아웃 없음, 자리 비움만 짧은 시계, 연결 끊김은 방 유예 뒤 자동 행동 그대로
- 포커는 리바이 고르는 시간도 무제한 가능, 고스톱은 고·스톱 선택 시간도 무제한 가능, 뱅!은 반응 시간·캐릭터 고르기도
- card-fx: 날아가는 카드·칩(ghost), 제자리 날아오기, 배너, view 변화 감지 훅(처음 렌더·다시 보기는 건너뜀)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 13:04:11 +09:00
parent f12cf12b84
commit ac37a6a6d8
44 changed files with 1438 additions and 198 deletions

View File

@@ -28,7 +28,7 @@ function practice(options: Record<string, unknown> = {}) {
room.addBot('A');
room.configure('A', { options: { ...(room.config.options as object), ...options } });
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). */
@@ -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'));
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);
});

View File

@@ -77,7 +77,7 @@ export function helpNow(v: BangView, me: string | null, players: Record<string,
if (use.length >= p.needed) {
const label = use.map((c) => NAME[c.kind as 'bang' | 'missed'] ?? '빗나감!').join(' + ');
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)]를 눌러요.`);
if (p.canBarrel) lines.push('[술통 판정하기]를 누르면 카드를 한 장 뒤집어 ♥가 나올 때 피해요.');
lines.push(life);

View File

@@ -1034,7 +1034,7 @@ function BangSide({ view: v, me, players }: BoardProps<BangView>) {
{v.winner ? ' · 게임 끝' : ''}
</strong>
<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>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
{v.players.map((p) => (
@@ -1132,7 +1132,7 @@ function statusText(v: BangView, me: string | null, players: Record<string, Publ
// ---------------------------------------------------------------- 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 (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
@@ -1168,10 +1168,10 @@ function Options({ value: o, onChange }: OptionsProps<BangOptions>) {
<Seg label="캐릭터 정하기" value={o.characterDraft} options={[['random', '무작위 1장'], ['choose2', '2장 중 고르기']]} onChange={(characterDraft) => set({ characterDraft })} />
</Field>
<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 label="반응 제한 시간" help="빗나감!·맥주·결투·잡화점을 고르는 시간이에요.">
<Seg label="반응 제한 시간" value={o.reactionSeconds} options={[[8, '8초'], [15, '15초'], [25, '25초']]} onChange={(reactionSeconds) => set({ reactionSeconds })} />
<Field label="반응 제한 시간" help="빗나감!·맥주·결투·잡화점을 고르는 시간이에요. 무제한이어도 연결이 끊긴 채 오래 돌아오지 않으면 자동으로 골라요.">
<Seg label="반응 제한 시간" value={o.reactionSeconds} options={[[8, '8초'], [15, '15초'], [25, '25초'], [null, '무제한']]} onChange={(reactionSeconds) => set({ reactionSeconds })} />
</Field>
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
@@ -1208,8 +1208,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 {
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.drawBeforeDeath || o.beerAtFullHealth || o.selfTargetCatBalou || o.deputyCount7) parts.push('하우스 룰');
return parts.join(' · ');
@@ -1239,7 +1241,7 @@ function CardTable() {
);
}
function Rules() {
function Rules({ options }: { options?: BangOptions }) {
return (
<div className="stack">
<p>
@@ -1256,7 +1258,10 @@ function Rules() {
<p>
생명이 0이 되면 맥주로 살아날 수 있어요(2명 남으면 안 돼요). 무법자를 쓰러뜨리면 카드 3장을 받고, 보안관이 부관을 쓰러뜨리면 카드를 모두 버려요. 쓰러진 사람의 역할은 공개돼요.
</p>
<p className="small muted">반응 시간이 지나면 막을 카드가 있을 때 자동으로 내요(설정에서 끌 수 있어요). 내 역할은 역할 카드를 꾹 누르고 있을 때만 보여요.</p>
<p className="small muted">
{options?.reactionSeconds === null ? '이 방은 반응 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '반응 시간이 지나면'} 막을 카드가 있을 때 자동으로 내요(설정에서 끌 수
있어요).{options?.turnSeconds === null ? ' 내 턴도 시간 제한이 없고, 연결이 끊긴 채 오래 돌아오지 않으면 턴을 자동으로 마쳐요.' : ''} 내 역할은 역할 카드를 꾹 누르고 있을 때만 보여요.
</p>
<CardTable />
<table className="bg-rules small" style={{ borderCollapse: 'collapse', width: '100%' }}>
<tbody>

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

View File

@@ -956,7 +956,7 @@ function statusText(v: CockroachView, me: string | null, players: Record<string,
// ---------------------------------------------------------------- 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 (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
@@ -986,7 +986,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 })} />
</Field>
<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 label="이번 라운드 주장 기록">
<Seg label="이번 라운드 주장 기록" value={o.claimHistory} options={[[true, '보이기'], [false, '숨기기']]} onChange={(claimHistory) => set({ claimHistory })} />
@@ -1015,7 +1015,7 @@ function optionsSummary(o: CockroachOptions, players?: number): string {
const lose = o.loseCount === 'auto' ? (players ? `${players === 2 ? 5 : 4}장` : '자동(2명 5장, 그 외 4장)') : `${o.loseCount}장`;
return [
`같은 벌레 ${lose}이면 패배`,
`제한 ${o.turnSeconds}초`,
o.turnSeconds === null ? '시간 무제한' : `제한 ${o.turnSeconds}초`,
...(o.claimHistory ? [] : ['주장 기록 숨김']),
...(o.quickChat ? [] : ['빠른 말 끔']),
...(o.eightKindsRule ? ['8종 모으면 패배'] : []),
@@ -1058,7 +1058,7 @@ function Rules({ options }: { options?: CockroachOptions }) {
<p>카드를 앞마당에 놓은 사람이 다음 라운드를 시작해요. 그때 손에 카드가 한 장도 없으면 바로 져요.</p>
{o?.eightKindsRule && <p>하우스 룰: 앞마당에 8종을 모두 한 장 이상 모아도 져요.</p>}
<p className="muted">
시간 안에 고르지 않으면 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
것으로 끝나요.
</p>
</div>

View File

@@ -1,10 +1,11 @@
/** 달무티 화면 (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 { PublicUser } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { TurnTimer } from '../../components/TurnTimer';
import { haptic, sounds } from '../../lib/feedback';
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries } from '../card-fx';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
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 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 = `
.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; }
@@ -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;
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.anim-glow { animation: anim-glow 1.4s ease-in-out infinite; }
.dm-seat.me { background: var(--primary-soft); }
.dm-seat.out { opacity: .7; }
.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-set { display: flex; }
.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;
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; }
@@ -129,10 +176,9 @@ const CSS = `
.dm-flip { animation: dm-flip .7s ease both; }
@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-fly { from { transform: translateY(40px) scale(.85); opacity: .2; } to { transform: none; opacity: 1; } }
@keyframes dm-flip { from { transform: rotateY(180deg); } to { transform: none; } }
@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) {
.dm { gap: 8px; }
@@ -195,7 +241,8 @@ function Seats({ v, players, me, deadline }: { v: DalmutiView; players: Record<s
return (
<li
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` }}
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 curName = v.current === me ? '내' : `${nick(players, v.current ?? '')}님`;
return (
<div className="dm-table" role="region" aria-label="바닥">
<div className="dm-table" data-fx="dm-center" role="region" aria-label="바닥">
{top ? (
<>
<div className="dm-now" aria-live="polite">
@@ -339,6 +386,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
setSel(null);
return;
}
sfx.select();
if (top) setSel({ rank: g.n, count: top.count, mix: ch.needsJester });
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 = () => {
if (!ids || !legal) return;
rememberPlay(sel!.rank);
act({ type: 'play', cardIds: ids });
setSel(null);
};
@@ -374,7 +423,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
</strong>
{mine && <span className="small muted">{top ? `${setText(top)}보다 낮은 숫자를 골라요` : '낼 숫자를 골라요'}</span>}
</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) => {
const c = choice(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 done = v.seats.filter((s) => s.confirmed).length;
return (
<div className="dm-panel">
<div className="dm-panel" data-fx="dm-center">
<h3>
{v.round}라운드 준비 · 손패 확인 ({done}/{v.seats.length})
</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 toggle = (id: string) => {
if (!owe) return;
sfx.select();
if (picked.includes(id)) setPicked(picked.filter((x) => x !== id));
else setPicked(picked.length >= owe.count ? [...picked.slice(1), id] : [...picked, id]);
};
return (
<div className={`dm-panel${owe ? ' hot' : ''}`}>
<div className={`dm-panel${owe ? ' hot' : ''}`} data-fx="dm-center">
<h3>세금 카드 교환</h3>
<RoundRecap v={v} players={players} me={me} />
<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 prevMine = useRef(false);
const lastLog = v.log[v.log.length - 1];
const [banner, showBanner] = useBanner();
useDalmutiFx(v, me, players, showBanner);
useEffect(() => {
if (mine && !prevMine.current) {
haptic(40);
@@ -715,10 +767,101 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
<p className="sr-only" aria-live="polite">
{announce}
</p>
{banner}
</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
function rulesLine(o: DalmutiOptions): string {
@@ -729,7 +872,7 @@ function rulesLine(o: DalmutiOptions): string {
o.jesterTaxable ? '세금에 광대 포함' : '세금에 광대 빼기',
o.passLocksOut ? '패스하면 트릭에서 빠짐' : '패스해도 다시 낼 수 있음',
o.removeHighCards ? '9~12 빼기' : '',
`${o.turnSeconds}초`,
o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`,
]
.filter(Boolean)
.join(' · ');
@@ -853,7 +996,7 @@ function statusText(v: DalmutiView, me: string | null, players: Record<string, P
// ---------------------------------------------------------------- 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 (
<div className="segmented" role="group" aria-label={label}>
{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 })} />
</Field>
<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>
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
@@ -926,7 +1069,7 @@ function optionsSummary(o: DalmutiOptions): string {
if (o.jesterTaxable) parts.push('세금에 광대');
if (o.passLocksOut) parts.push('패스하면 빠짐');
if (o.removeHighCards) parts.push('9~12 빼기');
parts.push(`${o.turnSeconds}초`);
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
return parts.join(' · ');
}
@@ -990,7 +1133,10 @@ function Rules({ options }: { options?: DalmutiOptions }) {
라운드에서 1등은 (사람 수 − 1)점, 마지막 순위는 0점을 받아요. {o?.scoring === 'last-round' ? '이 방은 마지막 라운드 순위가 최종 순위예요.' : '총점이 높은 사람이 이기고, 같으면 마지막 라운드 순위로 정해요.'}{' '}
점수는 이 방 안에서만 쓰는 표시용이에요.
</p>
<p>시간 안에 고르지 않으면 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는 패스해요.</p>
<p>
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는
패스해요.
</p>
<CardTable removeHigh={o?.removeHighCards} />
</div>
);

View File

@@ -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 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') {
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);
lines.push('광팔기 차례예요. 4~5명이면 이번 판은 3명만 쳐요(선은 꼭 쳐요).');
lines.push(
`[치기]를 누르면 이번 판에 참가해요. ${n > 0 ? `[죽기 · 광 ${n}장 팔기]를 누르면 ${gain}점을 받고 이번 판은 쉬어요.` : '[죽기]를 누르면 팔 패가 없어 그냥 쉬어요.'} 시간이 지나면 죽기로 정해져요.`,
`[치기]를 누르면 이번 판에 참가해요. ${n > 0 ? `[죽기 · 광 ${n}장 팔기]를 누르면 ${gain}점을 받고 이번 판은 쉬어요.` : '[죽기]를 누르면 팔 패가 없어 그냥 쉬어요.'} ${late('죽기로 정해져요.')}`,
);
} else if (seat) {
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;
lines.push(`총통이에요! 손에 같은 월 4장${months.length ? `(${months.map((m) => `${m}월`).join(', ')})` : ''}이 있어요.`);
lines.push(`[총통 선언]을 누르면 이번 판을 바로 이기고 상대마다 ${each}점, 모두 ${each * others}점을 받아요. [그냥 치기]를 누르면 판을 계속하고, 그 월로 흔들기나 폭탄을 할 수 있어요.`);
lines.push('시간이 지나면 총통 선언으로 정해져요.');
lines.push(late('총통 선언으로 정해져요.'));
} else {
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;
if (seat && who === me && pf) {
lines.push(`뒤집은 ${pf.flipped.name}과(와) 같은 월 패가 바닥에 2장(${pf.options.map((c) => c.name).join(', ')}) 있어요. 창에서 가져올 패를 눌러 골라요.`);
lines.push('시간이 지나면 더 좋은 패를 저절로 가져와요.');
lines.push(late('더 좋은 패를 저절로 가져와요.'));
} else {
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.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('시간이 지나면 스톱으로 정해져요.');
lines.push(late('스톱으로 정해져요.'));
} else {
lines.push(`${nm(who)}이 ${g ? `${g.score}점을 내서 ` : ''}고 또는 스톱을 고르는 중이에요. 스톱하면 이번 판이 끝나요.`);
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;
if (seat && who === me && g) {
lines.push('판이 끝나기 전에 내가 가진 9월 열끗(국진)을 어떻게 셀지 골라요.');
lines.push(`[열끗으로]: 내 점수 ${g.yeolScore}점. [쌍피로](피 2장 값): 내 점수 ${g.piScore}점. 시간이 지나면 나에게 유리한 쪽으로 정해져요.`);
lines.push(`[열끗으로]: 내 점수 ${g.yeolScore}점. [쌍피로](피 2장 값): 내 점수 ${g.piScore}점. ${late('나에게 유리한 쪽으로 정해져요.')}`);
} else {
lines.push(`스톱이 나왔어요. ${nm(who)}이 9월 열끗(국진)을 열끗으로 셀지 쌍피로 셀지 정하는 중이에요. 정하면 이번 판 점수를 계산해요.`);
}

View File

@@ -51,7 +51,7 @@ function totalMsOf(v: GostopView): number {
if (v.phase === 'roundResult') return 10_000;
const who = v.step === 'sell' ? v.sell?.current : v.turn;
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). */
@@ -672,7 +672,7 @@ function Decisions({ view: v, me, players, act, pending }: BoardProps<GostopView
return (
<Sheet onClose={nop} label="국진 정하기">
<h2>9월 열끗(국진)을 어떻게 쓸까요?</h2>
<p className="muted">열끗 1장 또는 쌍피(피 2장 값)로 셀 수 있어요. 시간이 지나면 나에게 유리한 쪽으로 정해져요.</p>
<p className="muted">열끗 1장 또는 쌍피(피 2장 값)로 셀 수 있어요.{v.rules.decisionSeconds === null ? '' : ' 시간이 지나면 나에게 유리한 쪽으로 정해져요.'}</p>
<div className="gs-big">
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'gukjin', as: 'yeol' })}>
열끗으로<small>내 점수 {g.yeolScore}점</small>
@@ -1033,12 +1033,14 @@ function Rules({ options }: { options?: GostopOptions }) {
</div>
<strong>족보</strong>
<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>
);
}
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 (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
@@ -1080,7 +1082,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 })} />
</Field>
<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>
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
@@ -1091,7 +1093,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 })} />
</Field>
<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 label="피박 기준(진 사람 피 값)">
<Seg label="피박 기준" value={o.piBakLimit} options={[['auto', '자동(맞고 7·고스톱 5)'], [5, '5 이하'], [6, '6 이하'], [7, '7 이하']]} onChange={(piBakLimit) => set({ piBakLimit })} />
@@ -1155,7 +1157,7 @@ function optionsSummary(o: GostopOptions): string {
return [
`${o.rounds}판`,
o.winScore === 'auto' ? '맞고 7점·고스톱 3점' : `${o.winScore}점 나기`,
`${o.turnSeconds}초`,
o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`,
o.bonusCards === 'none' ? '보너스패 없음' : o.bonusCards === 'auto' ? '' : `보너스 ${o.bonusCards}`,
o.gwangPalgi ? '' : '광팔기 없음',
]

View File

@@ -686,7 +686,7 @@ function statusText(v: NinetyNineView, me: string | null, players: Record<string
// ---------------------------------------------------------------- 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 (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
@@ -735,7 +735,7 @@ function Options({ value: o, onChange }: OptionsProps<NNOptions>) {
/>
</Field>
<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>
{kr && (
<button type="button" className="btn btn-secondary" onClick={() => set({ jokerRange: '0-99', handSize: 'auto' })}>
@@ -790,7 +790,7 @@ function optionsSummary(o: NNOptions): string {
if (o.mode === 'kr-product' && o.startTotal === 'zero') parts.push('0부터 시작');
if (!o.refill) parts.push('보충 없음');
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(' · ');
}
@@ -872,7 +872,7 @@ function Rules({ options }: { options?: NNOptions }) {
</p>
<SpecialTable o={o} />
<p className="small muted">
시간 안에 내지 않으면 합계가 가장 작아지는 카드를 자동으로 내요. 어린이와 할 때는 조커 0~99를 추천해요. 목숨(하트)은 이 판에서만 쓰는 표시예요.
{o.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 내지 않으면'} 합계가 가장 작아지는 카드를 자동으로 내요. 어린이와 할 때는 조커 0~99를 추천해요. 목숨(하트)은 이 판에서만 쓰는 표시예요.
</p>
</div>
);

View File

@@ -1,13 +1,14 @@
/** 도둑잡기 화면 (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 { PublicUser } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { TurnTimer } from '../../components/TurnTimer';
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 type { BoardProps, GameUI, OptionsProps } from '../types';
import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useChange, useNewEntries } from '../card-fx';
import { helpNow } from './help';
import { quickStart } from './quick';
@@ -15,6 +16,35 @@ import { quickStart } from './quick';
const JOKER = 'X1';
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 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)}님`);
@@ -122,7 +152,7 @@ button.om-back:hover:not(:disabled) { transform: translateY(-5px); }
function Card({ card, className }: { card: string | null; className?: string }) {
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">
<PlayingCard card={card} size="lg" style={{ width: '100%', height: '100%', filter: 'none' }} />
</span>
@@ -158,9 +188,9 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaid
const u = userOf(players, id);
const st = v.status[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 (
<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 && (
<span className="om-bubble" aria-hidden>
{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]]);
const draw = (index: number) => {
if (pending) return;
myDrawRect = document.querySelectorAll('.om-fan button.om-back')[index]?.getBoundingClientRect() ?? null;
act({ type: 'draw', from: target, index });
setSel(null);
};
const tap = (i: number) => {
if (!mine) return;
if (sel === i || !tapConfirm) draw(i);
else setSel(i);
else {
setSel(i);
sfx.select();
}
};
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
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 total = Object.values(v.pairCounts).reduce((a, b) => a + b, 0);
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>
{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[1]} />
</span>
@@ -308,11 +342,11 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record<strin
if (v.phase === 'finished') {
const f = v.final!;
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>
{f.thief ? (
<>
<Card card={JOKER} />
<Card card={JOKER} className="om-thief-joker" />
<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 target = v.target;
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">
<span>{who(players, drawer, me)}</span>
<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 }) {
const hand = v.myHand ?? [];
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 (
<section className={cls} aria-label="내 자리">
<section className={cls} data-fx-seat={me} aria-label="내 자리">
{bubble && (
<span className="om-bubble" aria-hidden>
{bubble}
@@ -382,7 +416,7 @@ function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v:
)}
</div>
{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) => (
<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(' ')} />
@@ -408,6 +442,8 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
const [shake, setShake] = useState(false);
const [fresh, setFresh] = useState<string | null>(null);
const prev = useRef({ logCount: v.logCount, hand: v.myHand ?? [], turn: v.turn });
const [banner, showBanner] = useBanner();
useOldMaidFx(v, me, players, showBanner);
useEffect(() => {
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">
{announce}
</p>
{banner}
</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
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
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 (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
@@ -591,6 +736,7 @@ function Options({ value: o, onChange }: OptionsProps<OldMaidOptions>) {
[20, '20초'],
[30, '30초'],
[60, '60초'],
[null, '무제한'],
]}
onChange={(turnSeconds) => onChange({ ...o, turnSeconds })}
/>
@@ -600,7 +746,7 @@ function Options({ value: o, onChange }: OptionsProps<OldMaidOptions>) {
}
function optionsSummary(o: OldMaidOptions): string {
return `트럼프 52장 + 조커 1장 · 제한 ${o.turnSeconds}초`;
return `트럼프 52장 + 조커 1장 · ${o.turnSeconds === null ? '시간 무제한' : `제한 ${o.turnSeconds}초`}`;
}
function Rules({ options }: { options?: OldMaidOptions }) {
@@ -631,7 +777,10 @@ function Rules({ options }: { options?: OldMaidOptions }) {
<strong>끝</strong>: 손패를 다 턴 사람은 빠지고, 먼저 턴 순서대로 1등, 2등…이에요. 짝이 다 버려지면 조커 한 장만 남고, 그걸 든 사람이 도둑이에요.
</p>
<p className="muted">
{options?.turnSeconds ?? 20}초 안에 고르지 않으면 무작위로 한 장을 뽑아요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 카드를 든 채 게임을 나가면 그 사람 카드는 섞어서 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고(짝이
{options?.turnSeconds === null
? '시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 무작위로 한 장을 대신 뽑아 주고, 그런 일이 세 번 연속이면 그 사람은 5초 안에 뽑아야 해요.'
: `${options?.turnSeconds ?? 20}초 안에 고르지 않으면 무작위로 한 장을 뽑아요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요.`}{' '}
카드를 든 채 게임을 나가면 그 사람 카드는 섞어서 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고(짝이
생기면 버려요), 나간 사람은 맨 아래 등수가 돼요. 둘만 남았을 때 한 사람이 나가면 도둑 없이 끝나요.
</p>
</div>

View File

@@ -1,12 +1,13 @@
/** 포커 화면 (docs/games/poker.md §9). Chips are room-only play points. */
import { useEffect, useRef, useState } from 'react';
import type { BetActionType, LegalBetView, PokerMode, PokerOptions, PokerView, SeatView, Side, ViewCard } from '@bg/games/poker';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import type { BetActionType, LegalBetView, LogEntry, PokerMode, PokerOptions, PokerView, SeatView, Side, ViewCard } from '@bg/games/poker';
import type { PublicUser } from '@bg/shared/lite';
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
import { TurnTimer } from '../../components/TurnTimer';
import { PlayingCard } from '../../components/cards/PlayingCard';
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 { helpNow } from './help';
import { quickStart } from './quick';
@@ -119,7 +120,7 @@ function SeatCards({ seat, v, me }: { seat: SeatView; v: PokerView; me: string |
if (!cards.length) return null;
const best = new Set(sd?.best ?? []);
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) => (
<PlayingCard
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', '보스(먼저 베팅)']);
return (
<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}
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(', ')}` : ''}`}
>
<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 penalty = v.penalties.reduce((a, p) => a + p.amount, 0);
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>}
{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 />))}
</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)}
</div>
{v.pots.length > 1 && (
@@ -239,6 +241,8 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
const prevWaiting = useRef(false);
const mine = isMyTurn(v, me);
const showKey = `${v.handNo}-${v.handPhase}`;
const [banner, showBanner] = useBanner();
usePokerFx(v, me, players, showBanner);
useEffect(() => {
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">
{announce}
</p>
{banner}
</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 {
if (!v.awards) return '';
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 best = new Set(sd?.best ?? []);
return (
<div className="pk-mine" aria-label="내 카드">
<div className="pk-mine" aria-label="내 카드" data-fx="poker-mine">
{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 : '내 이마 카드(나만 못 봐요)'} />
<span className="small muted">이마</span>
</div>
)}
{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)} />
{(isSevenMode(v.mode) || v.mode === 'indian') && <span className="small muted">{v.mode === 'indian' ? '손' : '나만 봄'}</span>}
</div>
))}
{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)} />
<span className="small muted">공개</span>
</div>
@@ -397,6 +650,7 @@ function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unkno
const [discard, setDiscard] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const tap = (c: string) => {
sfx.select();
if (!discard) setDiscard(c);
else if (c === discard) {
setDiscard(null);
@@ -410,9 +664,9 @@ function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unkno
<br />
<span className="small muted">버린 카드는 아무에게도 보이지 않아요. 남는 2장은 나만 봐요.</span>
</p>
<div className="pk-mine">
<div className="pk-mine" data-fx="poker-mine">
{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} />
</span>
))}
@@ -457,7 +711,11 @@ function DrawPicker({ v, hole, act, pending }: { v: PokerView; hole: string[]; a
</p>
<div className="pk-mine">
{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>
{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
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 (
<div className="segmented">
{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 })} />}
</Field>
<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>
{o.mode === 'indian' && (
<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 })} />
{o.rebuy === 'limited' && <Seg value={o.rebuyLimit} options={[[1, '1번'], [2, '2번'], [3, '3번']]} onChange={(rebuyLimit) => set({ rebuyLimit })} />}
</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배로 올리기">
<Seg value={o.blindUpEvery} options={[[0, '안 올림'], [5, '5판마다'], [10, '10판마다'], [15, '15판마다']]} onChange={(blindUpEvery) => set({ blindUpEvery })} />
</Field>
@@ -933,7 +1196,7 @@ function Options({ value: o, onChange }: OptionsProps<PokerOptions>) {
function optionsSummary(o: PokerOptions): string {
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)
.join(' · ');
}
@@ -974,7 +1237,11 @@ function Rules({ options }: { options?: PokerOptions }) {
{o?.rebuy === 'off' ? '탈락하고 구경해요.' : '칩을 다시 받을지 고를 수 있어요. 다시 받은 만큼 최종 점수에서 빠져요.'}{' '}
{o?.endCondition === 'lastStanding' ? '칩을 가진 사람이 한 명 남으면 끝나요.' : '정해진 판 수가 끝나면 (마지막 칩 − 시작 칩 × 다시 받은 횟수)로 순위를 정해요.'}
</p>
<p>시간 안에 고르지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 처리돼요. 두 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 짧아져요.</p>
{o?.turnSeconds === null ? (
<p>시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 자동 처리돼요. 이렇게 두 번 연속 넘어가면 '자리 비움'이 되고 짧은 제한 시간이 생겨요.</p>
) : (
<p>시간 안에 고르지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 처리돼요. 두 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 짧아져요.</p>
)}
</div>
);
}

View File

@@ -4,7 +4,8 @@ import type { CardFace, Color, LogEntry, SeatView, UnoCard, UnoOptions, UnoView
import type { PublicUser } from '@bg/shared/lite';
import { Avatar, Sheet } from '../../components/ui';
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 type { BoardProps, GameUI, OptionsProps } from '../types';
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';
/** 우노 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[] {
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);
@@ -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::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.top { animation: un-fly .28s ease-out; }
.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 .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-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; }
@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-shake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-8deg); } 75% { transform: rotate(8deg); } }
@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 }) {
const u = userOf(players, s.id);
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' }}>
<Avatar user={u} size={24} />
<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);
return (
<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} />
<span className="cnt" aria-hidden>
{v.drawPileCount}
@@ -235,7 +258,7 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: UnoView; pl
</div>
<div className="un-info">
{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 />
지금 색: {COLOR_KO[v.color]}
</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 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> = {}) => {
rememberPlay(id);
act({ type: 'play', cardId: id, ...extra, ...(armed && my.hand.length === 2 ? { uno: true } : {}) });
setSel(null);
setPick(null);
@@ -336,6 +364,7 @@ function MyHand({ v, act, pending, players }: { v: UnoView; act: (a: unknown) =>
}
setNote('');
setSel(c.id);
sfx.select();
};
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
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
ref={ref}
data-fx="uno-hand"
className={`un-hand${phone ? ' wrap' : ''}`}
role="group"
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));
}, [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 others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
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' })}
onDropCard={(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} />
@@ -662,10 +698,105 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
<p className="sr-only" aria-live="polite">
{announce}
</p>
{banner}
</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
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>
<ol className="un-log">
{[...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)}
</li>
))}
@@ -777,7 +908,7 @@ function statusText(v: UnoView, me: string | null, players: Record<string, Publi
// ---------------------------------------------------------------- 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 (
<div className="segmented" role="group" aria-label={label}>
{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 })} />
</Field>
<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>
</div>
);
@@ -834,7 +965,7 @@ function optionsSummary(o: UnoOptions): string {
const parts = [o.scoring === 'to500' ? '500점 먼저' : '한 판', o.wild4Rule === 'challenge' ? '+4 도전' : '+4 제한'];
if (o.stacking) parts.push('쌓기');
if (o.drawUntilPlayable) parts.push('나올 때까지 뽑기');
parts.push(`${o.turnSeconds}초`);
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
return parts.join(' · ');
}
@@ -897,7 +1028,10 @@ function Rules({ options }: { options?: UnoOptions }) {
<strong>점수</strong>: 이긴 사람은 다른 사람 손에 남은 카드 점수(숫자 그대로, 스킵·리버스·드로우2 20점, 와일드 50점)를 얻어요.
{o.scoring === 'to500' ? ' 여러 판을 해서 500점에 먼저 닿으면 이겨요.' : ' 이 방은 한 판으로 끝나요.'}
</p>
<p>시간 안에 고르지 않으면 낼 수 있는 카드 하나를 자동으로 내요(와일드는 가장 많이 가진 색). 낼 카드가 없으면 1장 뽑아요.</p>
<p>
{o.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 낼 수 있는 카드 하나를 자동으로 내요(와일드는 가장 많이
가진 색). 낼 카드가 없으면 1장 뽑아요.
</p>
</div>
);
}

View File

@@ -11,8 +11,8 @@
| 옵션 키 | 설명 | 선택지 | 기본값 |
|---|---|---|---|
| `characterDraft` | 캐릭터 배정 방식 | `random`(1장 무작위) / `choose2`(2장 중 1장 선택) | `random` |
| `turnSeconds` | 내 턴 제한 시간(초) | 30 / 60 / 90 / 120 | 60 |
| `reactionSeconds` | 반응(빗나감!/맥주/결투 응수/잡화점 선택) 제한 시간(초) | 8 / 15 / 25 | 15 |
| `turnSeconds` | 내 턴 제한 시간(초) | 30 / 60 / 90 / 120 / 무제한(`null`, 캐릭터 2장 중 고르기 30초도 없앰) | 60 |
| `reactionSeconds` | 반응(빗나감!/맥주/결투 응수/잡화점 선택) 제한 시간(초) | 8 / 15 / 25 / 무제한(`null`) | 15 |
| `autoDefend` | 반응 시간 초과 시 가능한 방어 카드를 자동으로 사용 | on / off | on |
| `autoBarrel` | 술통/주르도네 판정을 묻지 않고 자동 실행 | on / off | on |
| `revealRoleOnDeath` | 사망 시 역할 공개(원작 규칙) | on 고정 | on |
@@ -140,7 +140,7 @@
패닉!/캣 벌루 대상은 "다른 플레이어"로 한정한다(자기 자신 불가, 결정 사항).
### 5.4 반응 창(Reaction window)
턴 진행은 다음 반응이 모두 끝날 때까지 멈춘다. 각 반응에는 `reactionSeconds` 타이머가 있다.
턴 진행은 다음 반응이 모두 끝날 때까지 멈춘다. 각 반응에는 `reactionSeconds` 타이머가 있다(무제한이면 타이머가 없다. 자리 비움인 사람만 5초. 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 처리).
- **뱅! 반응**: 대상에게 `missedNeeded`(기본 1, 슬랩의 뱅!은 2). 순서: (1) 술통 판정(실제 술통, 주르도네 능력 각각 1회, `autoBarrel`이면 자동) → 성공마다 needed -1. (2) 남은 needed만큼 빗나감!(캘러미티는 뱅!도) 제출 또는 포기. 포기/시간 초과 시 생명 1 손실.
- 슬랩 상대로 빗나감!이 1장뿐이면 내 봐야 소용없으므로 UI에서 "막을 수 없음"을 안내하되 낼 수는 있다(효과 없음 → 실제로는 막지 못함). 엔진은 needed를 모두 채울 때만 카드 제출을 받는다(부분 제출 금지, 결정 사항).
- **개틀링 / 인디언!**: 대상 전원에게 동시에 반응 창을 연다. 각자의 응답은 도착 순서대로 개별 처리된다.

View File

@@ -11,7 +11,7 @@
| 옵션 키 | 설명 | 선택지 | 기본값 |
|---|---|---|---|
| `loseCount` | 같은 종류가 몇 장 쌓이면 패배 | 3 / 4 / 5 | 3~6인 4, 2인 5(원작) |
| `turnSeconds` | 카드 건네기/판단 제한 시간 | 15 / 30 / 60 | 30 |
| `turnSeconds` | 카드 건네기/판단 제한 시간 | 15 / 30 / 60 / 무제한(`null`) | 30 |
| `showSeenBy` | 현재 카드를 이미 본 사람 표시 | on 고정 | on |
| `claimHistory` | 이번 라운드의 주장 이력(누가 무엇이라 했는지) 표시 | on / off | on |
| `quickChat` | 정해진 문구 버튼("정말이야!", "의심스러운데?") | on / off | on |

View File

@@ -17,7 +17,7 @@
| `jesterTaxable` | 세금 낼 때 광대도 "좋은 카드"로 내야 하나 | on / off | off |
| `passLocksOut` | 한 번 패스하면 그 트릭에서 다시 못 냄(하우스 룰) | on / off(원작) | off |
| `removeHighCards` | 9~12 카드를 빼고 하기(손패가 많을 때, 나무위키 언급) | on / off | off |
| `turnSeconds` | 턴 제한 시간 | 15 / 20 / 30 / 45 | 20 |
| `turnSeconds` | 턴 제한 시간 | 15 / 20 / 30 / 45 / 무제한(`null`) | 20 |
## 3. 구성물
- 숫자 카드 78장: 숫자 n인 카드가 n장이다(1이 1장, 2가 2장, …, 12가 12장).
@@ -182,7 +182,7 @@ interface DalmutiState {
- 그 외 없음(세금 자동 선택은 숫자 → 카드 ID 순으로 결정적).
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- 마감: `revolutionCheck` 20초, `taxReturn` 30초, 플레이 `turnSeconds`.
- 마감: `revolutionCheck` 20초, `taxReturn` 30초, 플레이 `turnSeconds`. 무제한(`null`)이면 세 단계 모두 마감이 없다(기다리는 사람이 모두 자리 비움이면 5초). 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 행동.
- `onTimeout`
- `revolutionCheck`: `confirmHand { declareRevolution: false }`. 자동으로 혁명을 선언하지 않는다.
- `taxReturn`: 숫자가 가장 큰(가장 나쁜) 숫자 카드부터 필요한 장수만큼 돌려준다(광대 제외).

View File

@@ -38,8 +38,8 @@
| `gwangPrice` | 광팔기 1장당 값 | 1 / 2 / 3 | 1 |
| `gwangPayer` | 광값 내는 사람 | `nonDealerPlayers`(선 제외 참가자 각자) / `allPlayers`(참가자 3명 각자) | `nonDealerPlayers` |
| `gwangSellCards` | 팔 수 있는 패 | `gwang`(광만) / `gwangPlus`(광 + 쌍피·국진·보너스) | `gwang` |
| `turnSeconds` | 1턴 제한 시간 | 5~60 | 15 |
| `decisionSeconds` | 고/스톱·선택 제한 시간 | 5~30 | 10 |
| `turnSeconds` | 1턴 제한 시간 | 5~60 / 무제한(`null`) | 15 |
| `decisionSeconds` | 고/스톱·선택 제한 시간 | 5~30 / 무제한(`null`) | 10 |
| `hints` | 먹을 수 있는 패·족보 진행 힌트 | true / false | true |
모드(맞고/고스톱)는 `setup`의 인원 수로 정한다. 2명이면 맞고 기본값, 3~5명이면 고스톱 기본값을 쓴다.
@@ -342,7 +342,7 @@ interface GostopState {
- 그 밖에는 RNG를 쓰지 않는다. 자동 행동은 결정적이다.
### 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)` (모두 결정적):
- `play`: 빈패가 있으면 빈패를 낸다. 없으면 보너스패가 있으면 그것부터. 그 밖에는 바닥과 맞는 패 중 가져올 바닥 패 가치가 가장 큰 것(광 > 열끗 > 띠 > 쌍피 > 피, 같으면 낮은 ID), 맞는 패가 없으면 손패 중 가치가 가장 낮은 패(같으면 낮은 ID). target은 가치 큰 쪽. 흔들기·폭탄은 선언하지 않는다.
- `chooseFlip`: 가치 큰 쪽.

View File

@@ -42,7 +42,7 @@
| `jokerRange` | (`kr-product`) 조커로 부를 수 있는 범위 | `60-99`(원작) / `0-99` | `60-99` |
| `aceHigh` | (`classic`) A의 큰 값 | 10(나무위키) / 11(Bicycle) | 11 |
| `deckCount` | (`classic`) 덱 수 | `auto`(7인 이상 2벌) / 1 / 2 | `auto` |
| `turnSeconds` | 턴 제한 시간 | 10 / 15 / 20 / 30 | 15 |
| `turnSeconds` | 턴 제한 시간 | 10 / 15 / 20 / 30 / 무제한(`null`) | 15 |
## 3. 구성물
`kr-product` (기본값 기준 91장)
@@ -213,7 +213,7 @@ interface NinetyNineState {
- 라운드 재시작(목숨 모드, `reset`) 때 다시 섞기.
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- `deadline = turnStartedAt + turnSeconds*1000`.
- `deadline = turnStartedAt + turnSeconds*1000`. 무제한(`null`)이면 마감 없음(자리 비움만 3초). 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 행동.
- `onTimeout(state, p)`: 합법인 (카드, 선택값) 조합 중 결과 합계 S'가 가장 작은 것을 고른다.
- 같으면 우선순위: 0/4/9(변화 없음) → 일반 숫자 카드 → ±카드 → K/조커. 그래도 같으면 카드 ID 순.
- `kr-product`의 0은 방향을 그대로 두는 쪽으로 낸다.

View File

@@ -11,7 +11,7 @@
## 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)
```ts
interface OldMaidState {
options: { turnSeconds: 10 | 20 | 30 | 60 };
options: { turnSeconds: 10 | 20 | 30 | 60 | null };
order: PlayerId[];
hands: Record<PlayerId, string[]>; // 들고 있는 순서 그대로(왼쪽부터)
discards: Record<PlayerId, string[]>; // 버린 짝(공개)
@@ -79,7 +79,7 @@ interface OldMaidState {
- 덱 섞기, 첫 사람, 뽑은 카드를 넣을 자리, 섞기, 시간 초과 때 뽑을 자리, 나간 사람 카드 섞기와 넣을 자리. 모두 `ctx.rng`.
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- 차례마다 `turnSeconds`. 넘기면 지금 뽑을 사람의 **무작위 자리 한 장**을 뽑는다(자동 짝 버리기 포함). 3번 연속이면 "자리 비움"으로 제한 시간 5초, 직접 뽑으면 풀린다.
- 차례마다 `turnSeconds`(무제한 `null`이면 시계 없음, 자리 비움만 5초, 연결이 끊긴 사람은 방의 유예 시간 뒤 자동으로 뽑음). 넘기면 지금 뽑을 사람의 **무작위 자리 한 장**을 뽑는다(자동 짝 버리기 포함). 3번 연속이면 "자리 비움"으로 제한 시간 5초, 직접 뽑으면 풀린다.
- 섞기는 차례 시계를 다시 시작하지 않는다.
- **나가기(공정 처리)**: 카드를 든 사람이 나가면 그 카드를 섞어, 남아 있는 사람들에게 **나간 사람의 다음 자리부터 한 장씩 돌아가며** 나눠 준다(각자 손패 무작위 자리에). 받은 사람은 짝을 자동으로 버리고, 그걸로 0장이 되면 빠진다. 조커가 있었다면 누구에게 갈지 무작위라 특정 사람만 손해 보지 않는다. 나간 사람은 맨 아래 순위. 그 결과 카드 든 사람이 한 명 이하가 되면 **도둑 없이** 끝난다(`reason: resign`, 남은 사람이 나간 사람보다 위). 나간 사람이 차례였으면 다음 자리로 넘어간다.
- 이미 다 턴 사람이 나가면 아무 변화도 없다(`onLeave` = null, 순위 유지).

View File

@@ -45,7 +45,7 @@
| `blindUpEvery` | N핸드마다 기본 단위 2배(0=안 올림) | 0 / 5 / 10 / 15 | 0 (`lastStanding` 선택 시 UI가 10을 추천) |
| `rebuy` | 리바이(재충전) | `off` / `limited` / `unlimited` | `unlimited` (`lastStanding` 선택 시 UI가 `off`를 추천) |
| `rebuyLimit` | `limited`일 때 1인당 횟수 | 1 / 2 / 3 | 1 |
| `turnSeconds` | 행동 제한 시간(초) | 15 / 20 / 30 / 60 | 20 |
| `turnSeconds` | 행동 제한 시간(초) | 15 / 20 / 30 / 60 / 무제한(`null`) | 20 |
| `dealerRule` | 다음 핸드 딜러(선) 결정 | `rotate`(시계 방향 회전) / `winner`(직전 승자) | `rotate` |
| `hints` | 현재 족보 표시·추천 행동 하이라이트 | 켬 / 끔 | 켬 |
| `hiLoLow` | 하이로우 로우 판정 방식 | `korean`(스트레이트·플러시 불인정, 최고 로우 A-2-3-4-6) / `aceToFive`(스트레이트·플러시 무시, 최고 로우 A-2-3-4-5) | `korean` |
@@ -227,7 +227,7 @@
- 핸드 종료 후 칩이 0인 플레이어는 `busted`.
- `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일 때만).
- 리바이는 실제 재화와 무관한 방 내부 칩 보충이다.
@@ -391,7 +391,7 @@ interface PokerOptions {
blindUpEvery: 0 | 5 | 10 | 15;
rebuy: 'off' | 'limited' | 'unlimited';
rebuyLimit: 1 | 2 | 3;
turnSeconds: 15 | 20 | 30 | 60;
turnSeconds: 15 | 20 | 30 | 60 | null;
dealerRule: 'rotate' | 'winner';
hints: boolean;
hiLoLow: 'korean' | 'aceToFive';
@@ -556,8 +556,8 @@ interface PokerState {
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
`deadline(state)`:
- 베팅: `turnSeconds`(자리 비움이면 5초).
- 7포커 초이스·교환·선언: `turnSeconds + 10`초(동시 단계, 모두에게 같은 마감).
- 베팅: `turnSeconds`(자리 비움이면 5초). 무제한(`null`)이면 시계 없음(자리 비움만 짧은 시계). 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 행동.
- 7포커 초이스·교환·선언: `turnSeconds + 10`초(동시 단계, 모두에게 같은 마감). 무제한이면 마감 없음(기다리는 사람이 모두 자리 비움일 때만 짧은 시계).
- `handEnd`: 4초. 리바이 결정: 15초.
`onTimeout(state, player)`:

View File

@@ -16,7 +16,7 @@
| `wild4Rule` | 와일드 드로우4 | `challenge`(공식: 몰래 낼 수 있고 다음 사람이 도전) / `strict`(쉬운 규칙: 지금 색 카드가 있으면 못 냄, 도전 없음) | `challenge` |
| `stacking` | (하우스 룰) 드로우 카드 쌓기 | 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-0 규칙(7로 손패 교환, 0으로 모두 돌리기), 점프인, 쇼앰 노머시 카드, 낮은 점수 방식(각자 자기 남은 점수를 쌓는 변형), 팀전.
@@ -145,7 +145,7 @@ interface UnoState {
- `setup`: 첫 사람(`rng.int`) → 덱 섞기 → 시작 드로우4면 다시 섞기.
- 더미가 비었을 때 버린 카드 섞기, 다음 판 덱 섞기. 모두 `ctx.rng`.
### 8.5 타이머·시간 초과·연결 끊김
- 제한 시간 = `turnSeconds`(시작 색·도전 답도 같음). 판 사이 8초. 시간 초과가 3번 이어지면 "자리 비움"이 되어 5초만 기다린다(직접 행동하면 풀림).
- 제한 시간 = `turnSeconds`(시작 색·도전 답도 같음). 무제한(`null`)이면 차례 시계가 없고 타이머도 안 보인다. 연결이 끊긴 사람은 방의 유예 시간 뒤 자동 행동(아래 자리 비움 포함)이 그대로 적용된다. 판 사이 8초. 시간 초과가 3번 이어지면 "자리 비움"이 되어 5초만 기다린다(직접 행동하면 풀림).
- 시간 초과 자동 행동(원카드 관례: 낼 수 있으면 낸다)
- `turn`: 쌓인 드로우가 있으면 다 먹는다(자동으로 쌓지 않음). 아니면 낼 수 있는 카드 중 색 카드를 먼저(손패 순서 첫 장), 없으면 와일드, 그다음 규칙에 맞는 와일드 드로우4를 낸다. 와일드 색은 남은 손패에 가장 많은 색(같으면 빨강·노랑·초록·파랑 순). 낼 카드가 없으면 1장(하우스 룰이면 나올 때까지) 뽑고, 뽑은 카드가 맞으면 바로 낸다.
- `afterDraw`: 뽑은 카드가 규칙에 맞으면 내고, 아니면(어긋난 드로우4) 넘긴다.
@@ -164,6 +164,7 @@ interface UnoState {
- 오른쪽: 규칙 요약 한 줄, 자리 목록, 최종 순위, 기록, 특수 카드 표.
- 도움말: 30초 요약 3장(맞추기, 특수 카드, 우노!), [?] 지금 할 수 있는 것.
- 카드 그림은 원카드 색깔 카드 그림을 그대로 쓴다(흰 마름모, 색마다 무늬). 와일드 카드 아래 글자는 "색 바꾸기"로 나온다.
- 소리·움직임(2026-10-13, 내 행동과 남의 행동 모두 view 변화에 반응, 처음 들어올 때·다시 보기 건너뛰기에는 안 남): 카드 내기 = 낸 사람 자리(내 카드는 누른 자리)에서 버린 더미로 날아가며 "착" 소리, 와일드는 아르페지오, 드로우2·드로우4는 낮은 "쿵"과 "+2"/"+4" 배너. 뽑기 = 더미에서 내 손패/상대 자리로 카드가 날아가고 뽑는 소리, 벌칙·쌓인 장수를 먹으면 자리가 흔들림. 우노! = 큰 "우노!" 배너와 팡파르, 잡기 = "잡았다!" 배너와 경고음, 도전 성공/실패 배너. 스킵 = 건너뛴 자리 흔들림, 리버스 = 방향 화살표가 튀며 올라갔다 내려가는 소리, 더미 다시 섞기 = 섞는 소리. 판 시작 = 섞고 돌리는 소리와 함께 카드가 더미에서 모두에게, 판 끝 = 다른 자리 카드가 이긴 사람에게 모이며 모으는 소리. 차례인 자리는 테두리가 은은하게 빛나고, 바뀐 지금 색 칩은 튀어나온다. 소리는 사이트 음량을 따르고, 움직임 줄이기 설정이면 움직임은 생략된다.
### 9.1 컴퓨터 상대 (`packages/games/src/uno/bot.ts`)
- 공통: 낼 수 있는 카드 중 점수를 매겨 고른다(`humanBest`로 레벨만큼 가끔 실수). 와일드는 아끼고, 같은 색이 많이 남는 카드, 높은 숫자를 먼저 낸다. 다음 사람이 2장 이하면 스킵·리버스·드로우2·드로우4를 먼저 쓴다. 고르는 색은 남은 손패에 가장 많은 색(같으면 무작위).

View File

@@ -1053,7 +1053,7 @@ describe('시간 초과·자리 비움·나가기 (§8.5)', () => {
const c = pool();
const g = c('gatling');
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);
const paused = clock;
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.
for (const p of ['B', 'C', 'D']) x = act(x, p, { type: 'timeout' });
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' });
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']);
});
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은 모든 상태에서 합법 행동', () => {
for (let seed = 1; seed <= 40; seed++) {
const players = ['A', 'B', 'C', 'D', 'E'];
@@ -1261,6 +1328,7 @@ const PRESETS: Partial<BangOptions>[] = [
{ autoDefend: false, drawBeforeDeath: true },
{ beerAtFullHealth: true, selfTargetCatBalou: true, deputyCount7: true },
{ characterDraft: 'choose2', autoBarrel: false, autoDefend: false, reactionSeconds: 8 },
{ characterDraft: 'choose2', turnSeconds: null, reactionSeconds: null },
];
const SEEDS = playoutSeeds(1000);
@@ -1297,6 +1365,7 @@ describe(`무작위 대국 (시드 ${SEEDS}개, 4~7명)`, () => {
[5, { characterDraft: 'choose2' }],
[6, { autoBarrel: false }],
[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) => {
const players = Array.from({ length: n }, (_, k) => `P${k}`);
const options = bang.optionsSchema.parse(opts);

View File

@@ -71,12 +71,15 @@ export function clockwiseFrom(s: BangState, from: PlayerId): PlayerId[] {
return out;
}
export function reactionMs(s: BangState, p: PlayerState): number {
return p.away ? AWAY_MS : s.options.reactionSeconds * 1000;
/** Clock lengths in ms; null = 무제한 (an away player still gets the short clock). */
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 {
return p.away ? AWAY_MS : s.options.turnSeconds * 1000;
export function turnMs(s: BangState, p: PlayerState): number | null {
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. */
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 {
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 {
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 {
const p = P(s, id);
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 });
}
@@ -428,7 +431,7 @@ export function doDraw(s: BangState, ctx: Ctx, a: { jesseFrom?: PlayerId; pedroD
p.hand.push(...options);
if (options.length) log(s, ctx, { t: 'draw', p: p.id, n: options.length, why: 'kit' });
} 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;
}
@@ -471,7 +474,7 @@ export function settle(s: BangState, ctx: Ctx): void {
return;
}
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;
}
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,
barrelTried: false,
jourTried: false,
deadline: ctx.now + reactionMs(s, t),
deadline: after(ctx, reactionMs(s, t)),
};
if (s.options.autoBarrel) {
while (r.needed > 0 && tryBarrel(s, ctx, r));
@@ -582,7 +585,7 @@ export function storeAdvance(s: BangState, ctx: Ctx, r: Extract<Reaction, { kind
continue;
}
r.picker = next;
r.deadline = ctx.now + reactionMs(s, p);
r.deadline = after(ctx, reactionMs(s, p));
return;
}
}
@@ -661,13 +664,13 @@ export function playCard(s: BangState, ctx: Ctx, actor: PlayerId, a: PlayAction)
}
case 'duel': {
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;
}
case 'indians':
for (const id of clockwiseFrom(s, actor)) {
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;
case 'gatling':
@@ -700,7 +703,7 @@ export function respond(s: BangState, ctx: Ctx, actor: PlayerId, cardIds: string
const next = r.other;
r.other = r.actor;
r.actor = next;
r.deadline = ctx.now + reactionMs(s, P(s, next));
r.deadline = after(ctx, reactionMs(s, P(s, next)));
break;
}
case 'dying':
@@ -793,7 +796,7 @@ export function endPlay(s: BangState, ctx: Ctx, actor: PlayerId): void {
const p = P(s, actor);
if (p.hand.length > p.life) {
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';
}

View File

@@ -4,6 +4,7 @@ import { CARDS, CHARACTER_IDS, CHARACTER_LIFE, cardById, kindOf, rolesFor } from
import { distance, rangeOf } from './distance';
import {
AWAY_AFTER,
AWAY_MS,
P,
autoSave,
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)];
}
/** Earliest clock; reactions with no clock (무제한) are skipped, null when nothing is timed. */
function deadlineOf(s: BangState): number | 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;
}
/** 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[] {
if (s.winner) return [];
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))];
}
@@ -178,7 +186,8 @@ export const bang: Def = {
deck: rng.shuffle(CARDS.map((c) => c.id)),
discard: [],
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,
winner: null,
deathOrder: [],
@@ -318,8 +327,9 @@ export const bang: Def = {
}
: null,
turnDeadline: s.turn.deadline,
deadlineTotalMs: s.options.turnSeconds * 1000,
reactionTotalMs: s.options.reactionSeconds * 1000,
// 무제한: only an away player's short clock can run, so the ring is sized for it.
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)),
winner: s.winner,
result: s.final,

View File

@@ -3,7 +3,7 @@ import { z } from 'zod';
import type { PlayerId } from '@bg/engine';
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>[]]);
export const bangOptionsSchema = z.object({
@@ -11,12 +11,14 @@ export const bangOptionsSchema = z.object({
.enum(['random', 'choose2'])
.default('random')
.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)
.meta({ title: '내 턴 제한 시간', labels: { 30: '30초', 60: '60초', 90: '90초', 120: '120초' } }),
reactionSeconds: lit(8, 15, 25)
.meta({ title: '내 턴 제한 시간', labels: { 30: '30초', 60: '60초', 90: '90초', 120: '120초', null: '무제한' } }),
/** null = 무제한 (away players still get the short clock). */
reactionSeconds: lit(8, 15, 25, null)
.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: '반응 시간이 지나면 막을 카드를 자동으로 내기' }),
autoBarrel: z.boolean().default(true).meta({ title: '술통·주르도네 판정을 묻지 않고 자동으로 하기' }),
showDistanceHelper: z.boolean().default(true).meta({ title: '다른 사람까지 거리와 사거리 표시' }),
@@ -70,15 +72,16 @@ export interface PlayerState {
away: boolean;
}
/** `deadline: null` = 무제한 (no clock; only the room's disconnect grace applies). Never Infinity (state is JSON). */
export type Reaction =
| { kind: 'bang'; target: PlayerId; source: PlayerId; via: 'bang' | 'gatling'; needed: number; barrelTried: boolean; jourTried: boolean; deadline: number }
| { kind: 'indians'; target: PlayerId; source: PlayerId; deadline: number }
| { kind: 'duel'; actor: PlayerId; other: PlayerId; source: PlayerId; deadline: number }
| { kind: 'store'; picker: PlayerId; order: PlayerId[]; revealed: string[]; source: PlayerId; 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 | null }
| { kind: 'duel'; actor: PlayerId; other: PlayerId; source: PlayerId; deadline: number | null }
| { 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). */
| { kind: 'dying'; player: PlayerId; killer: PlayerId | null; lost: number; source: PlayerId | null; deadline: number }
| { kind: 'kitKeep'; player: PlayerId; options: string[]; deadline: number }
| { kind: 'choose2'; player: PlayerId; 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 | null }
| { kind: 'choose2'; player: PlayerId; deadline: number | null };
export type ReactionKind = Reaction['kind'];
export type TurnPhase = 'draft' | 'start' | 'draw' | 'play' | 'discard' | 'ended';
@@ -87,7 +90,8 @@ export interface TurnState {
player: PlayerId;
phase: TurnPhase;
bangsPlayed: number;
deadline: number;
/** null = 무제한. */
deadline: number | null;
/** Turn timer is paused while reactions run during the play phase. */
pausedAt: number | null;
dynamiteChecked: boolean;
@@ -217,7 +221,7 @@ export interface ReactionView {
via?: 'bang' | 'gatling';
needed?: number;
revealed?: Card[];
deadline: number;
deadline: number | null;
}
export interface BangView {
@@ -246,7 +250,9 @@ export interface BangView {
canSidHeal: boolean;
prompt: Prompt | 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;
reactionTotalMs: number;
log: LogEntry[];

View File

@@ -389,6 +389,23 @@ describe('시간 초과 (§8.5)', () => {
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이 합법', () => {
for (let seed = 1; seed <= 40; seed++) {
const n = 2 + (seed % 5);
@@ -538,7 +555,7 @@ function cfg(i: number): { players: string[]; options: CockroachOptions } {
claimHistory: i % 3 !== 0,
eightKindsRule: i % 7 === 0,
twoPlayerPass: i % 2 === 0,
turnSeconds: ([15, 30, 60] as const)[i % 3],
turnSeconds: ([15, 30, 60, null] as const)[i % 4],
}),
};
}

View File

@@ -45,10 +45,11 @@ export const cockroachOptionsSchema = z.object({
.union([z.literal('auto'), z.literal(3), z.literal(4), z.literal(5)])
.default('auto')
.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
.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)
.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: '이번 라운드 주장 기록 보이기' }),
quickChat: z.boolean().default(true).meta({ title: '빠른 말 버튼("정말이야!", "의심스러운데?")' }),
eightKindsRule: z.boolean().default(false).meta({ title: '앞마당에 8종을 모두 모아도 패배(하우스 룰)' }),
@@ -200,6 +201,7 @@ export interface CockroachView {
said: Said[];
removedCount: number;
turnStartedAt: number;
/** Clock length in ms; 0 = 무제한 (no clock). */
turnMs: number;
seq: number;
final: CockroachFinal | null;
@@ -266,9 +268,11 @@ function peekBlock(s: CockroachState): string | 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];
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 {
@@ -576,7 +580,7 @@ export const cockroachPoker: GameDefinition<CockroachState, CockroachAction, Coc
said: s.said,
removedCount: s.removed.length,
turnStartedAt: s.turnStartedAt,
turnMs: turnMs(s),
turnMs: turnMs(s) ?? 0,
seq: s.seq,
final: s.final,
revealed: over ? { hands: s.hands, removed: s.removed } : null,
@@ -586,7 +590,8 @@ export const cockroachPoker: GameDefinition<CockroachState, CockroachAction, Coc
activePlayers: waiting,
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,

View File

@@ -475,6 +475,30 @@ describe('시간 초과와 나가기 (§8.5)', () => {
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', () => {
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' });

View File

@@ -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 {
const w = waiting(s);
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) {
case 'revolutionCheck':
return allAway ? AWAY_MS : REVOLUTION_MS;
return REVOLUTION_MS;
case 'taxReturn':
return allAway ? AWAY_MS : TAX_MS;
return TAX_MS;
case 'playing':
return allAway ? AWAY_MS : s.options.turnSeconds * 1000;
case 'finished':
return null;
return s.options.turnSeconds * 1000;
}
}

View File

@@ -49,7 +49,7 @@ export function deckFor(removeHighCards: boolean): DCard[] {
// ---------------------------------------------------------------- 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>[]]);
export const dalmutiOptionsSchema = z.object({
@@ -66,9 +66,13 @@ export const dalmutiOptionsSchema = z.object({
jesterTaxable: z.boolean().default(false).meta({ title: '세금 낼 때 광대도 좋은 카드로 내기' }),
passLocksOut: z.boolean().default(false).meta({ title: '한 번 패스하면 그 트릭에서 다시 못 내기' }),
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)
.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>;

View File

@@ -776,6 +776,29 @@ describe('시간 초과·연결 끊김 (§8.5)', () => {
s = act(s, 'A', play(gostop.view(s, 'A').myHand![0]!.card.id), 14_000);
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초, 결과 화면 준비에서 빠짐', () => {
let s = rigged(2, { hands: [[2, 6], [11, 15]], floor: [20], deck: [24, 36, 37, 38] });
s = act(s, 'A', { type: 'leave' }, 5000);

View File

@@ -89,7 +89,9 @@ function deadlineMs(s: GostopState): number | null {
if (w.length === 0) return null;
if (w.every((i) => s.autoPilot[i])) return AUTO_MS;
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 {

View File

@@ -3,7 +3,7 @@ import { z } from 'zod';
import type { PlayerId } from '@bg/engine';
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>[]]);
export const gostopOptionsSchema = z.object({
@@ -58,12 +58,14 @@ export const gostopOptionsSchema = z.object({
.enum(['gwang', 'gwangPlus'])
.default('gwang')
.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)
.meta({ title: '한 턴 제한 시간', labels: { 5: '5초', 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }),
decisionSeconds: lit(5, 10, 15, 20, 30)
.meta({ title: '한 턴 제한 시간', labels: { 5: '5초', 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
/** null = 무제한 (고·스톱, 뒤집은 패 고르기, 총통, 광팔기, 국진). */
decisionSeconds: lit(5, 10, 15, 20, 30, null)
.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: '먹을 수 있는 패·족보 힌트' }),
});
export type GostopOptions = z.infer<typeof gostopOptionsSchema>;

View File

@@ -256,9 +256,11 @@ function validatePlay(s: NinetyNineState, actor: PlayerId, a: PlayAction): Valid
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 {
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[] {

View File

@@ -463,6 +463,20 @@ describe('시간 초과, 연결 끊김, 나가기 (§8.5)', () => {
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', () => {
let s = rig(make({ lives: 3 }), { hands: { A: ['1'], B: ['2'], C: ['3'] }, total: 40 });
expect(ninetyNine.onLeave!(s, 'A')).toEqual({ type: 'leave' });

View File

@@ -2,7 +2,7 @@
import { z } from 'zod';
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>[]]);
export const ninetyNineOptionsSchema = z.object({
@@ -47,9 +47,10 @@ export const ninetyNineOptionsSchema = z.object({
deckCount: lit<'auto' | 1 | 2>('auto', 1, 2)
.default('auto')
.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)
.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 NNMode = NNOptions['mode'];

View File

@@ -54,8 +54,10 @@ function waiting(s: OldMaidState): PlayerId[] {
return finished(s) || !s.turn ? [] : [s.turn];
}
function turnMs(s: OldMaidState): number {
return s.turn && s.away[s.turn] ? AWAY_MS : s.options.turnSeconds * 1000;
/** Turn clock in ms; null = 무제한 (an away player still gets the short clock). */
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 {
@@ -342,7 +344,7 @@ export const oldMaid: GameDefinition<OldMaidState, OldMaidAction, OldMaidView, O
logCount: s.logCount,
away: { ...s.away },
turnStartedAt: s.turnStartedAt,
turnMs: turnMs(s),
turnMs: turnMs(s) ?? 0,
seq: s.seq,
final: s.final,
revealed: over ? per((p) => [...s.hands[p]!]) : null,
@@ -352,7 +354,8 @@ export const oldMaid: GameDefinition<OldMaidState, OldMaidAction, OldMaidView, O
activePlayers: waiting,
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,

View File

@@ -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이 합법', () => {
for (const n of [2, 5, 8]) {
let s = setup(Array.from({ length: n }, (_, i) => `P${i}`), n);

View File

@@ -13,10 +13,11 @@ export const LOG_KEEP = 30;
// ---------------------------------------------------------------- options
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
.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)
.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>;
@@ -120,6 +121,7 @@ export interface OldMaidView {
logCount: number;
away: Record<PlayerId, boolean>;
turnStartedAt: number;
/** Turn clock length in ms; 0 = 무제한 (no clock). */
turnMs: number;
seq: number;
final: OldMaidFinal | null;

View File

@@ -739,22 +739,29 @@ export function deadlineSig(s: PokerState): string {
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 {
const o = s.options;
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!;
switch (h.phase) {
case 'betting': {
if (h.bet.turn === null) return 0;
const seat = seatOf(s, h.order[h.bet.turn]!)!;
return (seat.timeoutsInRow >= 2 ? o.awaySeconds : o.turnSeconds) * 1000;
if (isAway(h.order[h.bet.turn]!)) return o.awaySeconds * 1000;
return o.turnSeconds === null ? 0 : o.turnSeconds * 1000;
}
case 'choice':
case 'draw':
case 'declare':
return (o.turnSeconds + 10) * 1000;
return o.turnSeconds === null ? unlimited() : (o.turnSeconds + 10) * 1000;
case 'handEnd':
return o.handEndSeconds * 1000;
default:

View File

@@ -15,6 +15,9 @@ export const MODE_KO: Record<PokerMode, string> = {
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
.object({
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)])
.default(1)
.meta({ title: '리바이 횟수(횟수 제한일 때)', labels: { 1: '1번', 2: '2번', 3: '3번' } }),
turnSeconds: z
.union([z.literal(15), z.literal(20), z.literal(30), z.literal(60)])
/** null = 무제한 (no clock for betting or the simultaneous steps; a dropped connection still gets auto moves after the room's grace time). */
turnSeconds: lit(15, 20, 30, 60, null)
.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
.enum(['rotate', 'winner'])
.default('rotate')
@@ -100,10 +103,10 @@ export const pokerOptionsSchema = z
.union([z.literal(3), z.literal(4), z.literal(6), z.literal(10)])
.default(4)
.meta({ title: '판 결과 보여 주는 시간', labels: { 3: '3초', 4: '4초', 6: '6초', 10: '10초' } }),
rebuySeconds: z
.union([z.literal(10), z.literal(15), z.literal(30)])
/** null = 무제한 (same rule as turnSeconds). */
rebuySeconds: lit(10, 15, 30, null)
.default(15)
.meta({ title: '리바이 고르는 시간', labels: { 10: '10초', 15: '15초', 30: '30초' } }),
.meta({ title: '리바이 고르는 시간', labels: { 10: '10초', 15: '15초', 30: '30초', null: '무제한' } }),
awaySeconds: z
.union([z.literal(3), z.literal(5), z.literal(10)])
.default(5)

View File

@@ -180,6 +180,54 @@ describe('korean betting (§5.2)', () => {
s = act(s, 'A', { type: 'k.check' });
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포커

View File

@@ -571,14 +571,17 @@ function validatePlay(s: UnoState, actor: PlayerId, a: PlayAction): Validation {
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 {
switch (s.phase.kind) {
case 'startColor':
case 'turn':
case 'afterDraw':
return s.away[s.current] ? AWAY_MS : s.options.turnSeconds * 1000;
return turnMs(s, s.current);
case 'wild4':
return s.away[s.phase.target] ? AWAY_MS : s.options.turnSeconds * 1000;
return turnMs(s, s.phase.target);
case 'roundEnd':
return ROUND_END_MS;
case 'finished':

View File

@@ -3,7 +3,7 @@ import { z } from 'zod';
import type { PlayerId } from '@bg/engine';
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>[]]);
const colorSchema = z.enum(['R', 'Y', 'G', 'B']);
@@ -22,9 +22,10 @@ export const unoOptionsSchema = z.object({
}),
stacking: 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)
.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>;

View File

@@ -461,6 +461,22 @@ describe('시간 초과와 나가기 (§8.5)', () => {
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', () => {
let s = rig(make(), { hands: { A: ['R1a', 'R2a'], B: ['G2a'], C: ['Y3a'] }, discard: ['R5a'] });
expect(uno.onLeave!(s, 'A')).toEqual({ type: 'leave' });