할리갈리·도블·사과 게임: 뒤집기 시간 무제한·사과 게임 무제한(여기까지), 소리·움직임

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 04:16:54 +09:00
parent f12cf12b84
commit bafbf95d98
13 changed files with 476 additions and 94 deletions

View File

@@ -95,8 +95,40 @@ describe('사과 게임 room flow', () => {
room.onTimer();
expect(s().phase).toBe('playing');
expect(s().status.B).toBe('playing');
h.clock.advance(s().endsAt - h.clock.now());
h.clock.advance(s().endsAt! - h.clock.now());
room.onTimer();
expect(room.game!.finished).toBe(true);
});
test('제한 시간 무제한: 타이머가 돌지 않고, 끊긴 사람은 유예 뒤 한 번만 여기까지 처리(바쁜 루프 없음), 남은 사람이 여기까지 하면 끝', () => {
const h = harness();
const r = h.manager.create('A', 'apple', 'private');
if (typeof r === 'string') throw new Error(r);
const room = r as Room;
rooms.push(room);
const a = h.conn('A');
const b = h.conn('B');
room.join(a, 'player');
room.join(b, 'player');
room.ready('B', true);
expect(room.configure('A', { options: { timeLimitSec: null } })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
const s = () => room.game!.state as AppleState;
expect(s().phase).toBe('playing');
expect(s().endsAt).toBeNull();
expect(room.effectiveDeadline()).toBeNull();
room.disconnect(b);
const d = room.effectiveDeadline()!;
expect(d).toBeGreaterThan(h.clock.now());
h.clock.advance(d - h.clock.now());
room.onTimer();
expect(s().status.B).toBe('done');
expect(s().status.A).toBe('playing');
// Nothing else is due: no timer fires again for B.
expect(room.effectiveDeadline()).toBeNull();
room.act('A', 1, { type: 'stop' });
expect(room.game!.finished).toBe(true);
expect(s().final!.summary).toContain('모두 끝냈어요');
});
});

View File

@@ -40,3 +40,14 @@ test('사과 게임: 막힘 / 나감 / 끝', () => {
s.final = { endReason: 'time', ranking: [], summary: '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요' };
expect(helpNow(view(s, 'A'), 'A', users)).toContain('시간이 다 됐어요');
});
test('사과 게임: 제한 시간 무제한 / 여기까지', () => {
const { state: s0 } = setupGame('apple', 3, { timeLimitSec: null });
expect(helpNow(view(s0, 'A'), 'A', users)).toContain('제한 시간은 없어요');
const s = playing({ timeLimitSec: null });
expect(helpNow(view(s, 'A'), 'A', users)).toContain('[여기까지 할래요]');
expect(helpNow(view(s, null), null, users)).toContain('모두 끝냈을 때');
s.status.A = 'done';
s.score.A = 30;
expect(helpNow(view(s, 'A'), 'A', users)).toContain('여기까지 했어요. 사과 30개');
});

View File

@@ -17,17 +17,20 @@ function leaders(v: AppleView, players: Record<string, PublicUser>, me: string |
export function helpNow(v: AppleView, me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'ended') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자 지운 사과 개수를 볼 수 있어요.';
const secs = v.options.timeLimitSec;
const limit = secs % 60 === 0 ? `${secs / 60}분` : `${secs}초`;
if (v.phase === 'countdown') return `곧 시작해요. 모두 똑같은 사과 판을 각자 풀어요. 제한 시간은 ${limit}이에요.\n${HOW}`;
const limitLine = secs === null ? '제한 시간은 없어요. 모두 끝낼 때까지 해요.' : `제한 시간은 ${secs % 60 === 0 ? `${secs / 60}분` : `${secs}초`}이에요.`;
if (v.phase === 'countdown') return `곧 시작해요. 모두 똑같은 사과 판을 각자 풀어요. ${limitLine}\n${HOW}`;
const mine = v.seats.find((s) => s.id === me) ?? null;
const lead = leaders(v, players, me);
if (!mine) return `모두 똑같은 판을 각자 풀고 있어요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.${lead ? `\n${lead}` : ''}`;
const winLine = secs === null ? '모두 끝냈을 때' : '시간이 끝났을 때';
if (!mine) return `모두 똑같은 판을 각자 풀고 있어요. ${winLine} 사과를 가장 많이 지운 사람이 이겨요.${lead ? `\n${lead}` : ''}`;
if (mine.status === 'left') return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
if (mine.status === 'stuck') {
return `내 판에는 이제 합이 10이 되는 사과 묶음이 없어요. 사과 ${mine.score}개를 지웠어요. 시간이 끝나거나 모두 막히면 순위가 나와요.${lead ? `\n${lead}` : ''}`;
return `내 판에는 이제 합이 10이 되는 사과 묶음이 없어요. 사과 ${mine.score}개를 지웠어요. ${secs === null ? '모두 끝내면' : '시간이 끝나거나 모두 막히면'} 순위가 나와요.${lead ? `\n${lead}` : ''}`;
}
if (mine.status === 'done') return `여기까지 했어요. 사과 ${mine.score}개를 지웠어요. 모두 끝내면 순위가 나와요.${lead ? `\n${lead}` : ''}`;
const lines = [HOW, '빈 칸은 합에 들어가지 않아서, 사이가 비어 있어도 멀리 있는 사과끼리 묶을 수 있어요.', `지금 내 점수는 사과 ${mine.score}개예요.`];
if (lead) lines.push(lead);
if (secs === null) lines.push('제한 시간이 없어요. 그만하고 싶으면 아래 [여기까지 할래요]를 두 번 눌러요.');
lines.push(KEYS);
return lines.join('\n');
}

View File

@@ -1,10 +1,10 @@
/** 사과 게임 화면 (docs/games/apple.md §9). */
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
import type { AppleOptions, AppleView, SeatView } from '@bg/games/apple';
import type { PublicUser } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { useServerNow } from '../../components/TurnTimer';
import { haptic, sounds } from '../../lib/feedback';
import { haptic, sfx, tone } from '../../lib/feedback';
import { socket } from '../../net/socket';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
@@ -49,7 +49,26 @@ const clock = (ms: number) => {
const s = Math.ceil(Math.max(0, ms) / 1000);
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
};
const limitLabel = (sec: number) => (sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
const limitLabel = (sec: number | null) => (sec === null ? '무제한' : sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
/** Game sounds on top of the shared palette (site volume applies). */
const apSound = {
/** Apples popping: one rising pop per apple (up to 5), quick enough to finish while they vanish. */
clear: (n: number) => {
for (let i = 0; i < Math.min(5, n); i++) tone(520 + i * 110, 80, 'sine', 0.16, i * 38, { slideTo: 1100 + i * 160 });
},
/** Let go on a sum that is not 10: a soft "thud", no penalty. */
miss: () => tone(230, 90, 'triangle', 0.09, 0, { slideTo: 180 }),
/** The box being dragged just added up to 10. */
ten: () => tone(1320, 45, 'triangle', 0.07),
count: () => tone(660, 90, 'triangle', 0.12),
go: () => {
tone(988, 120, 'triangle', 0.14);
tone(1318, 200, 'triangle', 0.12, 90);
},
};
const statusSuffix = (s: SeatView) => (s.status === 'stuck' ? ', 더 지울 사과 없음' : s.status === 'done' ? ', 여기까지 함' : s.status === 'left' ? ', 나감' : '');
/** Ranks by score (ties share), players who left last. */
function ranked(seats: SeatView[]): (SeatView & { rank: number })[] {
@@ -89,6 +108,11 @@ const CSS = `
:root[data-theme='dark'] .ap-board { background: #3b2f22; box-shadow: var(--shadow), inset 0 0 0 3px #6b4f2a; }
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .ap-board { background: #3b2f22; box-shadow: var(--shadow), inset 0 0 0 3px #6b4f2a; } }
.ap-pop { animation: ap-pop .42s ease-out forwards; transform-box: fill-box; transform-origin: center; pointer-events: none; }
.ap-burst { animation: ap-burst .45s ease-out forwards; transform-box: fill-box; transform-origin: center; pointer-events: none; }
.ap-in { animation: ap-in .34s cubic-bezier(.3,1.5,.5,1) both; animation-delay: var(--d, 0ms); transform-box: fill-box; transform-origin: center; }
.ap-pill b, .ap-others li b { display: inline-block; }
.ap-over.count b { display: block; animation: ap-count .9s ease-out both; }
.ap-stop { min-height: 40px; }
.ap-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; pointer-events: none;
border-radius: 14px; text-align: center; padding: 12px; }
.ap-over.count { background: rgba(0,0,0,.35); color: #fff; font-size: 5rem; font-weight: 900; text-shadow: 0 3px 8px rgba(0,0,0,.5); }
@@ -99,9 +123,12 @@ const CSS = `
.ap-flash.ok { color: var(--success); border: 3px solid var(--success); }
.ap-flash.bad { color: var(--text-sub); border: 3px solid var(--border); }
.ap-keys { color: var(--text-sub); font-size: .85rem; font-weight: 600; text-align: center; margin: 0; }
@keyframes ap-burst { 0% { transform: scale(.5); opacity: .9; } 100% { transform: scale(1.6); opacity: 0; } }
@keyframes ap-in { from { transform: scale(0); opacity: 0; } }
@keyframes ap-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } }
@keyframes ap-pop { 0% { transform: scale(1); opacity: 1; } 40% { transform: scale(1.25); opacity: .9; } 100% { transform: scale(.2) translateY(-30px); opacity: 0; } }
@keyframes ap-flash { 0% { opacity: 0; transform: translateX(-50%) scale(.8); } 15% { opacity: 1; transform: translateX(-50%) scale(1.05); } 70% { opacity: 1; } 100% { opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .ap-pop { animation-duration: .01s; } .ap-flash { animation: none; } }
@media (prefers-reduced-motion: reduce) { .ap-pop { animation-duration: .01s; } .ap-flash, .ap-in, .ap-burst, .ap-over.count b { animation: none; } .ap-burst { display: none; } }
`;
// ---------------------------------------------------------------- art
@@ -125,13 +152,19 @@ function AppleDefs() {
);
}
function AppleCell({ x, y, n }: { x: number; y: number; n: number }) {
return (
<g transform={`translate(${x} ${y})`}>
function AppleCell({ x, y, n, introDelay }: { x: number; y: number; n: number; introDelay?: number }) {
const apple = (
<>
<use href="#ap-apple" />
<text x="20" y="29" textAnchor="middle" fontSize="17" fontWeight="900" fill="#fff" stroke="#6b0b16" strokeWidth="0.8" paintOrder="stroke">
{n}
</text>
</>
);
return (
<g transform={`translate(${x} ${y})`}>
{/* The CSS animation goes on an inner group: it would replace the SVG translate on the outer one. */}
{introDelay === undefined ? apple : <g className="ap-in" style={{ '--d': `${introDelay}ms` } as CSSProperties}>{apple}</g>}
</g>
);
}
@@ -185,7 +218,27 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
const seq = useRef(0);
const mine = v.seats.find((s) => s.id === me) ?? null;
const canPlay = !!mine && mine.status === 'playing' && v.phase === 'playing' && !!v.cells && now < v.endsAt;
const canPlay = !!mine && mine.status === 'playing' && v.phase === 'playing' && !!v.cells && (v.endsAt === null || now < v.endsAt);
const unlimited = v.endsAt === null;
const [stopAsk, setStopAsk] = useState(false);
// The board appearing (after the countdown, or when I open the room) pops the apples in, row by row.
const [intro, setIntro] = useState(false);
const hadCells = useRef<boolean | null>(null);
useEffect(() => {
const has = !!v.cells;
if (hadCells.current === false && has) setIntro(true);
hadCells.current = has;
}, [v.cells]);
useEffect(() => {
if (!intro) return;
const t = setTimeout(() => setIntro(false), 900);
return () => clearTimeout(t);
}, [intro]);
useEffect(() => {
if (!stopAsk) return;
const t = setTimeout(() => setStopAsk(false), 3000);
return () => clearTimeout(t);
}, [stopAsk]);
// My board as I see it: the server's, minus the apples I just cleared and the server has not confirmed yet.
const cells = useMemo(() => {
@@ -240,17 +293,18 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
}
if (sum !== 10) {
if (idx.length >= 2 || fromKey) {
apSound.miss();
setFlash({ key: ++seq.current, ok: false, text: `합 ${sum} · 10이 아니에요` });
say(`합이 ${sum}이에요. 딱 10이 되게 골라 주세요.`);
}
return;
}
act({ type: 'select', ...rect });
setGone((g) => [...g, ...idx]);
setPops((p) => [...p, { key: ++seq.current, cells: idx.map((i) => ({ i, n: cells.charCodeAt(i) - 48 })) }]);
setFlash({ key: ++seq.current, ok: true, text: `+${idx.length}` });
sounds.stone();
apSound.clear(idx.length);
haptic(15);
act({ type: 'select', ...rect });
say(`사과 ${idx.length}개를 지웠어요.`);
};
@@ -316,9 +370,24 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
}
};
const left = Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt));
const left = v.endsAt === null ? null : Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt));
const countdown = v.phase === 'countdown' ? Math.max(1, Math.ceil((v.countdownEndsAt - now) / 1000)) : 0;
const sumState = !sel || sel.idx.length === 0 ? 'idle' : sel.sum === 10 ? 'ok' : sel.sum > 10 ? 'over' : 'under';
// Sounds that follow the clock and the state: 3·2·1, start, last 10 seconds, "10!" while dragging, finished.
const lastSec = v.phase === 'playing' && left !== null && left > 0 && left <= 10_000 ? Math.ceil(left / 1000) : 0;
const heard = useRef({ countdown: 0, lastSec: 0, sum: 'idle', status: mine?.status ?? null });
useEffect(() => {
const was = heard.current;
if (countdown !== was.countdown) {
if (countdown > 0) apSound.count();
else if (was.countdown > 0 && v.phase === 'playing') apSound.go();
}
if (lastSec && lastSec !== was.lastSec) sfx.tick();
if (sumState === 'ok' && was.sum !== 'ok') apSound.ten();
const st = mine?.status ?? null;
if (st !== was.status && was.status === 'playing' && (st === 'stuck' || st === 'done') && v.phase === 'playing') sfx.good();
heard.current = { countdown, lastSec, sum: sumState, status: st };
});
const others = ranked(v.seats);
// Selection rectangle in display coordinates.
@@ -348,12 +417,21 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
<div className="ap">
<style>{CSS}</style>
<div className="ap-top">
<span className={`ap-pill${v.phase === 'playing' && left <= 10_000 ? ' warn' : ''}`} role="timer" aria-label={`남은 시간 ${Math.floor(Math.ceil(left / 1000) / 60)}분 ${Math.ceil(left / 1000) % 60}초`}>
⏱ {clock(left)}
</span>
{left === null ? (
<span className="ap-pill" aria-label="제한 시간 없음">
⏱ 무제한
</span>
) : (
<span className={`ap-pill${v.phase === 'playing' && left <= 10_000 ? ' warn' : ''}`} role="timer" aria-label={`남은 시간 ${Math.floor(Math.ceil(left / 1000) / 60)}분 ${Math.ceil(left / 1000) % 60}초`}>
⏱ {clock(left)}
</span>
)}
{mine && (
<span className="ap-pill" aria-label={`내 점수 사과 ${mine.score}개`}>
🍎 <b>{mine.score}</b>
🍎{' '}
<b key={mine.score} className={mine.score ? 'anim-bump' : undefined}>
{mine.score}
</b>
</span>
)}
{mine && v.phase !== 'ended' && (
@@ -365,11 +443,13 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
{v.seats.length > 1 && (
<ol className="ap-others" aria-label="점수">
{others.map((s) => (
<li key={s.id} data-me={s.id === me} data-out={s.status === 'left'} aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''} 사과 ${s.score}개${s.status === 'stuck' ? ', 더 지울 사과 없음' : s.status === 'left' ? ', 나감' : ''}`}>
<li key={s.id} data-me={s.id === me} data-out={s.status === 'left'} aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''} 사과 ${s.score}개${statusSuffix(s)}`}>
<Avatar user={userOf(players, s.id)} size={20} />
<span>{s.id === me ? '나' : nick(players, s.id)}</span>
<b>{s.score}</b>
{s.status === 'stuck' && <span aria-hidden>✔</span>}
<b key={s.score} className={s.score ? 'anim-bump' : undefined}>
{s.score}
</b>
{(s.status === 'stuck' || s.status === 'done') && <span aria-hidden>✔</span>}
</li>
))}
</ol>
@@ -403,14 +483,17 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
const n = ch.charCodeAt(0) - 48;
if (n <= 0) return null;
const [dr, dc] = toDisp([Math.floor(i / COLS), i % COLS]);
return <AppleCell key={i} x={dc * S} y={dr * S} n={n} />;
return <AppleCell key={i} x={dc * S} y={dr * S} n={n} introDelay={intro ? (dr + dc) * 14 : undefined} />;
})}
{pops.map((p) =>
p.cells.map(({ i, n }) => {
const [dr, dc] = toDisp([Math.floor(i / COLS), i % COLS]);
return (
<g key={`${p.key}-${i}`} className="ap-pop">
<AppleCell x={dc * S} y={dr * S} n={n} />
<g key={`${p.key}-${i}`}>
<circle className="ap-burst" cx={dc * S + 20} cy={dr * S + 21} r={17} fill="none" stroke="#f87171" strokeWidth={4} />
<g className="ap-pop">
<AppleCell x={dc * S} y={dr * S} n={n} />
</g>
</g>
);
}),
@@ -425,7 +508,7 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
)}
{countdown > 0 && (
<div className="ap-over count" aria-hidden>
{countdown}
<b key={countdown}>{countdown}</b>
<small>합이 10이 되게 사과를 묶어요!</small>
</div>
)}
@@ -434,9 +517,27 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
더 지울 수 있는 사과가 없어요! 사과 {mine.score}개 · 끝날 때까지 기다려요
</div>
)}
{mine && mine.status === 'done' && v.phase === 'playing' && (
<div className="ap-over note" role="status">
여기까지 했어요! 사과 {mine.score}개 · 모두 끝날 때까지 기다려요
</div>
)}
{mine && mine.status === 'left' && v.phase !== 'ended' && <div className="ap-over note">게임에서 나갔어요.</div>}
{!mine && v.phase !== 'ended' && <div className="ap-over note">관전 중이에요 · 위에서 점수를 볼 수 있어요</div>}
</div>
{unlimited && canPlay && (
<button
type="button"
className={`btn ${stopAsk ? 'btn-primary' : 'btn-secondary'} ap-stop`}
onClick={() => {
if (!stopAsk) return setStopAsk(true);
setStopAsk(false);
act({ type: 'stop' });
}}
>
{stopAsk ? '한 번 더 누르면 여기까지 해요' : `여기까지 할래요 (사과 ${mine.score}개)`}
</button>
)}
{!phone && mine && v.phase !== 'ended' && <p className="ap-keys">마우스로 드래그해서 합이 10이면 손을 떼요 · 키보드: 화살표 + 스페이스(시작점·끝점), Esc 취소</p>}
<p className="sr-only" aria-live="polite">
{announce}
@@ -454,14 +555,14 @@ function AppleSide({ view: v, me, players }: BoardProps<AppleView>) {
<style>{CSS}</style>
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<strong>사과 게임{v.phase === 'ended' ? ' · 게임 끝' : ''}</strong>
<span className="small muted">17×10 판 · 제한 시간 {limitLabel(v.options.timeLimitSec)} · 모두 같은 판</span>
<span className="small muted">17×10 판 · 제한 시간 {limitLabel(v.options.timeLimitSec)}{v.options.timeLimitSec === null ? '(모두 끝낼 때까지)' : ''} · 모두 같은 판</span>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
{rows.map((s) => (
<li
key={s.id}
className="row"
style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'left' ? 0.55 : 1 }}
aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''}, 사과 ${s.score}개, ${s.clears}번 지움${s.status === 'stuck' ? ', 더 지울 사과 없음' : s.status === 'left' ? ', 나감' : ''}`}
aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''}, 사과 ${s.score}개, ${s.clears}번 지움${statusSuffix(s)}`}
>
<span aria-hidden style={{ width: 28, fontWeight: 800 }}>
{s.rank}등
@@ -470,7 +571,7 @@ function AppleSide({ view: v, me, players }: BoardProps<AppleView>) {
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }} aria-hidden>
{nick(players, s.id)}
{s.id === me ? ' (나)' : ''}
{s.status === 'stuck' ? ' · 다 지움' : s.status === 'left' ? ' · 나감' : ''}
{s.status === 'stuck' ? ' · 다 지움' : s.status === 'done' ? ' · 여기까지' : s.status === 'left' ? ' · 나감' : ''}
</span>
<strong style={{ fontVariantNumeric: 'tabular-nums' }} aria-hidden>
🍎 {s.score}
@@ -514,12 +615,13 @@ function statusText(v: AppleView, me: string | null, players: Record<string, Pub
}
if (mine.status === 'left') return '게임에서 나갔어요';
if (mine.status === 'stuck') return `더 지울 사과가 없어요 · 사과 ${mine.score}개 · 끝날 때까지 기다려요`;
if (mine.status === 'done') return `여기까지 했어요 · 사과 ${mine.score}개 · 모두 끝날 때까지 기다려요`;
return `사과 ${mine.score}개 지웠어요 · 합이 10이 되게 드래그!`;
}
// ---------------------------------------------------------------- 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]) => (
@@ -543,10 +645,15 @@ function Options({ value: o, onChange }: OptionsProps<AppleOptions>) {
[60, '1분'],
[120, '2분'],
[180, '3분'],
[null, '무제한'],
]}
onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec })}
/>
<span className="small muted">원래 게임은 2분이에요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.</span>
<span className="small muted">
{o.timeLimitSec === null
? '시간 제한 없이 각자 더 지울 사과가 없거나 [여기까지 할래요]를 누를 때까지 해요. 모두 끝나면 가장 많이 지운 사람이 이겨요.'
: '원래 게임은 2분이에요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.'}
</span>
</div>
</div>
);
@@ -559,7 +666,8 @@ function optionsSummary(o: AppleOptions): string {
// ---------------------------------------------------------------- rules
function Rules({ options }: { options?: AppleOptions }) {
const limit = limitLabel(options?.timeLimitSec ?? 120);
const limitSec = options ? options.timeLimitSec : 120;
const limit = limitLabel(limitSec);
return (
<div className="stack">
<p>
@@ -576,7 +684,10 @@ function Rules({ options }: { options?: AppleOptions }) {
일어나지 않고 벌칙도 없어요. 지운 자리는 빈 칸이 되고 빈 칸은 합에 들어가지 않아서, 사이가 비면 멀리 있는 사과끼리도 묶을 수 있어요.
</p>
<p>
제한 시간은 {limit}이에요. 시간이 끝나면 사과를 가장 많이 지운 사람이 이기고, 개수가 같으면 같은 순위예요. 모두 더 지울 수 있는 묶음이 없으면 조금 일찍 끝나요. 혼자서도 할 수 있어요.
{limitSec === null
? '이 방은 제한 시간이 없어요. 각자 더 지울 수 있는 묶음이 없거나 [여기까지 할래요]를 누르면 끝나고, 모두 끝나면 사과를 가장 많이 지운 사람이 이겨요. 개수가 같으면 같은 순위예요. 연결이 끊긴 채 오래 돌아오지 않으면 그때까지 점수로 끝낸 것으로 봐요.'
: `제한 시간은 ${limit}이에요. 시간이 끝나면 사과를 가장 많이 지운 사람이 이기고, 개수가 같으면 같은 순위예요. 모두 더 지울 수 있는 묶음이 없으면 조금 일찍 끝나요.`}{' '}
혼자서도 할 수 있어요.
</p>
<p>
휴대폰에서는 판을 세로로 돌려서 보여 줘요. 키보드로는 화살표로 칸을 옮기고 <strong>스페이스</strong>(또는 Enter)로 시작점, 한 번 더 눌러 끝점을 정해요. <strong>Esc</strong>는 취소예요.

View File

@@ -4,7 +4,7 @@ import type { CardView, ClaimPair, DobbleOptions, DobbleView, LogEntry, MiniGame
import type { PublicUser } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { useServerNow } from '../../components/TurnTimer';
import { haptic, sounds } from '../../lib/feedback';
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
import { useSeatRows } from '../../lib/seat-rows';
import { socket, useRoom } from '../../net/socket';
import type { BoardProps, GameUI, OptionsProps } from '../types';
@@ -21,6 +21,22 @@ const userOf = (players: Record<string, PublicUser>, id: string): PublicUser =>
players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
const who = (players: Record<string, PublicUser>, me: string | null, id: string) => (id === me ? '내가' : `${nick(players, id)}님이`);
/** Game sounds on top of the shared palette (site volume applies). */
const dbSound = {
/** Soft tap the moment a symbol is pressed (the verdict comes from the server). */
tap: () => tone(1500, 25, 'triangle', 0.06),
/** "찾았다!" two-note chime, a little brighter than the shared one. */
found: () => {
tone(1047, 80, 'triangle', 0.15);
tone(1568, 160, 'triangle', 0.13, 70);
},
count: () => tone(660, 90, 'triangle', 0.12),
go: () => {
tone(988, 120, 'triangle', 0.14);
tone(1318, 200, 'triangle', 0.12, 90);
},
};
const CSS = `
.db { width: 100%; max-width: 1060px; display: flex; flex-direction: column; gap: 10px; align-self: center; --cd: min(440px, 50vh, calc(50% - 14px)); }
.db-top { display: flex; flex-wrap: wrap; gap: 6px 8px; align-items: center; justify-content: space-between; font-weight: 700; }
@@ -47,6 +63,12 @@ button.db-seat { cursor: pointer; }
.db-card { position: relative; width: 100%; aspect-ratio: 1; border-radius: 50%; background: #fffdf6; border: 4px solid #d6c7a1; box-shadow: 0 6px 0 rgba(0,0,0,.18), 0 10px 22px rgba(0,0,0,.28); }
.db-card.empty { background: rgba(255,255,255,.1); border: 3px dashed rgba(255,255,255,.55); box-shadow: none; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 800; text-align: center; padding: 18%; }
.db-card[data-shake='true'] { animation: db-shake .4s ease; }
.db-card.slap { animation: db-slap .2s ease-out; }
.db-seat .meta .n { display: inline-block; }
.db-seat[data-done='true'] { border-color: #16a34a; }
.db-count b { display: block; animation: db-count .9s ease-out both; }
@keyframes db-slap { from { transform: scale(1.07) rotate(-3deg); } }
@keyframes db-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } }
.db-sym { position: absolute; border-radius: 50%; border: 0; padding: 0; margin: 0; background: transparent; cursor: pointer; display: flex; align-items: center; justify-content: center; -webkit-tap-highlight-color: transparent; touch-action: manipulation; }
.db-sym:disabled { cursor: default; }
@media (hover: hover) { .db-sym:hover:not(:disabled) { background: rgba(37, 99, 235, .08); } }
@@ -101,7 +123,7 @@ button.db-seat { cursor: pointer; }
.db-count { font-size: 4rem; }
}
@media (prefers-reduced-motion: reduce) {
.db-card[data-shake='true'], .db-sym .ic.in, .db-bubble, .db-sym[data-hint='true'] { animation: none; }
.db-card[data-shake='true'], .db-card.slap, .db-count b, .db-sym .ic.in, .db-bubble, .db-sym[data-hint='true'] { animation: none; }
.db-sym[data-hit='true'] .ic { transition: none; }
}
`;
@@ -144,7 +166,7 @@ function DobbleCard({
children?: ReactNode;
}) {
return (
<div className="db-card" role="group" aria-label={label} data-card={side} data-key={card.key} data-shake={!!shake}>
<div key={card.key} className="db-card slap" role="group" aria-label={label} data-card={side} data-key={card.key} data-shake={!!shake}>
{card.items.map((it, i) => {
const d = it.r * 100;
return (
@@ -286,7 +308,6 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
if (lockedLeft > 0) setBubble({ key: `lk${Date.now()}`, kind: 'late', text: `잠깐! ${Math.ceil(lockedLeft / 1000)}초 뒤에 다시 눌러요` });
return;
}
haptic(15);
act({
type: 'claim',
base: pair.base,
@@ -295,6 +316,9 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
...(pair.mine !== null ? { mine: pair.mine } : {}),
...(rtt !== null ? { rtt } : {}),
});
// After sending: feedback never delays the claim.
haptic(15);
dbSound.tap();
};
// "늦었어요" rejects come back as `reject` messages.
@@ -317,7 +341,8 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
const f = v.feedback;
if (f && f.seq !== p.feedback?.seq) {
if (f.kind === 'ok') {
sounds.ding();
dbSound.found();
sfx.cardPlay();
haptic([30, 30, 60]);
setHitArt(f.art);
const b: Bubble = { key: `f${f.seq}`, kind: 'ok', text: '찾았어요!', art: f.art };
@@ -341,7 +366,8 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
}
const h = v.lastHit;
if (h && h.seq !== p.lastHit?.seq && h.player !== me) {
sounds.stone();
sfx.cardPlay();
if (h.target === me && (mode === 'poisonedGift' || mode === 'hotPotato')) sfx.alarm();
let text = `${nick(players, h.player)}님이 찾았어요`;
if (mode === 'poisonedGift' && h.target === me) text = `${nick(players, h.player)}님이 나에게 카드를 줬어요`;
if (mode === 'hotPotato' && h.target === me) text = `${nick(players, h.player)}님이 카드 묶음을 넘겼어요!`;
@@ -353,7 +379,14 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
const text = r.loser ? `${r.round}라운드 끝! ${r.loser === me ? '내가' : `${nick(players, r.loser)}님이`} 카드 ${r.cards}장을 벌점으로 받아요` : `${r.round}라운드는 무효예요`;
setBubble({ key: `r${r.round}`, kind: r.loser === me ? 'bad' : 'info', text });
setAnnounce(text);
if (r.loser === me) sfx.bad();
else sfx.whoosh();
}
// Someone emptied their cards / escaped this round.
const done = v.seats.filter((s) => (s.status === 'finished' || s.status === 'escaped') && p.seats.find((x) => x.id === s.id)?.status === 'playing');
if (done.length && v.phase !== 'ended') sfx.good();
// The stall hint just appeared.
if (v.hint.length && v.hintUntil !== p.hintUntil && v.hintUntil > 0) sfx.select();
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
@@ -373,6 +406,16 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
}, [hitArt]);
const countdown = v.phase === 'countdown' || v.phase === 'roundEnd' ? Math.max(0, Math.ceil((v.phaseEndsAt - now) / 1000)) : 0;
// 3·2·1 beeps before the cards open, a start beep when they do.
const beep = v.phase === 'countdown' || v.phase === 'roundEnd' ? countdown : -1;
const beeped = useRef(-1);
useEffect(() => {
const was = beeped.current;
beeped.current = beep;
if (beep === was) return;
if (beep > 0 && beep <= 3) dbSound.count();
else if (beep === -1 && was >= 0 && playing) dbSound.go();
}, [beep, playing]);
const hint = v.hintUntil > now ? v.hint : [];
const tapper = canTap || (!!pair && playing && lockedLeft > 0) ? claim : null;
@@ -464,7 +507,9 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{nick(players, s.id)}</span>
</span>
<span className="meta">
{countText(mode, s)}
<span key={countText(mode, s)} className="n anim-bump">
{countText(mode, s)}
</span>
{s.lockedUntil > now && s.status === 'playing' ? ' · 잠금' : ''}
</span>
{v.options.showRtt && <Rtt ms={s.rtt} />}
@@ -486,7 +531,7 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
{inner}
</button>
) : (
<div className="db-seat" data-seat={s.id} data-out={s.status !== 'playing'} aria-label={seatLabel(v, s, players, me)} aria-pressed={targetMode ? targetId === s.id : undefined}>
<div className="db-seat" data-seat={s.id} data-out={s.status !== 'playing'} data-done={s.status === 'finished' || s.status === 'escaped'} aria-label={seatLabel(v, s, players, me)} aria-pressed={targetMode ? targetId === s.id : undefined}>
{inner}
</div>
)}
@@ -507,7 +552,7 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
)}
{countdown > 0 && (
<div className="db-count" aria-hidden>
{countdown}
<b key={countdown}>{countdown}</b>
<small>{v.phase === 'roundEnd' ? '다음 라운드를 준비해요' : '두 카드에 똑같이 있는 그림을 찾아요!'}</small>
</div>
)}

View File

@@ -33,6 +33,7 @@ export function helpNow(v: HalliGalliView, me: string | null, players: Record<st
if (v.options.autoFlip) lines.push('내 차례예요. 이 방은 카드가 자동으로 뒤집혀요.');
else if (v.pendingFlip) lines.push('내 차례예요. 뒤집기를 눌렀어요. 곧 카드가 펼쳐져요.');
else if (mine.deck === 0) lines.push('내 차례인데 내 덱(뒤집을 카드 더미)이 비었어요.');
else if (v.flipTotalMs === null) lines.push('내 차례예요. 아래 [뒤집기]를 눌러 카드를 한 장 펼쳐요. 시간 제한은 없어요.');
else lines.push(`내 차례예요. 아래 [뒤집기]를 눌러 카드를 한 장 펼쳐요. ${v.flipTotalMs / 1000}초가 지나면 자동으로 뒤집혀요.`);
} else {
lines.push(`${nick(v.turn)}님이 뒤집을 차례예요. 차례가 아니어도 종은 언제든 누를 수 있어요.`);

View File

@@ -4,7 +4,7 @@ import type { Fruit, FruitCount, HalliGalliOptions, HalliGalliView, LogEntry, Se
import type { PublicUser } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { useServerNow } from '../../components/TurnTimer';
import { haptic, sounds } from '../../lib/feedback';
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
import { socket, useRoom } from '../../net/socket';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
@@ -19,6 +19,21 @@ const userOf = (players: Record<string, PublicUser>, id: string): PublicUser =>
players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
const cardName = (c: Pick<TopCard, 'fruit' | 'count'>) => `${FRUIT_KO[c.fruit]} ${c.count}개`;
/** Game sounds on top of the shared palette (site volume applies). */
const hgSound = {
/** Countdown 3·2·1 and the start beep. */
count: () => tone(660, 90, 'triangle', 0.12),
go: () => {
tone(988, 120, 'triangle', 0.14);
tone(1318, 200, 'triangle', 0.12, 90);
},
/** Every face-up card swept to the winner. */
sweep: (cards: number) => {
sfx.whoosh();
sfx.deal(Math.min(6, Math.max(2, Math.ceil(cards / 3))), 45);
},
};
const CSS = `
.hg { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 10px; align-self: center; }
.hg-top { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; justify-content: space-between; font-weight: 700; }
@@ -82,6 +97,12 @@ const CSS = `
.hg-panel { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 12px; }
.hg-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 220px; overflow: auto; }
.hg-fruit-ic { width: 26px; height: 26px; display: inline-block; vertical-align: middle; }
.hg-seat[data-shake='true'] .hg-pile { animation: anim-shake .45s ease; }
.hg-seat[data-out='true'] .hg-pile { filter: grayscale(.7); transition: filter .4s ease; }
.hg-meta .gain { display: inline-block; }
.hg-count b { display: block; animation: hg-count .9s ease-out both; }
.hg-flipbtn.anim-glow { animation-duration: 1.1s; }
@keyframes hg-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } }
@keyframes hg-blink { 0%,100% { box-shadow: 0 0 0 0 rgba(253,224,71,.0); } 50% { box-shadow: 0 0 0 6px rgba(253,224,71,.55); } }
@keyframes hg-flip { from { transform: rotateY(85deg) scale(.9); } to { transform: none; } }
@keyframes hg-pop { 0% { transform: translateX(-50%) scale(.6); opacity: 0; } 70% { transform: translateX(-50%) scale(1.06); opacity: 1; } 100% { transform: translateX(-50%) scale(1); } }
@@ -96,7 +117,7 @@ const CSS = `
}
@media (prefers-reduced-motion: reduce) {
.hg-seat[data-turn='true'] { animation: none; box-shadow: 0 0 0 4px rgba(253,224,71,.55); }
.hg-pile .face, .hg-bell .art[data-ring='true'], .hg-bubble { animation: none; }
.hg-pile .face, .hg-bell .art[data-ring='true'], .hg-bubble, .hg-count b, .hg-seat[data-shake='true'] .hg-pile { animation: none; }
.hg-ghost { display: none; }
}
`;
@@ -296,14 +317,22 @@ function seatLabel(s: SeatView, players: Record<string, PublicUser>, me: string
return parts.join(', ');
}
function Seat({ s, v, pos, players, me, now }: { s: SeatView; v: HalliGalliView; pos: Pos; players: Record<string, PublicUser>; me: string | null; now: number }) {
function Seat({ s, v, pos, players, me, now, shake }: { s: SeatView; v: HalliGalliView; pos: Pos; players: Record<string, PublicUser>; me: string | null; now: number; shake: boolean }) {
const u = userOf(players, s.id);
const locked = s.lockedUntil > now && s.status === 'playing';
// The deck count bumps when it grows (cards won with the bell or given as a penalty).
const lastDeck = useRef(s.deck);
const [gain, setGain] = useState(0);
useEffect(() => {
if (s.deck > lastDeck.current) setGain((g) => g + 1);
lastDeck.current = s.deck;
}, [s.deck]);
return (
<li
className="hg-seat"
data-turn={s.isTurn && v.phase === 'playing'}
data-out={s.status !== 'playing'}
data-shake={shake}
data-me={s.id === me}
data-seat={s.id}
style={{ left: pos.left, top: pos.top }}
@@ -322,10 +351,10 @@ function Seat({ s, v, pos, players, me, now }: { s: SeatView; v: HalliGalliView;
) : (
<span className="empty" />
)}
{s.isTurn && v.phase === 'playing' && <Gauge start={v.turnStartedAt} end={v.turnDeadline} now={now} />}
{s.isTurn && v.phase === 'playing' && v.turnDeadline !== null && <Gauge start={v.turnStartedAt} end={v.turnDeadline} now={now} />}
</div>
<div className="hg-meta" aria-hidden>
<span>
<span key={gain} className={gain > 0 ? 'gain anim-bump' : 'gain'}>
<i className="hg-back" /> {s.deck}
</span>
{s.status === 'out' && (
@@ -384,6 +413,7 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
const [bubble, setBubble] = useState<Bubble | null>(null);
const [ghosts, setGhosts] = useState<Ghost[]>([]);
const [hit, setHit] = useState(0);
const [shake, setShake] = useState<{ id: string; seq: number } | null>(null);
const [announce, setAnnounce] = useState('');
const sentFor = useRef<number | null>(null);
const prev = useRef<HalliGalliView | null>(null);
@@ -406,10 +436,11 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
const ring = () => {
if (!canRing || sentFor.current === v.tableVersion) return;
sentFor.current = v.tableVersion;
// Send first: the sound and the bell wobble must not delay the press by a frame.
act({ type: 'ring', version: v.tableVersion, ...(v.options.latencyComp === 'light' && rtt !== null ? { rtt } : {}) });
setHit((h) => h + 1);
sounds.ding();
haptic(30);
act({ type: 'ring', version: v.tableVersion, ...(v.options.latencyComp === 'light' && rtt !== null ? { rtt } : {}) });
};
const flip = () => {
if (!canFlip) return;
@@ -469,13 +500,17 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
}
const to = posOf(b.player);
const fly: Ghost[] = [];
// Someone else's bell wobbles too (mine already did on the press).
if (b.player !== me) setHit((h) => h + 1);
if (b.correct) {
if (b.player !== me) sounds.ding();
else haptic([40, 30, 80]);
hgSound.sweep(b.cards);
p.seats.forEach((s, i) => s.top && fly.push({ key: `g${b.seq}-${s.id}`, from: posOf(s.id), to, card: s.top, delay: i * 40 }));
if (p.pot > 0) fly.push({ key: `g${b.seq}-pot`, from: CENTER, to, card: null, delay: 0 });
} else {
sounds.buzz();
setShake({ id: b.player, seq: b.seq });
if (b.player === me) haptic([90, 50, 90]);
const from = posOf(b.player);
const targets = v.options.wrongToPot ? [CENTER] : p.seats.filter((s) => s.id !== b.player && s.status === 'playing').map((s) => posOf(s.id));
@@ -484,8 +519,10 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
setGhosts(fly);
return;
}
const outNow = v.seats.filter((s) => s.status !== 'playing' && p.seats.find((x) => x.id === s.id)?.status === 'playing');
if (outNow.length && v.phase !== 'ended') sfx.capture();
if (v.tableVersion !== p.tableVersion && v.lastFlipBy) {
sounds.stone();
sfx.cardFlip();
const s = v.seats.find((x) => x.id === v.lastFlipBy);
if (s?.top) setAnnounce(`${s.id === me ? '내가' : `${nick(players, s.id)}님이`} ${cardName(s.top)}를 뒤집었어요`);
}
@@ -503,6 +540,12 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
return () => clearTimeout(t);
}, [ghosts]);
useEffect(() => {
if (!shake) return;
const t = setTimeout(() => setShake(null), 500);
return () => clearTimeout(t);
}, [shake]);
useEffect(() => {
if (!bubble) return;
const t = setTimeout(() => setBubble(null), bubble.kind === 'late' ? 1300 : 1900);
@@ -514,6 +557,19 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
const totals = FRUITS.map((f) => ({ f, n: v.seats.reduce((a, s) => a + (s.top && s.top.fruit === f ? s.top.count : 0), 0) }));
const timeLeft = v.endsAt !== null ? Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt)) : null;
const ping = rtt;
// 3·2·1 beeps, a start beep, and ticks in the last 10 seconds of the game clock.
const beep = v.phase === 'countdown' ? countdown : -1;
const lastSec = playing && timeLeft !== null && timeLeft > 0 && timeLeft <= 10_000 ? Math.ceil(timeLeft / 1000) : 0;
const sounded = useRef({ beep: -1, lastSec: 0 });
useEffect(() => {
const was = sounded.current;
if (beep !== was.beep) {
if (beep > 0) hgSound.count();
else if (beep === -1 && was.beep >= 0 && playing) hgSound.go();
}
if (lastSec && lastSec !== was.lastSec) sfx.tick();
sounded.current = { beep, lastSec };
}, [beep, lastSec, playing]);
return (
<div className="hg">
@@ -546,7 +602,7 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
>
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }} aria-label="사람들의 펼친 카드">
{rot.map((s, i) => (
<Seat key={s.id} s={s} v={v} pos={pos[i]!} players={players} me={me} now={now} />
<Seat key={s.id} s={s} v={v} pos={pos[i]!} players={players} me={me} now={now} shake={shake?.id === s.id} />
))}
</ul>
<div className="hg-center">
@@ -603,7 +659,7 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
)}
{countdown > 0 && (
<div className="hg-count" aria-hidden>
{countdown}
<b key={countdown}>{countdown}</b>
<small>과일이 딱 5개가 되면 종을 쳐요!</small>
</div>
)}
@@ -617,7 +673,7 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
<i className="hg-back" /> {mine.deck}장
</b>
</div>
<button type="button" className={`btn ${myTurn ? 'btn-primary' : 'btn-secondary'} hg-flipbtn`} disabled={!canFlip} onClick={flip} aria-keyshortcuts="Enter">
<button type="button" className={`btn ${myTurn ? 'btn-primary' : 'btn-secondary'} hg-flipbtn${canFlip ? ' anim-glow' : ''}`} disabled={!canFlip} onClick={flip} aria-keyshortcuts="Enter">
{v.options.autoFlip ? (myTurn ? '곧 자동으로 뒤집혀요' : '자동 뒤집기') : v.pendingFlip && myTurn ? '곧 뒤집혀요…' : myTurn ? '뒤집기' : `${v.turn ? nick(players, v.turn) : ''}님 차례`}
</button>
</div>
@@ -667,7 +723,8 @@ function logText(e: LogEntry, players: Record<string, PublicUser>, me: string |
function rulesLine(o: HalliGalliOptions): string {
const parts = [o.endMode === 'official' ? '2명 남으면 다음 종에서 끝' : '한 명 남을 때까지', o.timeLimitMin ? `${o.timeLimitMin}분 제한` : '시간 제한 없음'];
parts.push(o.autoFlip ? `자동 뒤집기 ${o.kidMode ? 8 : o.flipSeconds}초` : `뒤집기 ${o.kidMode ? 8 : o.flipSeconds}초`);
const sec = o.flipSeconds === null ? (o.autoFlip ? (o.kidMode ? 8 : 3) : null) : o.kidMode ? 8 : o.flipSeconds;
parts.push(o.autoFlip ? `자동 뒤집기 ${sec}초` : sec === null ? '뒤집기 시간 무제한' : `뒤집기 ${sec}초`);
if (o.wrongRingLockoutMs) parts.push(`틀리면 종 ${o.wrongRingLockoutMs / 1000}초 잠금`);
if (o.penaltyEscalation) parts.push('벌칙 점점 늘어남');
if (o.wrongToPot) parts.push('벌칙은 종 밑으로');
@@ -815,7 +872,10 @@ function Options({ value: o, onChange }: OptionsProps<HalliGalliOptions>) {
onChange={(timeLimitMin) => set({ timeLimitMin })}
/>
</Field>
<Field label="뒤집기 제한 시간" help="시간 안에 안 뒤집으면 자동으로 뒤집혀요.">
<Field
label="뒤집기 제한 시간"
help={o.flipSeconds === null ? (o.autoFlip ? '자동 뒤집기에서는 3초(어린이 모드 8초)마다 뒤집혀요.' : '차례인 사람이 직접 뒤집을 때까지 기다려요.') : '시간 안에 안 뒤집으면 자동으로 뒤집혀요.'}
>
<Seg
label="뒤집기 제한 시간"
value={o.flipSeconds}
@@ -824,11 +884,12 @@ function Options({ value: o, onChange }: OptionsProps<HalliGalliOptions>) {
[3, '3초'],
[5, '5초'],
[8, '8초'],
[null, '무제한'],
]}
onChange={(flipSeconds) => set({ flipSeconds })}
/>
</Field>
<Field label="어린이 모드" help="8초 뒤집기, 과일 합계 막대를 보여 줘요.">
<Field label="어린이 모드" help={o.flipSeconds === null && !o.autoFlip ? '과일 합계 막대를 보여 줘요(뒤집기 시간은 무제한 그대로).' : '8초 뒤집기, 과일 합계 막대를 보여 줘요.'}>
<Seg label="어린이 모드" value={o.kidMode} options={onOff} onChange={(kidMode) => set({ kidMode })} />
</Field>
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>

View File

@@ -80,7 +80,7 @@ describe('판 만들기', () => {
}
const s = make(['A', 'B', 'C']);
expect(new Set(Object.values(s.boards))).toEqual(new Set([s.initial]));
expect(s.endsAt).toBe(START + 120_000);
expect(s.endsAt!).toBe(START + 120_000);
expect(make(['A'], { timeLimitSec: 60 }).endsAt).toBe(START + 60_000);
});
@@ -160,10 +160,10 @@ describe('진행', () => {
s = act(s, 'A', sel(m1!), START + 1000);
s = act(s, 'B', sel(m1!), START + 1000);
s = act(s, 'B', sel(findMoves(s.boards.B!)[0]!), START + 2000);
expect(apple.deadline!(s)).toBe(s.endsAt);
expect(apple.timeoutNotBefore!(s)).toBe(s.endsAt);
expect(reason(s, 'C', sel(m1!), s.endsAt)).toBe('시간이 다 됐어요.');
s = tick(s, s.endsAt);
expect(apple.deadline!(s)).toBe(s.endsAt!);
expect(apple.timeoutNotBefore!(s)).toBe(s.endsAt!);
expect(reason(s, 'C', sel(m1!), s.endsAt!)).toBe('시간이 다 됐어요.');
s = tick(s, s.endsAt!);
expect(s.phase).toBe('ended');
const r = apple.result(s)!;
expect(r.ranking).toEqual([['B'], ['A'], ['C']]);
@@ -178,7 +178,7 @@ describe('진행', () => {
let s = make(['A']);
s = tick(s, START);
s = act(s, 'A', sel(findMoves(s.initial)[0]!), START + 500);
s = tick(s, s.endsAt + 5);
s = tick(s, s.endsAt! + 5);
const r = apple.result(s)!;
expect(r.ranking).toEqual([['A']]);
expect(r.summary).toBe(`시간이 다 됐어요. 사과 ${s.score.A}개를 지웠어요`);
@@ -220,7 +220,8 @@ describe('진행', () => {
expect(solo.phase).toBe('ended');
});
test('클라이언트 액션 스키마에는 select만(tick/leave는 시스템 전용)', () => {
test('클라이언트 액션 스키마에는 select·stop만(tick/leave는 시스템 전용)', () => {
expect(apple.actionSchema.safeParse({ type: 'stop' }).success).toBe(true);
expect(apple.actionSchema.safeParse({ type: 'tick' }).success).toBe(false);
expect(apple.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 9, c1: 16 }).success).toBe(true);
@@ -229,6 +230,47 @@ describe('진행', () => {
});
});
describe('제한 시간 무제한', () => {
test('마감 없음: 모두 막히거나 「여기까지」하면 끝, 시간 제한 방에서는 여기까지 거절', () => {
let s = make(['A', 'B'], { timeLimitSec: null });
expect(s.endsAt).toBeNull();
expect(apple.deadline!(s)).toBe(s.countdownEndsAt);
expect(reason(s, 'A', { type: 'stop' }, T0 + 100)).toBe('곧 시작해요. 잠시만 기다려 주세요.');
s = tick(s, START);
expect(s.phase).toBe('playing');
expect(s.status.A).toBe('playing'); // the start tick is not an away tick
expect(apple.deadline!(s)).toBeNull();
expect(apple.timeoutNotBefore!(s)).toBeNull();
// Hours later the board still takes moves.
const m = findMoves(s.initial)[0]!;
s = act(s, 'A', sel(m), START + 3_600_000);
expect(s.score.A).toBeGreaterThan(0);
s = act(s, 'A', { type: 'stop' }, START + 3_600_100);
expect(s.status.A).toBe('done');
expect(reason(s, 'A', { type: 'stop' }, START + 3_600_200)).toBe('이미 끝냈어요.');
expect(apple.activePlayers(s)).toEqual(['B']);
expect(apple.timeoutPlayers!(s)).toEqual(['B']);
s = act(s, 'B', { type: 'stop' }, START + 3_600_300);
expect(s.phase).toBe('ended');
const r = apple.result(s)!;
expect(r.ranking).toEqual([['A'], ['B']]);
expect(r.summary).toContain('모두 끝냈어요');
expect(reason(tick(make(['A']), START), 'A', { type: 'stop' }, START + 10)).toBe('제한 시간이 있는 방에서는 끝날 때까지 해요.');
});
test('자리 비움: 방이 유예 뒤 tick을 보내면 그 사람은 여기까지(점수 유지), 혼자면 바로 끝', () => {
let s = tick(make(['A', 'B'], { timeLimitSec: null }), START);
s = act(s, 'B', sel(findMoves(s.initial)[0]!), START + 500);
s = apple.apply(s, 'B', { type: 'tick' }, { rng: rng(), now: START + 60_000 }).state;
expect(s.status.B).toBe('done');
expect(s.score.B).toBeGreaterThan(0);
expect(s.phase).toBe('playing');
const solo = apple.apply(tick(make(['A'], { timeLimitSec: null }), START), 'A', { type: 'tick' }, { rng: rng(), now: START + 60_000 }).state;
expect(solo.phase).toBe('ended');
expect(apple.result(solo)!.summary).toBe('여기까지 했어요. 사과 0개를 지웠어요');
});
});
describe('무작위 대국', () => {
test.each([1, 2, 5, 8])('%i명: 엔진 randomPlayout(유출·JSON·결정성) 끝까지', (n) => {
const players = Array.from({ length: n }, (_, i) => `p${i + 1}`);
@@ -244,4 +286,11 @@ describe('무작위 대국', () => {
for (const p of players) expect(s.score[p]).toBe([...s.boards[p]!].filter((c) => c === '0').length);
}
});
test.each([1, 3])('무제한 %i명: 끝까지(여기까지·자리 비움 tick 포함)', (n) => {
const players = Array.from({ length: n }, (_, i) => `p${i + 1}`);
for (let i = 0; i < playoutSeeds(10); i++) {
const a = randomPlayout(apple, { players, options: apple.optionsSchema.parse({ timeLimitSec: null }), seed: seedN(900 + n * 10 + i), maxSteps: 1000, maxApplyMs: 20 });
expect(a.finished).toBe(true);
}
});
});

View File

@@ -133,7 +133,7 @@ interface Ctx {
events: GameEvent[];
}
const inGame = (s: S, p: PlayerId) => s.status[p] === 'playing' || s.status[p] === 'stuck';
const inGame = (s: S, p: PlayerId) => s.status[p] !== 'left';
/** The countdown is over (the room timer may not have ticked yet). */
const started = (s: S, now: number | undefined) => s.phase === 'playing' || (s.phase === 'countdown' && now !== undefined && now >= s.countdownEndsAt);
@@ -148,7 +148,15 @@ function catchUp(s: S, ctx: Ctx): void {
s.phase = 'playing';
ctx.events.push({ type: 'start' });
}
if (s.phase === 'playing' && ctx.now >= s.endsAt) finish(s, 'time', ctx);
if (s.phase === 'playing' && s.endsAt !== null && ctx.now >= s.endsAt) finish(s, 'time', ctx);
}
/** 무제한: a player stops (「여기까지」, or the room timed them out while away); the game ends when nobody is still playing. */
function stop(s: S, p: PlayerId, ctx: Ctx): void {
if (s.status[p] !== 'playing') return;
s.status[p] = 'done';
ctx.events.push({ type: 'done', player: p });
if (s.order.every((q) => s.status[q] !== 'playing')) finish(s, 'cleared', ctx);
}
function select(s: S, p: PlayerId, a: SelectAction, ctx: Ctx): void {
@@ -209,10 +217,15 @@ function finish(s: S, reason: EndReason, ctx: Ctx): void {
let summary: string;
if (s.order.length === 1) {
const n = ranking[0]!.score;
summary = reason === 'cleared' ? `더 지울 사과가 없어요. 사과 ${n}개를 지웠어요` : `시간이 다 됐어요. 사과 ${n}개를 지웠어요`;
const why = s.status[s.order[0]!] === 'done' ? '여기까지 했어요.' : '더 지울 사과가 없어요.';
summary = reason === 'cleared' ? `${why} 사과 ${n}개를 지웠어요` : `시간이 다 됐어요. 사과 ${n}개를 지웠어요`;
} else if (reason === 'left') summary = '다른 사람이 모두 나가서 남은 사람이 이겼어요';
else {
summary = reason === 'cleared' ? '모두 더 지울 사과가 없어요. 가장 많이 지운 사람이 이겼어요' : '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요';
const anyDone = s.order.some((p) => s.status[p] === 'done');
summary =
reason === 'cleared'
? `${anyDone ? '모두 끝냈어요' : '모두 더 지울 사과가 없어요'}. 가장 많이 지운 사람이 이겼어요`
: '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요';
if (top.length > 1) summary += ` (공동 1등 ${top.length}명)`;
}
s.final = { endReason: reason, ranking, summary } satisfies AppleFinal;
@@ -250,7 +263,7 @@ export const apple: Def = {
recent: per0<number[]>(() => []),
phase: 'countdown',
countdownEndsAt,
endsAt: countdownEndsAt + options.timeLimitSec * 1000,
endsAt: options.timeLimitSec === null ? null : countdownEndsAt + options.timeLimitSec * 1000,
final: null,
};
},
@@ -264,10 +277,14 @@ export const apple: Def = {
return ok;
case 'leave':
return inGame(s, actor) ? ok : fail('이미 게임에서 빠졌어요.');
case 'stop':
if (s.endsAt !== null) return fail('제한 시간이 있는 방에서는 끝날 때까지 해요.');
if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.');
return s.status[actor] === 'playing' ? ok : fail('이미 끝냈어요.');
case 'select': {
if (s.status[actor] === 'left') return fail('게임에서 빠졌어요.');
if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.');
if (now !== undefined && now >= s.endsAt) return fail('시간이 다 됐어요.');
if (now !== undefined && s.endsAt !== null && now >= s.endsAt) return fail('시간이 다 됐어요.');
if (s.status[actor] === 'stuck') return fail('더 지울 수 있는 사과가 없어요.');
if (!rateOk(s.recent[actor], now)) return fail('조금 천천히 해 주세요.');
const { sum, count } = rectSum(s.boards[actor]!, a);
@@ -281,10 +298,14 @@ export const apple: Def = {
apply(prev, actor, a, { now }) {
const s = clone(prev);
const ctx: Ctx = { now, events: [] };
const wasPlaying = prev.phase === 'playing';
catchUp(s, ctx);
if (s.phase !== 'ended') {
if (a.type === 'leave') leave(s, actor, ctx);
else if (a.type === 'select' && s.phase === 'playing') select(s, actor, a, ctx);
else if (a.type === 'stop' && s.phase === 'playing') stop(s, actor, ctx);
// 무제한: nothing is due during play, so a tick there means the room timed this player out while away.
else if (a.type === 'tick' && wasPlaying && s.endsAt === null) stop(s, actor, ctx);
}
return { state: s, events: ctx.events };
},
@@ -316,9 +337,13 @@ export const apple: Def = {
return s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt;
},
/** Everyone still in drives the clock (a stuck player too: they wait for the end like everybody else). */
/**
* Everyone still in drives the clock (a stuck player too: they wait for the end like everybody else).
* 무제한 after the start: only those still playing (an away one is stopped after the room's grace period).
*/
timeoutPlayers(s) {
if (s.phase === 'ended') return [];
if (s.phase === 'playing' && s.endsAt === null) return s.order.filter((p) => s.status[p] === 'playing');
return s.order.filter((p) => inGame(s, p));
},
@@ -351,12 +376,13 @@ export const apple: Def = {
};
},
/** Test helper: the clock tick and the first few rectangles that add up to 10. */
/** Test helper: the clock tick, the first few rectangles that add up to 10 and (무제한) 「여기까지」. */
legalActions(s, p) {
if (s.phase === 'ended' || !s.order.includes(p)) return [];
const out: A[] = [{ type: 'tick' }];
if (s.phase === 'playing' && s.status[p] === 'playing') {
for (const m of findMoves(s.boards[p]!, 8)) out.push({ type: 'select', ...m });
if (s.endsAt === null) out.push({ type: 'stop' });
}
return out.filter((x) => apple.validate(s, p, x).ok);
},

View File

@@ -8,29 +8,33 @@ export const COLS = 17;
export const CELLS = ROWS * COLS;
export const TARGET = 10;
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 appleOptionsSchema = z.object({
timeLimitSec: lit<60 | 120 | 180>(60, 120, 180)
/** null = 무제한: everyone plays until they run out of moves or press 「여기까지」 (`stop`). */
timeLimitSec: lit<60 | 120 | 180 | null>(60, 120, 180, null)
.default(120)
.meta({ title: '제한 시간', labels: { 60: '1분', 120: '2분', 180: '3분' } }),
.meta({ title: '제한 시간', labels: { 60: '1분', 120: '2분', 180: '3분', null: '무제한(모두 끝낼 때까지)' } }),
});
export type AppleOptions = z.infer<typeof appleOptionsSchema>;
/** A rectangle by two opposite corners (any order), rows 0..9, columns 0..16. */
export const appleActionSchema = z.object({
const selectSchema = z.object({
type: z.literal('select'),
r0: z.number().int().min(0).max(ROWS - 1),
c0: z.number().int().min(0).max(COLS - 1),
r1: z.number().int().min(0).max(ROWS - 1),
c1: z.number().int().min(0).max(COLS - 1),
});
export type SelectAction = z.infer<typeof appleActionSchema>;
/** Client action plus system-only ones (server timer, leaving) that are not in the schema. */
export type AppleAction = SelectAction | { type: 'tick' } | { type: 'leave' };
/** `stop` = 「여기까지」: only with no time limit, ends my game with the score I have. */
export const appleActionSchema = z.discriminatedUnion('type', [selectSchema, z.object({ type: z.literal('stop') })]);
export type SelectAction = z.infer<typeof selectSchema>;
/** Client actions plus system-only ones (server timer, leaving) that are not in the schema. */
export type AppleAction = z.infer<typeof appleActionSchema> | { type: 'tick' } | { type: 'leave' };
export type SeatStatus = 'playing' | 'stuck' | 'left';
/** `done` = stopped by choice (무제한 「여기까지」) or away past the grace period in a game without a time limit. */
export type SeatStatus = 'playing' | 'stuck' | 'done' | 'left';
export type EndReason = 'time' | 'cleared' | 'left';
export interface RankRow {
@@ -61,7 +65,8 @@ export interface AppleState {
recent: Record<PlayerId, number[]>;
phase: 'countdown' | 'playing' | 'ended';
countdownEndsAt: number;
endsAt: number;
/** null = 무제한. */
endsAt: number | null;
final: AppleFinal | null;
}
@@ -81,7 +86,7 @@ export interface AppleView {
/** My board (CELLS digits, '0' = cleared); null for spectators and during the countdown. */
cells: string | null;
countdownEndsAt: number;
endsAt: number;
endsAt: number | null;
seats: SeatView[];
result: AppleFinal | null;
}

View File

@@ -10,6 +10,7 @@ import {
allCardIds,
cardOf,
fiveFruit,
flipMs,
halliGalli as hg,
type Fruit,
type HalliGalliAction,
@@ -94,7 +95,8 @@ function rig(
s.phase = 'playing';
s.turn = r.turn ?? players[0]!;
s.turnStartedAt = now;
s.turnDeadline = now + s.options.flipSeconds * 1000 * (s.options.kidMode ? 8 / s.options.flipSeconds : 1);
const ms = flipMs(s.options);
s.turnDeadline = ms === null ? null : now + ms;
s.flipAllowedAt = now;
s.pendingFlip = null;
s.tableVersion = 5;
@@ -388,11 +390,35 @@ describe('뒤집기와 시간 (§5.1, §8.5)', () => {
expect(n.turnDeadline).toBe(START + 4000);
});
test('뒤집기 시간 무제한: 기다리다가 직접 뒤집기, 끊기면 방의 유예 뒤 자동, 자동 뒤집기는 3초 간격', () => {
const s = rig(['A', 'B'], { decks: { A: [3, 3], B: [3, 3] }, turn: 'A' }, { flipSeconds: null, timeLimitMin: null });
expect(s.turnDeadline).toBeNull();
expect(hg.deadline!(s)).toBeNull();
expect(hg.view(s, 'A').flipTotalMs).toBeNull();
// A non-turn tick (someone else's clock) does nothing however late it is.
const idle = act(s, 'B', { type: 'tick' }, START + 600_000);
expect(idle.faceUp.A).toHaveLength(0);
// A flips when ready; B's turn also has no deadline.
const n = act(s, 'A', { type: 'flip' }, START + 60_000);
expect(n.faceUp.A).toHaveLength(1);
expect(n.turn).toBe('B');
expect(n.turnDeadline).toBeNull();
expect(hg.deadline!(n)).toBeNull();
// The room times out an away turn player (its own grace period): that still flips.
const away = act(n, 'B', { type: 'tick' }, START + 120_000);
expect(away.faceUp.B).toHaveLength(1);
// 무제한 + 자동 뒤집기 keeps a 3-second pace (어린이 모드 8초).
const auto = rig(['A', 'B'], { decks: { A: [3], B: [3] }, turn: 'A' }, { flipSeconds: null, autoFlip: true });
expect(auto.turnDeadline).toBe(START + 3000);
expect(flipMs({ ...auto.options, kidMode: true })).toBe(8000);
expect(flipMs({ ...s.options, kidMode: true })).toBeNull();
});
test('시간 제한 만료: 보유 카드(덱 + 자기 공개 더미) 순, 동점은 정답 횟수, 그래도 같으면 공동', () => {
const s = rig(['A', 'B', 'C', 'D'], { decks: { A: [3], B: [5], C: [4], D: [4] }, faceUp: { A: ['S1', 'S1'], C: ['P1'], D: ['P1'] }, turn: 'A' }, { timeLimitMin: 5 });
s.correctCount = { A: 0, B: 0, C: 2, D: 2 };
// A 5 (3 + 2), B 5, C 5, D 5 → A,B (0 correct) below C,D (2 correct)
expect(hg.deadline!(s)).toBe(Math.min(s.endsAt!, s.turnDeadline));
expect(hg.deadline!(s)).toBe(Math.min(s.endsAt!, s.turnDeadline!));
const n = act(s, 'B', ringA(s), s.endsAt!); // any action at/after the end time ends the game first
expect(n.phase).toBe('ended');
expect(n.final!.endReason).toBe('timeLimit');
@@ -657,6 +683,8 @@ const PRESETS: Partial<HalliGalliOptions>[] = [
{ penaltyEscalation: true, strikeOut: true, timeLimitMin: 5 },
{ wrongToPot: true, autoFlip: true, flipGuardMs: 400, wrongRingLockoutMs: 0 },
{ duelWrongLoses: true, kidMode: true, timeLimitMin: 15 },
{ flipSeconds: null, kidMode: true },
{ flipSeconds: null, autoFlip: true, timeLimitMin: null },
];
describe('random playouts (§10, docs/09 §7)', () => {

View File

@@ -34,7 +34,15 @@ export const AWAY_FLIP_MS = 1000;
const LOG_KEEP = 30;
const POINTS = [3, 2, 1];
export const flipMs = (o: HalliGalliOptions): number => (o.kidMode ? 8 : o.flipSeconds) * 1000;
/** Flip time limit in ms; null = 무제한 (자동 뒤집기 still needs a pace: 3 s, 어린이 모드 8 s). */
export function flipMs(o: HalliGalliOptions): number | null {
if (o.flipSeconds === null) return o.autoFlip ? (o.kidMode ? 8 : 3) * 1000 : null;
return (o.kidMode ? 8 : o.flipSeconds) * 1000;
}
const deadlineFrom = (o: HalliGalliOptions, from: number): number | null => {
const ms = flipMs(o);
return ms === null ? null : from + ms;
};
/** Public key of a visible card; secretsOf uses the same form so leak checks are meaningful. */
export const cardKey = (id: number): string => `hg${id}`;
@@ -116,7 +124,7 @@ function othersClockwise(s: S, p: PlayerId): PlayerId[] {
function startTurn(s: S, p: PlayerId, now: number): void {
s.turn = p;
s.turnStartedAt = now;
s.turnDeadline = now + flipMs(s.options);
s.turnDeadline = deadlineFrom(s.options, now);
s.pendingFlip = null;
}
@@ -327,7 +335,7 @@ function tick(s: S, actor: PlayerId, ctx: Ctx): void {
if (ctx.now >= s.ringWindow.openedAt + RING_WINDOW_MS) resolveWindow(s, ctx);
return;
}
const due = (s.pendingFlip !== null && ctx.now >= s.flipAllowedAt) || ctx.now >= Math.max(s.turnDeadline, s.flipAllowedAt);
const due = (s.pendingFlip !== null && ctx.now >= s.flipAllowedAt) || (s.turnDeadline !== null && ctx.now >= Math.max(s.turnDeadline, s.flipAllowedAt));
if (actor === s.turn || due) flipOrQueue(s, s.turn, ctx);
}
@@ -413,7 +421,7 @@ export const halliGalli: GameDefinition<S, A, HalliGalliView, HalliGalliOptions>
officialDuel: false,
turn: first,
turnStartedAt: now,
turnDeadline: countdownEndsAt + flipMs(options),
turnDeadline: deadlineFrom(options, countdownEndsAt),
flipAllowedAt: countdownEndsAt,
pendingFlip: null,
tableVersion: 0,
@@ -544,9 +552,9 @@ export const halliGalli: GameDefinition<S, A, HalliGalliView, HalliGalliOptions>
if (s.ringWindow) c.push(s.ringWindow.openedAt + RING_WINDOW_MS);
else {
if (s.pendingFlip) c.push(s.flipAllowedAt);
c.push(Math.max(s.turnDeadline, s.flipAllowedAt));
if (s.turnDeadline !== null) c.push(Math.max(s.turnDeadline, s.flipAllowedAt));
}
return Math.min(...c);
return c.length ? Math.min(...c) : null;
},
/** Only the turn player's clock drives the server tick (flips, guard, bell window, time limit). */

View File

@@ -35,9 +35,10 @@ export const halliGalliOptionsSchema = z.object({
timeLimitMin: lit<5 | 10 | 15 | null>(5, 10, 15, null)
.default(10)
.meta({ title: '전체 제한 시간', labels: { 5: '5분', 10: '10분', 15: '15분', null: '없음' } }),
flipSeconds: lit<2 | 3 | 5 | 8>(2, 3, 5, 8)
/** null = 무제한: the turn player flips whenever they like (자동 뒤집기 then keeps a 3-second pace, 어린이 모드 8). */
flipSeconds: lit<2 | 3 | 5 | 8 | null>(2, 3, 5, 8, null)
.default(3)
.meta({ title: '뒤집기 제한 시간', labels: { 2: '2초', 3: '3초', 5: '5초', 8: '8초' } }),
.meta({ title: '뒤집기 제한 시간', labels: { 2: '2초', 3: '3초', 5: '5초', 8: '8초', null: '무제한' } }),
autoFlip: z.boolean().default(false).meta({ title: '카드를 자동으로 뒤집기(뒤집기 버튼 없음)' }),
flipGuardMs: lit<400 | 600 | 1000>(400, 600, 1000)
.default(600)
@@ -135,7 +136,8 @@ export interface HalliGalliState {
officialDuel: boolean;
turn: PlayerId;
turnStartedAt: number;
turnDeadline: number;
/** null = 무제한 뒤집기 시간 (nobody flips for the turn player unless they are away). */
turnDeadline: number | null;
flipAllowedAt: number;
pendingFlip: PlayerId | null;
tableVersion: number;
@@ -188,8 +190,8 @@ export interface HalliGalliView {
removed: number;
countdownEndsAt: number;
turnStartedAt: number;
turnDeadline: number;
flipTotalMs: number;
turnDeadline: number | null;
flipTotalMs: number | null;
flipAllowedAt: number;
/** The turn player's flip is queued behind the flip guard / bell window. */
pendingFlip: boolean;