병합: wt2/g4-party
This commit is contained in:
@@ -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('모두 끝냈어요');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import { RoomStore } from './store';
|
||||
type Msgs = ServerMessage[];
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
|
||||
function harness(players: string[]) {
|
||||
function harness(players: string[], options: Record<string, unknown> = {}) {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
@@ -19,7 +19,7 @@ function harness(players: string[]) {
|
||||
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
|
||||
const config: RoomConfig = {
|
||||
gameId: 'catchmind',
|
||||
options: games.catchmind.defaultOptions,
|
||||
options: { ...games.catchmind.defaultOptions, ...options },
|
||||
maxPlayers: players.length,
|
||||
visibility: 'private',
|
||||
allowSpectators: true,
|
||||
@@ -170,12 +170,29 @@ describe('그림 맞히기 room flow', () => {
|
||||
expect(state().away).toEqual([d]);
|
||||
});
|
||||
|
||||
test('그리기 무제한: 연결된 출제자는 타이머 없음, 연결이 끊기면 10초 뒤 턴 종료', () => {
|
||||
const { room, clock, conns, state, act } = harness(['A', 'B'], { drawSeconds: null, hints: 'basic' });
|
||||
const d = state().turn.drawer;
|
||||
act(d, { type: 'chooseWord', index: 0 });
|
||||
expect(state().turn.endsAt).toBeNull();
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
clock.advance(600_000);
|
||||
expect(state().turn.phase).toBe('drawing');
|
||||
room.disconnect(conns[d]!);
|
||||
room.clearTimer();
|
||||
expect(room.effectiveDeadline()).toBe(clock.now() + 10_000);
|
||||
clock.advance(10_000);
|
||||
room.onTimer();
|
||||
room.clearTimer();
|
||||
expect(state().turn.endReason).toBe('drawerAway');
|
||||
});
|
||||
|
||||
test('연결된 출제자는 힌트·시간 만료 때만 tick(10초 지나도 끝나지 않음)', () => {
|
||||
const { room, clock, state, act } = harness(['A', 'B']);
|
||||
const d = state().turn.drawer;
|
||||
act(d, { type: 'chooseWord', index: 0 });
|
||||
const t0 = state().turn.startedAt;
|
||||
const ends = state().turn.endsAt;
|
||||
const ends = state().turn.endsAt!;
|
||||
expect(room.effectiveDeadline()).toBe(t0 + (ends - t0) / 2);
|
||||
clock.advance(20_000);
|
||||
room.onTimer();
|
||||
|
||||
@@ -114,4 +114,17 @@ describe('라이어 게임 room flow with computers', () => {
|
||||
expect(state().descriptions.filter((d) => d.from === 'A').every((d) => d.text === null)).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
|
||||
test('모든 시간 무제한: 컴퓨터는 알아서 하고, 연결이 끊긴 사람은 유예 시간 뒤 넘겨져 끝까지 가요', () => {
|
||||
const { room, conn, run, state, logs } = practice();
|
||||
const none = { describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null };
|
||||
expect(room.configure('A', { options: { ...(room.config.options as object), ...none } })).toBeNull();
|
||||
room.start('A');
|
||||
room.disconnect(conn);
|
||||
run();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(state().options.describeSeconds).toBeNull();
|
||||
expect(state().descriptions.filter((d) => d.from === 'A').every((d) => d.text === null)).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import { openDb } from '../db';
|
||||
import { Room, type Conn, type RoomConfig } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
function harness(players: string[]) {
|
||||
function harness(players: string[], options: Record<string, unknown> = {}) {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
@@ -16,7 +16,7 @@ function harness(players: string[]) {
|
||||
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
|
||||
const config: RoomConfig = {
|
||||
gameId: 'mafia',
|
||||
options: { ...games.mafia.defaultOptions, firstPhase: 'night' },
|
||||
options: { ...games.mafia.defaultOptions, firstPhase: 'night', ...options },
|
||||
maxPlayers: players.length,
|
||||
visibility: 'private',
|
||||
allowSpectators: true,
|
||||
@@ -67,4 +67,23 @@ describe('마피아 room flow', () => {
|
||||
expect(state().phase.kind).toBe('discussion');
|
||||
expect(state().day).toBe(2);
|
||||
});
|
||||
|
||||
test('밤 시간 무제한: 타이머 없이 모두 밤 마치기를 누를 때까지, 연결이 끊긴 사람은 유예 시간 뒤 넘김', () => {
|
||||
const { room, clock, conns, state } = harness(['A', 'B', 'C', 'D'], { nightSeconds: null });
|
||||
expect(room.start('A')).toBeNull();
|
||||
clock.advance(8_000);
|
||||
room.onTimer();
|
||||
expect(state().phase.kind).toBe('night');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
let cs = 10;
|
||||
for (const p of ['A', 'B', 'C']) room.act(p, ++cs, { type: 'readyEarly' });
|
||||
clock.advance(3_600_000);
|
||||
room.onTimer();
|
||||
expect(state().phase.kind).toBe('night');
|
||||
room.disconnect(conns.D!);
|
||||
expect(room.effectiveDeadline()).toBe(clock.now() + 60_000);
|
||||
clock.advance(60_000);
|
||||
room.onTimer();
|
||||
expect(state().phase.kind).toBe('discussion');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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개');
|
||||
});
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
@@ -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>는 취소예요.
|
||||
|
||||
@@ -57,3 +57,13 @@ test('그림 맞히기: 공개 / 끝', () => {
|
||||
s.final = { ranking: [], turns: [], summary: '호랑이님 우승!' };
|
||||
expect(helpNow(view(s, null), null, users)).toContain('호랑이님 우승!');
|
||||
});
|
||||
|
||||
test('그림 맞히기: 그리기 무제한이면 출제자에게 정답 공개 안내', async () => {
|
||||
const { setupGame, usersOf } = await import('../help-kit.test-util');
|
||||
const { GAMES } = await import('@bg/games');
|
||||
const users = usersOf(['A', 'B', 'C']);
|
||||
const { state } = setupGame('catchmind', 3, { drawSeconds: null, wordChoice: false });
|
||||
const d: string = state.turn.drawer;
|
||||
const t = helpNow(GAMES.catchmind!.view(state, d) as never, d, users);
|
||||
expect(t).toContain('[정답 공개하고 넘기기]');
|
||||
});
|
||||
|
||||
@@ -32,7 +32,7 @@ export function helpNow(v: CatchmindView, me: string | null, players: Record<str
|
||||
}
|
||||
const word = v.word ? `그릴 단어는 "${v.word}"예요(나와 맞힌 사람만 보여요). ` : '';
|
||||
const report = v.options.letterReport ? ' 글자를 쓰면 신고를 받아 0점이 될 수 있어요.' : '';
|
||||
return `${word}그림판에 손가락이나 마우스로 그려요. 아래 버튼으로 색, 굵기, 지우개(🧽), 되돌리기(↶), 전체 지우기(🗑)를 쓸 수 있어요.\n글자나 숫자는 쓰지 말고 그림으로만 설명해요.${report}\n그리는 동안 채팅은 못 하고 [거의 다 왔어요]·[비슷해요]·[아니에요] 반응 버튼만 보낼 수 있어요.`;
|
||||
return `${word}그림판에 손가락이나 마우스로 그려요. 아래 버튼으로 색, 굵기, 지우개(🧽), 되돌리기(↶), 전체 지우기(🗑)를 쓸 수 있어요.\n글자나 숫자는 쓰지 말고 그림으로만 설명해요.${report}\n그리는 동안 채팅은 못 하고 [거의 다 왔어요]·[비슷해요]·[아니에요] 반응 버튼만 보낼 수 있어요.${v.endsAt === null ? '\n그리기 시간은 무제한이에요. 아무도 못 맞히면 [정답 공개하고 넘기기]를 두 번 눌러 넘겨요.' : ''}`;
|
||||
}
|
||||
// guesser / solver
|
||||
if (v.phase === 'choosing') return `${turn} · ${drawer}이 그릴 단어를 고르고 있어요. 그림이 시작되면 보고 정답을 입력해요.${v.canChat ? ' 지금은 채팅만 할 수 있어요.' : ''}${away}`;
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { PublicUser, ServerMessage } from '@bg/shared/lite';
|
||||
import { nameHue } from '../../components/ChatMessage';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { useWide } from '../../lib/media';
|
||||
import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
@@ -70,6 +70,23 @@ const CHAT_MAX = 100;
|
||||
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' };
|
||||
|
||||
/** Game sounds on top of the shared palette (site volume applies). */
|
||||
const cmSound = {
|
||||
/** Pencil touching the paper (drawer's own strokes only). */
|
||||
scribble: () => noise(50, 0.05, 0, 'highpass', 4500),
|
||||
/** A hint letter turned over. */
|
||||
hint: () => {
|
||||
tone(880, 70, 'triangle', 0.1);
|
||||
tone(1320, 110, 'triangle', 0.08, 60);
|
||||
},
|
||||
/** Somebody else got it. */
|
||||
otherCorrect: () => tone(1175, 120, 'triangle', 0.1),
|
||||
/** "아까워요!" (only the sender sees it). */
|
||||
close: () => tone(700, 90, 'triangle', 0.1, 0, { slideTo: 600 }),
|
||||
/** The drawer's reaction button (heard by the guessers). */
|
||||
react: () => tone(990, 60, 'sine', 0.08),
|
||||
};
|
||||
|
||||
const CSS = `
|
||||
.cm { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 8px; align-self: center; }
|
||||
.cm-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; justify-content: space-between; font-weight: 700; }
|
||||
@@ -139,6 +156,12 @@ const CSS = `
|
||||
.cm-form { display: flex; gap: 6px; }
|
||||
.cm-form .input { flex: 1; min-height: 48px; font-size: 1.05rem; }
|
||||
.cm-close { color: var(--warning); font-weight: 900; font-size: .95rem; animation: cm-shake .4s ease; }
|
||||
.cm-over { animation: fade .25s ease both; }
|
||||
.cm-over .word { animation: cm-word .5s cubic-bezier(.3,1.6,.5,1) both; animation-delay: .1s; }
|
||||
.cm-hint .ch.flip { animation: anim-flip .42s ease both; }
|
||||
.cm-strip .p .sc, .cm-score strong { display: inline-block; }
|
||||
.cm-unl { font-weight: 800; color: var(--text-sub); font-size: .92rem; }
|
||||
@keyframes cm-word { from { transform: scale(.3) rotate(-6deg); opacity: 0; } }
|
||||
.cm-away { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; background: var(--warning-soft); color: var(--text); border-radius: 12px; padding: 8px 12px; }
|
||||
@keyframes cm-pop { 0% { transform: translate(-50%, -50%) scale(.5); opacity: 0; } 70% { transform: translate(-50%, -50%) scale(1.08); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); } }
|
||||
@keyframes cm-shake { 0%,100% { transform: none; } 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } }
|
||||
@@ -156,7 +179,7 @@ const CSS = `
|
||||
.cm-hint .ch { min-width: 34px; height: 40px; font-size: 1.35rem; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.cm-pop, .cm-close { animation: none; }
|
||||
.cm-pop, .cm-close, .cm-over, .cm-over .word, .cm-hint .ch.flip { animation: none; }
|
||||
.cm-bar i { transition: none; }
|
||||
}
|
||||
`;
|
||||
@@ -507,6 +530,7 @@ function Paper({ v, me, act, players }: { v: CatchmindView; me: string | null; a
|
||||
sender.begin(t.c, t.w, ex, x, y);
|
||||
drawing.apply({ k: 'b', s: sender.stroke, c: t.c, w: t.w, e: ex });
|
||||
drawing.addPoint(x, y);
|
||||
cmSound.scribble();
|
||||
};
|
||||
const onMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
||||
if (active.current !== e.pointerId) return;
|
||||
@@ -606,6 +630,7 @@ function Paper({ v, me, act, players }: { v: CatchmindView; me: string | null; a
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{v.options.drawSeconds === null && <GiveUp act={act} />}
|
||||
{!wide && <span className="small muted">그리는 동안에는 채팅 대신 반응 버튼만 쓸 수 있어요.</span>}
|
||||
</div>
|
||||
)}
|
||||
@@ -613,6 +638,29 @@ function Paper({ v, me, act, players }: { v: CatchmindView; me: string | null; a
|
||||
);
|
||||
}
|
||||
|
||||
/** 무제한 drawings: the drawer may open the answer (press twice). */
|
||||
function GiveUp({ act }: { act: (a: unknown) => void }) {
|
||||
const [ask, setAsk] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!ask) return;
|
||||
const t = setTimeout(() => setAsk(false), 3000);
|
||||
return () => clearTimeout(t);
|
||||
}, [ask]);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${ask ? 'btn-primary' : 'btn-ghost'} btn-sm`}
|
||||
onClick={() => {
|
||||
if (!ask) return setAsk(true);
|
||||
setAsk(false);
|
||||
act({ type: 'giveUp' });
|
||||
}}
|
||||
>
|
||||
{ask ? '한 번 더 누르면 정답을 공개해요' : '🏳 정답 공개하고 넘기기'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const END_TEXT: Record<TurnEndReason, string> = {
|
||||
time: '시간이 다 됐어요',
|
||||
allSolved: '모두 맞혔어요!',
|
||||
@@ -620,6 +668,7 @@ const END_TEXT: Record<TurnEndReason, string> = {
|
||||
report: '글자를 썼다는 신고로 끝났어요(출제자 0점)',
|
||||
drawerAway: '출제자의 연결이 끊겼어요',
|
||||
drawerLeft: '출제자가 나갔어요',
|
||||
giveUp: '출제자가 정답을 공개했어요',
|
||||
};
|
||||
|
||||
function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string | null; act: (a: unknown) => void; players: Record<string, PublicUser>; onSave: () => void }) {
|
||||
@@ -663,7 +712,12 @@ function OverlayMain({ v, act, players, onSave }: { v: CatchmindView; act: (a: u
|
||||
<h2>그릴 단어를 골라 주세요</h2>
|
||||
<div className="cm-choices">
|
||||
{v.choices.map((c, i) => (
|
||||
<button key={c.word} type="button" className="btn btn-primary" onClick={() => act({ type: 'chooseWord', index: i })} aria-label={`${c.word} (${CATEGORY_KO[c.category]})`}>
|
||||
<button
|
||||
key={c.word}
|
||||
type="button"
|
||||
className="btn btn-primary anim-deal"
|
||||
style={{ '--anim-delay': `${i * 90}ms` } as CSSProperties}
|
||||
onClick={() => act({ type: 'chooseWord', index: i })} aria-label={`${c.word} (${CATEGORY_KO[c.category]})`}>
|
||||
<span className="ic" aria-hidden>
|
||||
{CATEGORY_ICON[c.category]}
|
||||
</span>
|
||||
@@ -721,7 +775,7 @@ function HintRow({ v }: { v: CatchmindView }) {
|
||||
{hint ? (
|
||||
<span role="text" aria-label={`힌트: ${hint.filter((c) => c !== ' ').length}글자, ${hint.map((c) => (c === '○' ? '빈칸' : c === ' ' ? '띄어쓰기' : c)).join(' ')}`} style={{ display: 'inline-flex', gap: 6, flexWrap: 'wrap', justifyContent: 'center' }}>
|
||||
{hint.map((c, i) => (
|
||||
<span key={i} className={`ch${c === ' ' ? ' sp' : ''}${c !== '○' && c !== ' ' && !/^[ㄱ-ㅎ]$/.test(c) ? ' open' : ''}`} aria-hidden>
|
||||
<span key={`${i}-${c}`} className={`ch${c === ' ' ? ' sp' : ''}${c !== '○' && c !== ' ' && !/^[ㄱ-ㅎ]$/.test(c) ? ' open' : ''}${c !== '○' && c !== ' ' && v.phase === 'drawing' ? ' flip' : ''}`} aria-hidden>
|
||||
{c === ' ' ? '' : c}
|
||||
</span>
|
||||
))}
|
||||
@@ -736,7 +790,21 @@ function HintRow({ v }: { v: CatchmindView }) {
|
||||
|
||||
function TimeBar({ v }: { v: CatchmindView }) {
|
||||
const now = useServerNow(250);
|
||||
// Ticks in the last 10 seconds of the drawing.
|
||||
const lastSec = v.phase === 'drawing' && v.endsAt !== null ? Math.ceil(Math.max(0, v.endsAt - now) / 1000) : 0;
|
||||
const ticked = useRef(0);
|
||||
useEffect(() => {
|
||||
if (lastSec > 0 && lastSec <= 10 && lastSec !== ticked.current) sfx.tick();
|
||||
ticked.current = lastSec;
|
||||
}, [lastSec]);
|
||||
if (v.phase === 'ended') return null;
|
||||
if (v.endsAt === null || v.phaseMs === null) {
|
||||
return (
|
||||
<div className="cm-unl" role="status">
|
||||
⏱ 그리기 시간 무제한 · {v.options.guessMode === 'multi' ? '모두 맞히거나' : '누가 맞히거나'} 출제자가 정답을 공개할 때까지
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const left = Math.max(0, v.endsAt - now);
|
||||
const frac = Math.min(1, left / Math.max(1, v.phaseMs));
|
||||
const sec = Math.ceil(left / 1000);
|
||||
@@ -777,7 +845,7 @@ function ScoreStrip({ v, me, players }: { v: CatchmindView; me: string | null; p
|
||||
<span className="nm" aria-hidden style={{ fontWeight: id === me ? 900 : 700 }}>
|
||||
{nick(players, id)}
|
||||
</span>
|
||||
<span className="sc" aria-hidden>
|
||||
<span key={v.scores[id] ?? 0} className={`sc${v.scores[id] ? ' anim-bump' : ''}`} aria-hidden>
|
||||
{v.scores[id] ?? 0}점
|
||||
</span>
|
||||
</div>
|
||||
@@ -807,7 +875,7 @@ function ScoreList({ v, me, players }: { v: CatchmindView; me: string | null; pl
|
||||
✓ 맞힘
|
||||
</span>
|
||||
)}
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }} aria-hidden>
|
||||
<strong key={v.scores[id] ?? 0} className={v.scores[id] ? 'anim-bump' : undefined} style={{ fontVariantNumeric: 'tabular-nums' }} aria-hidden>
|
||||
{v.scores[id] ?? 0}점
|
||||
</strong>
|
||||
</li>
|
||||
@@ -917,7 +985,7 @@ function GuessPanel({ v, me, players, act, pending }: { v: CatchmindView; me: st
|
||||
{v.chat.map((m) => {
|
||||
const { cls, body } = chatLine(m, me, players, v.drawer);
|
||||
return (
|
||||
<li key={m.id} className={`cm-line ${cls}${m.from === me ? ' mine' : ''}`} style={{ '--name-h': nameHue(m.from) } as CSSProperties}>
|
||||
<li key={m.id} className={`cm-line ${cls}${m.from === me ? ' mine' : ''} anim-slide-up`} style={{ '--name-h': nameHue(m.from) } as CSSProperties}>
|
||||
{body}
|
||||
</li>
|
||||
);
|
||||
@@ -983,8 +1051,40 @@ function AwayBanner({ v, me, act }: { v: CatchmindView; me: string | null; act:
|
||||
);
|
||||
}
|
||||
|
||||
/** Sounds for what happens on the table (my own "정답!" is played by the overlay). */
|
||||
function useTableSounds(v: CatchmindView, me: string | null): void {
|
||||
const prev = useRef(v);
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
if (p === v) return;
|
||||
const turnChanged = p.turnNo !== v.turnNo;
|
||||
if (turnChanged && v.phase === 'choosing') {
|
||||
if (v.drawer === me) {
|
||||
sounds.myTurn();
|
||||
sfx.deal(v.choices?.length ?? 1);
|
||||
} else sfx.whoosh();
|
||||
}
|
||||
if (v.phase === 'drawing' && (p.phase !== 'drawing' || turnChanged)) sfx.whoosh();
|
||||
if (!turnChanged && v.phase === 'drawing' && v.hintStage > p.hintStage) cmSound.hint();
|
||||
// New chat lines: someone else got it, the drawer reacted, my "아까워요".
|
||||
const seen = p.chat.at(-1)?.id ?? 0;
|
||||
const fresh = v.chat.filter((m) => m.id > seen);
|
||||
if (fresh.some((m) => m.kind === 'correct' && m.from !== me)) cmSound.otherCorrect();
|
||||
if (v.role !== 'drawer' && fresh.some((m) => m.kind === 'reaction')) cmSound.react();
|
||||
if (fresh.some((m) => m.kind === 'close' && m.from === me)) cmSound.close();
|
||||
if (!turnChanged && p.phase === 'drawing' && v.phase === 'reveal') {
|
||||
if (v.endReason === 'report') sfx.alarm();
|
||||
else if (v.endReason === 'allSolved') sfx.fanfare();
|
||||
else if (v.solvers.length === 0) sfx.bad();
|
||||
else sfx.cardFlip();
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
function CatchmindBoard({ view: v, me, players, act, pending }: BoardProps<CatchmindView>) {
|
||||
const wide = useWide();
|
||||
useTableSounds(v, me);
|
||||
return (
|
||||
<div className="cm">
|
||||
<style>{CSS}</style>
|
||||
@@ -1068,7 +1168,7 @@ function statusText(v: CatchmindView, 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]) => (
|
||||
@@ -1137,9 +1237,11 @@ function Options({ value: o, onChange }: OptionsProps<CatchmindOptions>) {
|
||||
[80, '80초'],
|
||||
[100, '100초'],
|
||||
[120, '120초'],
|
||||
[null, '무제한'],
|
||||
]}
|
||||
onChange={(drawSeconds) => set({ drawSeconds })}
|
||||
/>
|
||||
{o.drawSeconds === null && <span className="small muted">맞힐 때까지 그려요. 아무도 못 맞히면 출제자가 [정답 공개하고 넘기기]로 넘겨요. 힌트는 80초 기준으로 나와요.</span>}
|
||||
</Field>
|
||||
<Field label="단어 난이도">
|
||||
<Seg
|
||||
@@ -1212,7 +1314,7 @@ function Options({ value: o, onChange }: OptionsProps<CatchmindOptions>) {
|
||||
function optionsSummary(o: CatchmindOptions): string {
|
||||
const hint = o.hints === 'full' ? '힌트 많이' : o.hints === 'basic' ? '글자 수 힌트' : '힌트 없음';
|
||||
const diff = o.difficulty === 'easy' ? '쉬운 단어' : o.difficulty === 'normal' ? '보통 단어' : '';
|
||||
return [o.guessMode === 'multi' ? '여러 명 맞히기' : '첫 정답자만', `${o.rounds}라운드`, `${o.drawSeconds}초`, hint, diff, o.customOnly ? '추가 단어만' : ''].filter(Boolean).join(' · ');
|
||||
return [o.guessMode === 'multi' ? '여러 명 맞히기' : '첫 정답자만', `${o.rounds}라운드`, o.drawSeconds === null ? '그리기 무제한' : `${o.drawSeconds}초`, hint, diff, o.customOnly ? '추가 단어만' : ''].filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
@@ -1223,7 +1325,7 @@ function Rules({ options }: { options?: CatchmindOptions }) {
|
||||
<div className="stack">
|
||||
<p>
|
||||
한 사람(출제자)이 제시어를 <strong>그림으로</strong> 그리고, 나머지는 그림을 보며 <strong>채팅으로 정답</strong>을 맞혀요. 차례대로 돌아가며 모두 한 번씩 그리면 1라운드예요
|
||||
{o ? `(이 방은 ${o.rounds}라운드, 그리기 ${o.drawSeconds}초)` : ''}.
|
||||
{o ? `(이 방은 ${o.rounds}라운드, 그리기 ${o.drawSeconds === null ? '시간 무제한' : `${o.drawSeconds}초`})` : ''}.
|
||||
</p>
|
||||
<p>
|
||||
출제자는 단어 3개 중 하나를 10초 안에 골라요. 그리는 동안에는 글자를 쓰면 안 되고, 채팅 대신 "거의 다 왔어요" 같은 반응 버튼만 쓸 수 있어요. 글자를 쓰면 맞히는 사람들이 신고할 수 있어요.
|
||||
@@ -1234,7 +1336,10 @@ function Rules({ options }: { options?: CatchmindOptions }) {
|
||||
: '먼저 맞힐수록 점수가 커요: 10점, 8점, 6점, 그다음부터 4점. 출제자는 맞힌 사람 1명마다 2점(최대 12점)을 받아요.'}{' '}
|
||||
띄어쓰기·문장부호는 무시하고, "사과요"처럼 끝에 붙인 말도 정답으로 봐요. 거의 맞히면 나에게만 "아까워요!"가 떠요.
|
||||
</p>
|
||||
<p>시간이 지나면 힌트가 나와요: 처음엔 글자 수, 절반이 지나면 초성, 3/4이 지나면 한 글자. 점수가 같으면 많이 맞힌 사람이 앞서요.</p>
|
||||
<p>
|
||||
시간이 지나면 힌트가 나와요: 처음엔 글자 수, 절반이 지나면 초성, 3/4이 지나면 한 글자.{' '}
|
||||
{o?.drawSeconds === null ? '그리기 시간이 무제한이면 40초에 초성, 60초에 한 글자가 나오고, 아무도 못 맞히면 출제자가 정답을 공개하고 넘길 수 있어요. ' : ''}점수가 같으면 많이 맞힌 사람이 앞서요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** 클루 화면 (docs/games/clue.md §9). */
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
|
||||
import type { ClueOptions, ClueView, SuggestionView } from '@bg/games/clue';
|
||||
import {
|
||||
PASSAGES,
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
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, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -55,12 +55,29 @@ const ro = (word: string) => {
|
||||
};
|
||||
const lastOf = <T,>(xs: readonly T[]): T | undefined => xs[xs.length - 1];
|
||||
|
||||
/** Clock length for the timer ring (무제한 has no deadline, so the ring only shows for away players' grace). */
|
||||
function totalMsOf(v: ClueView): number {
|
||||
if (v.phase.kind === 'refute') return 20_000;
|
||||
if ((v.idle[v.current] ?? 0) >= 3) return 10_000;
|
||||
return v.options.turnSeconds * 1000;
|
||||
return (v.options.turnSeconds ?? 60) * 1000;
|
||||
}
|
||||
|
||||
/** Game sounds on top of the shared palette (site volume applies). */
|
||||
const clSound = {
|
||||
/** "그건 바로…!" a suggestion is made: a low questioning motif. */
|
||||
suggest: () => [330, 392, 466].forEach((f, i) => tone(f, 150, 'triangle', 0.1, i * 110)),
|
||||
/** Nobody could show a card: a suspenseful low "dun-dun". */
|
||||
noneShown: () => {
|
||||
tone(196, 260, 'sawtooth', 0.05);
|
||||
tone(185, 420, 'sawtooth', 0.05, 280);
|
||||
},
|
||||
/** Walking a few squares in the hallway. */
|
||||
steps: (n: number) => {
|
||||
for (let i = 0; i < Math.min(4, n); i++) tone(i % 2 ? 520 : 440, 45, 'triangle', 0.09, i * 120);
|
||||
},
|
||||
};
|
||||
const posKey = (p: Pos) => JSON.stringify(p);
|
||||
|
||||
/** The player the game waits on (refuter while a card is being chosen). */
|
||||
const waitingOn = (v: ClueView): string => (v.phase.kind === 'refute' ? v.phase.refuter : v.current);
|
||||
|
||||
@@ -81,7 +98,7 @@ function knownCards(v: ClueView): Map<Item, string> {
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.cl-board { width: 100%; max-width: 1040px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; }
|
||||
.cl-board { position: relative; width: 100%; max-width: 1040px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; }
|
||||
.cl-top { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); gap: 12px; align-items: start; }
|
||||
.cl-map { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-rows: repeat(4, minmax(84px, auto));
|
||||
grid-template-areas: "k b c" "d m bi" "d m li" "lo h s"; gap: 6px; background: var(--wood); padding: 8px; border-radius: var(--radius-lg); box-shadow: var(--shadow); }
|
||||
@@ -133,7 +150,15 @@ button.cl-room:disabled { cursor: default; }
|
||||
button.cl-card { cursor: pointer; font: inherit; font-weight: 800; font-size: .8rem; }
|
||||
button.cl-card:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
button.cl-card.can { box-shadow: 0 0 0 3px var(--primary); }
|
||||
.cl-card.new { animation: cl-pop .6s ease-out; }
|
||||
.cl-card.new { animation: cl-pop .6s ease-out; animation-delay: var(--anim-delay, 0ms); animation-fill-mode: both; }
|
||||
.cl-dice span { display: inline-block; }
|
||||
.cl-room.landed { animation: cl-land .7s ease-out; }
|
||||
.cl-banner { position: absolute; left: 50%; top: 30%; translate: -50% 0; z-index: 8; pointer-events: none; border-radius: 18px; padding: 12px 22px; font-weight: 900; font-size: 1.35rem;
|
||||
background: var(--surface); box-shadow: 0 10px 30px rgba(0,0,0,.35); text-align: center; white-space: nowrap; max-width: 92vw; overflow: hidden; text-overflow: ellipsis; }
|
||||
.cl-banner.ok { border: 4px solid var(--success); color: var(--success); }
|
||||
.cl-banner.bad { border: 4px solid var(--danger); color: var(--danger); }
|
||||
.cl-banner.info { border: 4px solid var(--primary); color: var(--text); }
|
||||
@keyframes cl-land { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--focus) 80%, transparent); } 100% { box-shadow: 0 0 0 12px transparent; } }
|
||||
@keyframes cl-pop { 0% { transform: scale(.6) rotate(-8deg); opacity: .2; } 100% { transform: none; opacity: 1; } }
|
||||
.cl-sec { background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.cl-note { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
|
||||
@@ -166,20 +191,20 @@ button.cl-card.can { box-shadow: 0 0 0 3px var(--primary); }
|
||||
.cl-note { grid-template-columns: minmax(0, 1fr); }
|
||||
.cl-card { width: 66px; min-height: 78px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .cl-card.new { animation: none; } }
|
||||
@media (prefers-reduced-motion: reduce) { .cl-card.new, .cl-room.landed { animation: none; } }
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- small pieces
|
||||
|
||||
function Token({ x, me }: { x: Suspect; me?: boolean }) {
|
||||
function Token({ x, me, pop }: { x: Suspect; me?: boolean; pop?: boolean }) {
|
||||
return (
|
||||
<span className={`cl-tok${x === 'white' ? ' light' : ''}${me ? ' me' : ''}`} style={{ background: SUSPECT_COLOR[x] }} title={SUSPECT_KO[x]} aria-hidden>
|
||||
<span className={`cl-tok${x === 'white' ? ' light' : ''}${me ? ' me' : ''}${pop ? ' anim-pop' : ''}`} style={{ background: SUSPECT_COLOR[x] }} title={SUSPECT_KO[x]} aria-hidden>
|
||||
{SUSPECT_SHORT[x]}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Card({ id, onClick, can, fresh, label }: { id: string; onClick?: () => void; can?: boolean; fresh?: boolean; label?: string }) {
|
||||
function Card({ id, onClick, can, fresh, label, delay }: { id: string; onClick?: () => void; can?: boolean; fresh?: boolean; label?: string; delay?: number }) {
|
||||
const x = itemOf(id);
|
||||
const cat = categoryOf(x);
|
||||
const body = (
|
||||
@@ -199,7 +224,7 @@ function Card({ id, onClick, can, fresh, label }: { id: string; onClick?: () =>
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<span className={`cl-card${fresh ? ' new' : ''}`} role="img" aria-label={aria}>
|
||||
<span className={`cl-card${fresh ? ' new' : ''}`} role="img" aria-label={aria} style={delay ? ({ '--anim-delay': `${delay}ms` } as CSSProperties) : undefined}>
|
||||
{body}
|
||||
</span>
|
||||
);
|
||||
@@ -214,9 +239,67 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const prevTurn = useRef(`${v.current}|${v.turnNo}`);
|
||||
const prevSg = useRef(JSON.stringify(lastOf(v.suggestions) ?? null));
|
||||
const prevView = useRef(v);
|
||||
const [banner, setBanner] = useState<{ key: string; kind: 'ok' | 'bad' | 'info'; text: string } | null>(null);
|
||||
const [landed, setLanded] = useState<{ room: Room; key: number } | null>(null);
|
||||
|
||||
useEffect(() => setSel(null), [v.phase.kind, v.current, v.turnNo]);
|
||||
|
||||
// Sounds and highlights for what anyone just did: dice, moves, passages, suggestions, answers, accusations.
|
||||
useEffect(() => {
|
||||
const p = prevView.current;
|
||||
prevView.current = v;
|
||||
if (p === v) return;
|
||||
if (v.dice && (!p.dice || p.turnNo !== v.turnNo || p.dice[0] !== v.dice[0] || p.dice[1] !== v.dice[1])) sfx.dice();
|
||||
const mover = v.suspectOf[v.current];
|
||||
let moved = false;
|
||||
for (const x of SUSPECTS) {
|
||||
if (posKey(v.pos[x]) === posKey(p.pos[x])) continue;
|
||||
moved = true;
|
||||
const r = roomAt(v.pos[x]);
|
||||
if (r && x === mover) setLanded({ room: r, key: Date.now() });
|
||||
}
|
||||
const sgNew = v.suggestions.length > p.suggestions.length;
|
||||
if (moved && !sgNew && mover) {
|
||||
const from = roomAt(p.pos[mover]);
|
||||
const to = roomAt(v.pos[mover]);
|
||||
if (from && to && PASSAGES[from] === to && !v.dice) sfx.whoosh();
|
||||
else if (to) sfx.piece();
|
||||
else clSound.steps(v.dice ? v.dice[0] + v.dice[1] : 3);
|
||||
}
|
||||
if (sgNew) clSound.suggest();
|
||||
const lastNow = lastOf(v.suggestions);
|
||||
const lastPrev = lastOf(p.suggestions);
|
||||
if (lastNow && !sgNew && lastPrev && v.suggestions.length === p.suggestions.length && !lastPrev.refuter && lastNow.refuter) {
|
||||
if (lastNow.shown && (lastNow.by === me || lastNow.refuter === me)) sfx.cardFlip();
|
||||
else sfx.cardDeal();
|
||||
}
|
||||
if (lastNow && p.phase.kind === 'refute' && v.phase.kind !== 'refute' && !lastNow.refuter) clSound.noneShown();
|
||||
if (lastNow && sgNew && v.phase.kind === 'afterSuggest' && !lastNow.refuter) clSound.noneShown();
|
||||
if (v.accusations.length > p.accusations.length) {
|
||||
const a = v.accusations[v.accusations.length - 1]!;
|
||||
const who = a.by === me ? '내' : `${nick(players, a.by)}님의`;
|
||||
if (a.correct) {
|
||||
// The game ends here: the room plays win / lose.
|
||||
setBanner({ key: `a${v.accusations.length}`, kind: 'ok', text: `⚖️ ${who} 고발이 맞았어요!` });
|
||||
} else {
|
||||
sfx.bad();
|
||||
setBanner({ key: `a${v.accusations.length}`, kind: 'bad', text: `⚖️ ${who} 고발이 틀렸어요 · 탈락` });
|
||||
}
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!banner) return;
|
||||
const t = setTimeout(() => setBanner(null), 1700);
|
||||
return () => clearTimeout(t);
|
||||
}, [banner]);
|
||||
useEffect(() => {
|
||||
if (!landed) return;
|
||||
const t = setTimeout(() => setLanded(null), 800);
|
||||
return () => clearTimeout(t);
|
||||
}, [landed]);
|
||||
|
||||
useEffect(() => {
|
||||
const key = `${v.current}|${v.turnNo}`;
|
||||
if (key !== prevTurn.current && v.phase.kind !== 'finished') {
|
||||
@@ -250,11 +333,16 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
<div className="cl-board" role="region" aria-label="클루 판">
|
||||
<style>{CSS}</style>
|
||||
<div className="cl-top">
|
||||
<Mansion view={v} me={me} myTurn={myTurn && !pending} sel={sel} setSel={setSel} />
|
||||
<Mansion view={v} me={me} myTurn={myTurn && !pending} sel={sel} setSel={setSel} landed={landed?.room ?? null} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} setSel={setSel} />
|
||||
</div>
|
||||
{amPlayer && <MyCards view={v} me={me!} />}
|
||||
{amPlayer && <Notebook view={v} me={me!} players={players} />}
|
||||
{banner && (
|
||||
<div key={banner.key} className={`cl-banner anim-banner ${banner.kind}`} aria-hidden>
|
||||
{banner.text}
|
||||
</div>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -262,7 +350,21 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
);
|
||||
}
|
||||
|
||||
function Mansion({ view: v, me, myTurn, sel, setSel }: { view: ClueView; me: string | null; myTurn: boolean; sel: Room | null; setSel: (r: Room | null) => void }) {
|
||||
function Mansion({
|
||||
view: v,
|
||||
me,
|
||||
myTurn,
|
||||
sel,
|
||||
setSel,
|
||||
landed,
|
||||
}: {
|
||||
view: ClueView;
|
||||
me: string | null;
|
||||
myTurn: boolean;
|
||||
sel: Room | null;
|
||||
setSel: (r: Room | null) => void;
|
||||
landed: Room | null;
|
||||
}) {
|
||||
const mySuspect = me ? v.suspectOf[me] : undefined;
|
||||
const myPos = mySuspect ? v.pos[mySuspect] : null;
|
||||
const here = myPos ? roomAt(myPos) : null;
|
||||
@@ -282,7 +384,7 @@ function Mansion({ view: v, me, myTurn, sel, setSel }: { view: ClueView; me: str
|
||||
const can = picking && r !== here;
|
||||
const reach = can && (free || (d !== undefined && d <= sum));
|
||||
const pass = PASSAGES[r];
|
||||
const cls = ['cl-room', can ? (reach ? 'reach' : 'far') : '', sel === r ? 'sel' : '', r === here ? 'here' : ''].filter(Boolean).join(' ');
|
||||
const cls = ['cl-room', can ? (reach ? 'reach' : 'far') : '', sel === r ? 'sel' : '', r === here ? 'here' : '', landed === r ? 'landed' : ''].filter(Boolean).join(' ');
|
||||
const label = [
|
||||
ROOM_KO[r],
|
||||
r === here ? '내가 있는 방' : '',
|
||||
@@ -302,10 +404,10 @@ function Mansion({ view: v, me, myTurn, sel, setSel }: { view: ClueView; me: str
|
||||
{can && !free && d !== undefined && <span className="cl-dist">{d}칸</span>}
|
||||
<span className="cl-things">
|
||||
{toks.map((x) => (
|
||||
<Token key={x} x={x} me={x === mySuspect} />
|
||||
<Token key={x} x={x} me={x === mySuspect} pop />
|
||||
))}
|
||||
{weaps.map((w) => (
|
||||
<span key={w} className="cl-weap" title={WEAPON_KO[w]} aria-hidden>
|
||||
<span key={w} className="cl-weap anim-pop" title={WEAPON_KO[w]} aria-hidden>
|
||||
{WEAPON_ICON[w]}
|
||||
</span>
|
||||
))}
|
||||
@@ -337,7 +439,7 @@ function Mansion({ view: v, me, myTurn, sel, setSel }: { view: ClueView; me: str
|
||||
const p = owner(x);
|
||||
return (
|
||||
<li key={x} style={p ? undefined : { opacity: 0.6 }} aria-label={`${SUSPECT_KO[x]}${p ? '' : '(맡은 사람 없음)'}: ${hallwayText(v.pos[x])}`}>
|
||||
<Token x={x} me={x === mySuspect} />
|
||||
<Token key={posKey(v.pos[x])} x={x} me={x === mySuspect} pop />
|
||||
<span aria-hidden>{hallwayText(v.pos[x])}</span>
|
||||
</li>
|
||||
);
|
||||
@@ -500,8 +602,8 @@ function ActionPanel({
|
||||
<span>{v.final?.summary}</span>
|
||||
{v.solution && (
|
||||
<div className="cl-cards" aria-label="사건 봉투 속 정답">
|
||||
{[v.solution.suspect, v.solution.weapon, v.solution.room].map((x) => (
|
||||
<Card key={x} id={`card-${x}`} fresh />
|
||||
{[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => (
|
||||
<Card key={x} id={`card-${x}`} fresh delay={i * 250} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
@@ -517,7 +619,7 @@ function ActionPanel({
|
||||
<strong>
|
||||
{nick(players, sg.by)}님이 {ro(triple(sg))} 추리했어요
|
||||
</strong>
|
||||
<span className="small muted">내 카드 중 하나를 골라 {nick(players, sg.by)}님에게만 보여 줘요. 다른 사람은 내가 보여 줬다는 것만 알아요. 20초 안에 안 고르면 자동으로 보여 줘요.</span>
|
||||
<span className="small muted">내 카드 중 하나를 골라 {nick(players, sg.by)}님에게만 보여 줘요. 다른 사람은 내가 보여 줬다는 것만 알아요.{v.options.turnSeconds === null ? '' : ' 20초 안에 안 고르면 자동으로 보여 줘요.'}</span>
|
||||
<div className="cl-cards">
|
||||
{(ph.canShow ?? []).map((c) => (
|
||||
<Card key={c} id={c} can onClick={() => !pending && act({ type: 'show', card: c })} label={`${ITEM_KO[itemOf(c)]} 카드 보여 주기`} />
|
||||
@@ -616,8 +718,12 @@ function ActionPanel({
|
||||
<div className="cl-panel">
|
||||
{v.dice && (
|
||||
<div className="cl-dice" role="img" aria-label={`주사위 ${v.dice[0]}과 ${v.dice[1]}, 합 ${sum}`}>
|
||||
<span aria-hidden>{DICE[v.dice[0]]}</span>
|
||||
<span aria-hidden>{DICE[v.dice[1]]}</span>
|
||||
<span key={`a${v.turnNo}-${v.dice[0]}`} className="anim-roll" aria-hidden>
|
||||
{DICE[v.dice[0]]}
|
||||
</span>
|
||||
<span key={`b${v.turnNo}-${v.dice[1]}`} className="anim-roll" style={{ animationDelay: '80ms' }} aria-hidden>
|
||||
{DICE[v.dice[1]]}
|
||||
</span>
|
||||
<b aria-hidden>= {sum}칸</b>
|
||||
</div>
|
||||
)}
|
||||
@@ -876,7 +982,7 @@ function statusText(v: ClueView, me: string | null, players: Record<string, Publ
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
function Seg<T extends string | number | 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]) => (
|
||||
@@ -914,16 +1020,18 @@ function Options({ value: o, onChange }: OptionsProps<ClueOptions>) {
|
||||
[45, '45초'],
|
||||
[60, '60초'],
|
||||
[90, '90초'],
|
||||
[null, '무제한'],
|
||||
]}
|
||||
onChange={(turnSeconds) => set({ turnSeconds })}
|
||||
/>
|
||||
{o.turnSeconds === null && <span className="small muted">차례와 카드 보여 주기에 시간 제한이 없어요. 연결이 끊긴 채 돌아오지 않는 사람만 자동으로 넘겨요.</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: ClueOptions): string {
|
||||
return [o.movement === 'free' ? '빠른 이동' : '주사위 이동', `차례 ${o.turnSeconds}초`].join(' · ');
|
||||
return [o.movement === 'free' ? '빠른 이동' : '주사위 이동', o.turnSeconds === null ? '차례 시간 무제한' : `차례 ${o.turnSeconds}초`].join(' · ');
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: ClueOptions }) {
|
||||
@@ -956,7 +1064,10 @@ function Rules({ options }: { options?: ClueOptions }) {
|
||||
<strong>추리 노트</strong>: 화면 아래 노트에 내 카드, 공개 카드, 나에게 보여 준 카드가 자동으로 ✗ 표시돼요. 나머지는 직접 눌러 ✗·?·✓를 적어 두세요(이 기기에만 저장돼요).
|
||||
</p>
|
||||
<p className="muted">
|
||||
차례 시간이 지나면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요. 카드를 보여 줄 때는 20초 안에 고르지 않으면 맞는 카드가 자동으로 보여져요. 게임 중에 나간 사람의 카드는 모두에게 공개돼요.
|
||||
{options?.turnSeconds === null
|
||||
? '이 방은 차례 시간이 무제한이에요. 연결이 끊긴 채 돌아오지 않으면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요(카드 보여 주기는 맞는 카드가 자동으로).'
|
||||
: '차례 시간이 지나면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요. 카드를 보여 줄 때는 20초 안에 고르지 않으면 맞는 카드가 자동으로 보여져요.'}{' '}
|
||||
게임 중에 나간 사람의 카드는 모두에게 공개돼요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
)}
|
||||
|
||||
@@ -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)}님이 뒤집을 차례예요. 차례가 아니어도 종은 언제든 누를 수 있어요.`);
|
||||
|
||||
@@ -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}>
|
||||
|
||||
@@ -47,3 +47,10 @@ test('라이어 게임: 설명 차례, 투표, 정답 맞히기', () => {
|
||||
expect(helpNow(view(s, 'D'), 'D', users)).toContain('[정답!]');
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain(`${users.D!.nickname}님이 라이어였어요`);
|
||||
});
|
||||
|
||||
test('라이어 게임: 시간 무제한이면 "시간 제한은 없어요" 안내', () => {
|
||||
const s = tick(game({ describeSeconds: null, discussionSeconds: null }));
|
||||
const t = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(t).toContain('시간 제한은 없어요');
|
||||
expect(t).not.toContain('시간이 지나면 넘어가요');
|
||||
});
|
||||
|
||||
@@ -35,29 +35,30 @@ export function helpNow(v: LiarView, me: string | null, players: Record<string,
|
||||
if (v.players.find((p) => p.id === me)?.left) return '게임에서 나갔어요. 남은 사람들이 계속해요.';
|
||||
const liar = my.role === 'liar';
|
||||
const mine = liar ? `나는 라이어예요. 제시어는 모르고 주제만 알아요.` : `내 제시어는 위의 [내 제시어] 카드를 꾹 누르면 보여요.`;
|
||||
const unl = ph.endsAt === null;
|
||||
switch (ph.kind) {
|
||||
case 'reveal':
|
||||
return `${topic} ${mine}\n확인했으면 [확인했어요]를 눌러요. 모두 누르면 바로 설명이 시작돼요(${ph.readyCount}/${ph.readyNeeded}).\n${WIN}`;
|
||||
case 'describe': {
|
||||
if (my.canDescribe) {
|
||||
const tip = liar ? '앞사람 설명을 듣고 아는 척해요. 너무 구체적으로 말하면 틀릴 수 있어요.' : '제시어를 직접 말하면 안 돼요. 라이어가 알아채지 못하게 애매하게, 시민은 알아듣게 말해요.';
|
||||
return `${topic} 내 차례예요! 오른쪽 칸에 한 문장(80자까지)으로 설명하고 [말하기]를 눌러요.\n${tip} 시간이 지나면 넘어가요.`;
|
||||
return `${topic} 내 차례예요! 오른쪽 칸에 한 문장(80자까지)으로 설명하고 [말하기]를 눌러요.\n${tip} ${unl ? '시간 제한은 없어요.' : '시간이 지나면 넘어가요.'}`;
|
||||
}
|
||||
const round = v.rounds > 1 ? ` ${ph.round}/${v.rounds}바퀴예요${ph.round === 2 ? '(두 번째 바퀴는 거꾸로 돌아요)' : ''}.` : '';
|
||||
return `${topic} ${ph.speaker ? josa(n(ph.speaker), ['이', '가']) : '다른 사람이'} 설명하는 중이에요.${round}\n설명 기록을 잘 보고 어색한 사람을 기억해 둬요. ${mine}`;
|
||||
}
|
||||
case 'discussion':
|
||||
return `${topic} 자유 토론 시간이에요. [토론 채팅]으로 누가 라이어 같은지 이야기해요. 제시어는 직접 말할 수 없어요.\n다 이야기했으면 [토론 끝내기]를 눌러요. 모두 누르면 바로 투표로 넘어가요(${ph.readyCount}/${ph.readyNeeded}).`;
|
||||
return `${topic} 자유 토론 시간이에요. [토론 채팅]으로 누가 라이어 같은지 이야기해요. 제시어는 직접 말할 수 없어요.\n${unl ? '토론 시간은 무제한이에요. ' : ''}다 이야기했으면 [토론 끝내기]를 눌러요. 모두 누르면 바로 투표로 넘어가요(${ph.readyCount}/${ph.readyNeeded}).`;
|
||||
case 'vote': {
|
||||
if (!my.voteTargets.length) return `${topic} 동점인 사람끼리 다시 투표하고 있어요. 결과를 기다려 주세요.`;
|
||||
const now = my.vote ? `지금 ${josa(n(my.vote), ['을', '를'])} 골랐어요. 시간 안에는 바꿀 수 있어요.` : '아직 고르지 않았어요.';
|
||||
const now = my.vote ? `지금 ${josa(n(my.vote), ['을', '를'])} 골랐어요. ${unl ? '모두 투표하기 전에는' : '시간 안에는'} 바꿀 수 있어요.` : '아직 고르지 않았어요.';
|
||||
const tie = ph.voteRound === 2 ? '또 동점이면 라이어가 이겨요.' : '동점이면 동점인 사람끼리 한 번 더 투표해요.';
|
||||
return `${topic} '사람들'에서 초록 테두리 사람을 눌러 라이어로 의심되는 사람을 골라요.\n${now} 표가 가장 많은 한 명이 지목돼요. ${tie}`;
|
||||
}
|
||||
case 'guess':
|
||||
if (my.canGuess) {
|
||||
const how = v.options.guessMode === 'choice' ? '목록에서 단어 하나를 눌러요.' : '입력칸에 제시어를 적고 [정답!]을 눌러요. 띄어쓰기는 상관없어요.';
|
||||
return `${topic} 들켰어요! 제시어를 맞히면 그래도 라이어가 이겨요. ${how} 기회는 한 번이에요.`;
|
||||
return `${topic} 들켰어요! 제시어를 맞히면 그래도 라이어가 이겨요. ${how} 기회는 한 번이에요.${unl ? ' 시간 제한은 없어요.' : ''}`;
|
||||
}
|
||||
return `${topic} ${ph.liar ? josa(n(ph.liar), ['이', '가']) : '지목된 사람이'} 라이어였어요! 라이어가 제시어를 맞히는 중이에요. 못 맞히면 시민이 이겨요.`;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { TOPIC_IDS, TOPIC_KO } from '@bg/games/liar/topics';
|
||||
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 { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
|
||||
@@ -127,6 +127,12 @@ button.lg-tile { cursor: pointer; }
|
||||
.lg-final .word { font-size: 1.3rem; font-weight: 900; }
|
||||
.lg-log { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 3px; max-height: 320px; overflow: auto; }
|
||||
@keyframes lg-pop { from { transform: scale(.96); opacity: 0; } to { transform: none; opacity: 1; } }
|
||||
.lg-unl { font-size: 1.6rem; }
|
||||
.lg-unl small { display: block; font-size: .7rem; font-weight: 800; }
|
||||
.lg-tile[aria-pressed='true'] { animation: lg-pick .28s ease-out; }
|
||||
.lg-tile.accused { animation: anim-shake .45s ease both; }
|
||||
@keyframes lg-pick { 50% { transform: scale(1.07); } }
|
||||
.lg-card[data-show='true'] { animation: anim-flip .35s ease both; }
|
||||
@keyframes lg-grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }
|
||||
@media (max-width: 1099px) {
|
||||
.lg { height: auto; }
|
||||
@@ -145,14 +151,20 @@ button.lg-tile { cursor: pointer; }
|
||||
.lg-msgs { min-height: 160px; max-height: 300px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.lg-news, .lg-bar .tr i { animation: none; }
|
||||
.lg-news, .lg-bar .tr i, .lg-tile[aria-pressed='true'], .lg-tile.accused, .lg-card[data-show='true'] { animation: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- small parts
|
||||
|
||||
function Clock({ endsAt }: { endsAt: number | null }) {
|
||||
function Clock({ endsAt, unlimited }: { endsAt: number | null; unlimited: boolean }) {
|
||||
const now = useServerNow(500);
|
||||
if (unlimited)
|
||||
return (
|
||||
<span className="lg-clock lg-unl" role="timer" aria-label="시간 제한 없음">
|
||||
∞<small>무제한</small>
|
||||
</span>
|
||||
);
|
||||
if (endsAt === null) return null;
|
||||
const sec = Math.max(0, Math.ceil((endsAt - now) / 1000));
|
||||
const text = sec >= 60 ? `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}` : `${sec}`;
|
||||
@@ -225,7 +237,7 @@ function eventText(e: PublicEvent, players: Record<string, PublicUser>): string
|
||||
case 'accused':
|
||||
return e.liar ? `${josa(n(e.p), ['은', '는'])} 라이어가 맞아요!` : `${josa(n(e.p), ['은', '는'])} 라이어가 아니었어요`;
|
||||
case 'guess':
|
||||
return e.text === null ? '라이어가 시간 안에 답하지 못했어요' : `라이어의 답: "${e.text}" — ${e.correct ? '정답!' : '틀렸어요'}`;
|
||||
return e.text === null ? '라이어가 답하지 못했어요' : `라이어의 답: "${e.text}" — ${e.correct ? '정답!' : '틀렸어요'}`;
|
||||
case 'left':
|
||||
return `${josa(n(e.p), ['이', '가'])} 게임을 나갔어요`;
|
||||
case 'end':
|
||||
@@ -322,8 +334,8 @@ function Players({ v, players, me, pick, pending }: { v: LiarView; players: Reco
|
||||
{id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
{speaking && <span className="lg-tag say">말하는 중</span>}
|
||||
{ph.kind === 'vote' && p.voted && <span className="lg-tag ok">투표함</span>}
|
||||
{p.liar === true && <span className="lg-tag liar">🤥 라이어</span>}
|
||||
{ph.kind === 'vote' && p.voted && <span className="lg-tag ok anim-pop">투표함</span>}
|
||||
{p.liar === true && <span className="lg-tag liar anim-pop">🤥 라이어</span>}
|
||||
{p.left && <span className="lg-tag">나감</span>}
|
||||
</>
|
||||
);
|
||||
@@ -372,9 +384,9 @@ function Descriptions({ v, players, me }: { v: LiarView; players: Record<string,
|
||||
{v.descriptions
|
||||
.filter((d) => d.round === r)
|
||||
.map((d) => (
|
||||
<li key={d.n} className={`${d.from === me ? 'mine' : ''}${d.text === null ? ' skip' : ''}`} style={{ '--name-h': nameHue(d.from) } as CSSProperties}>
|
||||
<li key={d.n} className={`${d.from === me ? 'mine' : ''}${d.text === null ? ' skip' : ''} anim-slide-up`} style={{ '--name-h': nameHue(d.from) } as CSSProperties}>
|
||||
<strong>{nick(players, d.from)}</strong>
|
||||
{d.text ?? '(시간이 지나 넘어갔어요)'}
|
||||
{d.text ?? (v.options.describeSeconds === null ? '(자리를 비워 넘어갔어요)' : '(시간이 지나 넘어갔어요)')}
|
||||
</li>
|
||||
))}
|
||||
{v.phase.kind === 'describe' && v.phase.round === r && v.phase.speaker && (
|
||||
@@ -540,7 +552,10 @@ function Actions({ v, players, me, act, pending }: { v: LiarView; players: Recor
|
||||
body = my.canDescribe ? (
|
||||
<>
|
||||
<p className="lg-prompt">내 차례예요! 한 문장으로 설명해 주세요</p>
|
||||
<span className="small">{my.role === 'liar' ? '제시어를 모르니 앞사람 말을 잘 듣고 아는 척해요.' : '제시어는 직접 말할 수 없어요. 너무 쉬우면 라이어가 알아채요.'}</span>
|
||||
<span className="small">
|
||||
{my.role === 'liar' ? '제시어를 모르니 앞사람 말을 잘 듣고 아는 척해요.' : '제시어는 직접 말할 수 없어요. 너무 쉬우면 라이어가 알아채요.'}
|
||||
{ph.endsAt === null ? ' 시간 제한은 없어요.' : ''}
|
||||
</span>
|
||||
<DescribeForm key={`${ph.round}-${ph.turn}`} act={act} pending={pending} />
|
||||
</>
|
||||
) : (
|
||||
@@ -562,7 +577,7 @@ function Actions({ v, players, me, act, pending }: { v: LiarView; players: Recor
|
||||
{my.ready ? `기다리는 중 (${ph.readyCount}/${ph.readyNeeded})` : `토론 끝내기 (${ph.readyCount}/${ph.readyNeeded})`}
|
||||
</button>
|
||||
</div>
|
||||
<span className="small muted">모두 누르면 바로 투표로 넘어가요.</span>
|
||||
<span className="small muted">{ph.endsAt === null ? '토론 시간이 무제한이에요. ' : ''}모두 누르면 바로 투표로 넘어가요.</span>
|
||||
</>
|
||||
);
|
||||
} else if (ph.kind === 'vote') {
|
||||
@@ -583,7 +598,10 @@ function Actions({ v, players, me, act, pending }: { v: LiarView; players: Recor
|
||||
body = my.canGuess ? (
|
||||
<>
|
||||
<p className="lg-prompt">들켰어요! 제시어를 맞히면 그래도 이겨요</p>
|
||||
<span className="small">주제는 {v.topicKo}이에요. {v.options.guessMode === 'choice' ? '목록에서 하나를 골라요. 기회는 한 번이에요.' : '띄어쓰기는 상관없어요. 기회는 한 번이에요.'}</span>
|
||||
<span className="small">
|
||||
주제는 {v.topicKo}이에요. {v.options.guessMode === 'choice' ? '목록에서 하나를 골라요. 기회는 한 번이에요.' : '띄어쓰기는 상관없어요. 기회는 한 번이에요.'}
|
||||
{ph.endsAt === null ? ' 시간 제한은 없어요.' : ''}
|
||||
</span>
|
||||
<GuessForm v={v} act={act} pending={pending} />
|
||||
</>
|
||||
) : (
|
||||
@@ -651,6 +669,36 @@ function FinalReveal({ v, players }: { v: LiarView; players: Record<string, Publ
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
/** Game sounds on top of the shared palette (site volume applies). */
|
||||
const lgSound = {
|
||||
/** Someone else's description lands. */
|
||||
said: () => tone(660, 70, 'triangle', 0.09),
|
||||
/** The accused really is the liar. */
|
||||
caught: () => [523, 784].forEach((f, i) => tone(f, 140, 'square', 0.07, i * 120)),
|
||||
};
|
||||
|
||||
/** Sounds for what anyone did: descriptions, votes being cast, results (the room plays win / lose at the end). */
|
||||
function useLiarSounds(v: LiarView, me: string | null): void {
|
||||
const prev = useRef(v);
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
if (p === v) return;
|
||||
const last = p.events.at(-1)?.n ?? 0;
|
||||
const fresh = v.events.filter((e) => e.n > last);
|
||||
if (fresh.some((e) => e.t === 'end')) return;
|
||||
const acc = fresh.find((e) => e.t === 'accused');
|
||||
if (acc && acc.t === 'accused') return acc.liar ? lgSound.caught() : sfx.bad();
|
||||
if (fresh.some((e) => e.t === 'vote')) return sfx.chips(3);
|
||||
if (fresh.some((e) => e.t === 'left')) return sfx.whoosh();
|
||||
const newDesc = v.descriptions.slice(p.descriptions.length);
|
||||
if (newDesc.some((d) => d.from !== me)) return newDesc.some((d) => d.text === null) ? sfx.tick() : lgSound.said();
|
||||
if (v.my?.vote !== p.my?.vote && v.my?.vote) return sfx.select();
|
||||
const same = v.phase.kind === p.phase.kind && v.phase.voteRound === p.phase.voteRound;
|
||||
if (same && (v.phase.votedCount > p.phase.votedCount || v.phase.readyCount > p.phase.readyCount)) sfx.chip();
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>) {
|
||||
const ph = v.phase;
|
||||
const my = v.my;
|
||||
@@ -668,6 +716,7 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>)
|
||||
sounds.myTurn();
|
||||
}
|
||||
}, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useLiarSounds(v, me);
|
||||
|
||||
const pick: Pick = my && ph.kind === 'vote' && my.voteTargets.length ? { ids: my.voteTargets, chosen: my.vote, onPick: (id) => act({ type: 'vote', target: id }) } : null;
|
||||
const hot = ph.kind === 'guess' || (ph.kind === 'describe' && !!my?.canDescribe);
|
||||
@@ -683,10 +732,12 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>)
|
||||
<section className="lg-banner" data-time={ph.kind === 'ended' ? 'end' : 'play'} data-hot={hot} aria-label="진행 상황">
|
||||
<span className="lg-ph">
|
||||
<span className="d">🤥 라이어 게임</span>
|
||||
<strong>{phaseTitle(v)}</strong>
|
||||
<strong key={phaseKey} className="anim-slide-up">
|
||||
{phaseTitle(v)}
|
||||
</strong>
|
||||
<span className="s">{sub}</span>
|
||||
</span>
|
||||
<Clock endsAt={ph.endsAt} />
|
||||
<Clock endsAt={ph.endsAt} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
|
||||
{my && <WordCard v={v} always={ph.kind === 'ended'} />}
|
||||
</section>
|
||||
<News v={v} players={players} />
|
||||
@@ -778,7 +829,7 @@ function statusText(v: LiarView, 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} style={{ flexWrap: 'wrap' }}>
|
||||
{options.map(([k, l]) => (
|
||||
@@ -804,7 +855,7 @@ const onOff: [boolean, string][] = [
|
||||
[true, '켜기'],
|
||||
[false, '끄기'],
|
||||
];
|
||||
const secs = <T extends number>(...v: T[]): [T, string][] => v.map((x) => [x, `${x}초`]);
|
||||
const secs = <T extends number>(...v: T[]): [T | null, string][] => [...v.map((x): [T, string] => [x, `${x}초`]), [null, '무제한']];
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
|
||||
const [more, setMore] = useState(false);
|
||||
@@ -844,18 +895,21 @@ function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
|
||||
</button>
|
||||
{more && (
|
||||
<>
|
||||
<Field label="한 사람 설명 시간">
|
||||
<Field label="한 사람 설명 시간" help={o.describeSeconds === null ? '설명을 보낼 때까지 기다려요.' : undefined}>
|
||||
<Seg label="설명 시간" value={o.describeSeconds} options={secs(15, 20, 30, 45, 60)} onChange={(describeSeconds) => set({ describeSeconds })} />
|
||||
</Field>
|
||||
<Field label="자유 토론 시간">
|
||||
<Field label="자유 토론 시간" help={o.discussionSeconds === null ? '모두 [토론 끝내기]를 누르면 투표로 넘어가요.' : undefined}>
|
||||
<Seg label="토론 시간" value={o.discussionSeconds} options={secs(30, 60, 90, 120, 180)} onChange={(discussionSeconds) => set({ discussionSeconds })} />
|
||||
</Field>
|
||||
<Field label="투표 시간">
|
||||
<Field label="투표 시간" help={o.voteSeconds === null ? '모두 투표하면 결과가 나와요.' : undefined}>
|
||||
<Seg label="투표 시간" value={o.voteSeconds} options={secs(15, 20, 30, 45)} onChange={(voteSeconds) => set({ voteSeconds })} />
|
||||
</Field>
|
||||
<Field label="정답 맞히기 시간">
|
||||
<Field label="정답 맞히기 시간" help={o.guessSeconds === null ? '라이어가 답할 때까지 기다려요.' : undefined}>
|
||||
<Seg label="정답 맞히기 시간" value={o.guessSeconds} options={secs(20, 30, 45, 60)} onChange={(guessSeconds) => set({ guessSeconds })} />
|
||||
</Field>
|
||||
{[o.describeSeconds, o.discussionSeconds, o.voteSeconds, o.guessSeconds].includes(null) && (
|
||||
<span className="small muted">무제한이어도 연결이 끊긴 채 돌아오지 않는 사람은 잠시 뒤 넘어가요(설명 넘김, 표 없음, 답 없음).</span>
|
||||
)}
|
||||
<Field label="고운 말 필터(욕설·링크·전화번호 막기)">
|
||||
<Seg label="고운 말 필터" value={o.kidSafeChat} options={onOff} onChange={(kidSafeChat) => set({ kidSafeChat })} />
|
||||
</Field>
|
||||
@@ -868,7 +922,7 @@ function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
|
||||
function optionsSummary(o: LiarOptions): string {
|
||||
const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${TOPIC_KO[o.topic]}`];
|
||||
if (o.foolMode) parts.push('바보 모드');
|
||||
parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', `설명 ${o.describeSeconds}초`, `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기');
|
||||
parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', o.describeSeconds === null ? '설명 무제한' : `설명 ${o.describeSeconds}초`, o.discussionSeconds === null ? '토론 무제한' : `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기');
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
@@ -889,6 +943,7 @@ function Rules() {
|
||||
<li>라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.</li>
|
||||
<li>점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.</li>
|
||||
<li>바보 모드: 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.</li>
|
||||
<li>시간 무제한: 설명·토론·투표·정답 맞히기 시간을 무제한으로 할 수 있어요. 그 단계는 할 일을 다 마칠 때까지 기다려요.</li>
|
||||
</ul>
|
||||
<p className="small muted">내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.</p>
|
||||
</div>
|
||||
|
||||
@@ -55,3 +55,16 @@ test('마피아: 지목 투표 → 찬반 투표, 탈락한 사람', () => {
|
||||
const dead = { ...confirm, players: g.state.players.map((p: any) => (p.id === g.doctor ? { ...p, alive: false, diedDay: 1, diedBy: 'mafia' } : p)) };
|
||||
expect(helpNow(view(dead, g.doctor), g.doctor, users)).toContain('[죽은 사람] 채팅');
|
||||
});
|
||||
|
||||
test('마피아: 시간 무제한이면 [밤 마치기]·[반론 마치기]·모두 투표 안내', () => {
|
||||
const g = game();
|
||||
const night = { kind: 'night', startedAt: T, endsAt: null, ready: [], mafiaTarget: null, mafiaPickedBy: null, investigate: null, heal: null, mediumPeek: null };
|
||||
const s = { ...g.state, day: 2, phase: night };
|
||||
const c = helpNow(view(s, g.citizen), g.citizen, users);
|
||||
expect(c).toContain('[밤 마치기]');
|
||||
expect(c).toContain('(0/7)');
|
||||
const def = { ...g.state, day: 2, phase: { kind: 'defense', startedAt: T, endsAt: null, accused: g.citizen } };
|
||||
expect(helpNow(view(def, g.citizen), g.citizen, users)).toContain('[반론 마치기]를 눌러요');
|
||||
const vote = { ...g.state, day: 2, phase: { kind: 'vote', startedAt: T, endsAt: null, votes: {} } };
|
||||
expect(helpNow(view(vote, g.police), g.police, users)).toContain('모두 투표(기권 포함)하면 바로 결과가 나와요(0/7)');
|
||||
});
|
||||
|
||||
@@ -50,6 +50,8 @@ export function helpNow(v: MafiaView, me: string | null, players: Record<string,
|
||||
}
|
||||
|
||||
const idle = my.idleWarning ? '\n오늘도 아무것도 하지 않으면 자리 비움으로 탈락해요.' : '';
|
||||
const unl = ph.endsAt === null;
|
||||
const count = `(${ph.readyCount}/${ph.readyNeeded})`;
|
||||
|
||||
if (!my.alive) {
|
||||
const see = v.options.deadSeeAll ? ' 이 방에서는 탈락하면 모든 직업과 마피아 채팅도 볼 수 있어요.' : '';
|
||||
@@ -63,23 +65,28 @@ export function helpNow(v: MafiaView, me: string | null, players: Record<string,
|
||||
return `${head} [전체] 채팅으로 인사해요. 오늘은 투표가 없고, 끝나면 밤이 와요.\n다 됐으면 [인사 끝내기]를 눌러요. 살아 있는 사람이 모두 누르면 바로 넘어가요(${ph.readyCount}/${ph.readyNeeded}).${idle}`;
|
||||
case 'discussion': {
|
||||
const adj = my.canAdjust ? '\n[+15초]·[−15초]로 토론 시간을 하루 한 번 바꿀 수 있어요.' : '';
|
||||
return `${head} [전체] 채팅으로 누가 마피아 같은지 이야기해요. 직업을 밝힐지는 내 선택이에요.${adj}\n다 이야기했으면 [토론 끝내기]를 눌러요. 모두 누르면 바로 지목 투표로 넘어가요(${ph.readyCount}/${ph.readyNeeded}).${idle}`;
|
||||
return `${head} [전체] 채팅으로 누가 마피아 같은지 이야기해요. 직업을 밝힐지는 내 선택이에요.${adj}\n${unl ? '토론 시간은 무제한이에요. ' : ''}다 이야기했으면 [토론 끝내기]를 눌러요. 모두 누르면 바로 지목 투표로 넘어가요${count}.${idle}`;
|
||||
}
|
||||
case 'vote': {
|
||||
const now = my.vote === null ? '아직 고르지 않았어요(안 고르면 기권).' : my.vote === 'abstain' ? '지금은 기권으로 되어 있어요.' : `지금 ${n(my.vote)}을 골랐어요.`;
|
||||
return `${head} '사람들' 목록에서 초록 테두리 사람을 눌러 마피아로 의심되는 사람을 골라요. 시간 안에는 바꿀 수 있고, [기권]도 돼요.\n${now} 표가 가장 많은 한 명이 지목돼요. 같은 표가 나오면 아무도 지목되지 않아요.${idle}`;
|
||||
const now = my.vote === null ? `아직 고르지 않았어요${unl ? '' : '(안 고르면 기권)'}.` : my.vote === 'abstain' ? '지금은 기권으로 되어 있어요.' : `지금 ${n(my.vote)}을 골랐어요.`;
|
||||
const when = unl ? `시간 제한이 없어요. 모두 투표(기권 포함)하면 바로 결과가 나와요${count}. 그 전에는 바꿀 수 있어요.` : '시간 안에는 바꿀 수 있고, [기권]도 돼요.';
|
||||
return `${head} '사람들' 목록에서 초록 테두리 사람을 눌러 마피아로 의심되는 사람을 골라요. ${when}\n${now} 표가 가장 많은 한 명이 지목돼요. 같은 표가 나오면 아무도 지목되지 않아요.${idle}`;
|
||||
}
|
||||
case 'defense':
|
||||
if (ph.accused === me) return `${head} 내가 지목됐어요! [전체] 채팅으로 내가 왜 마피아가 아닌지 마지막으로 말해요. 지금은 나만 말할 수 있어요.`;
|
||||
return `${head} ${ph.accused ? n(ph.accused) : '지목된 사람'}의 마지막 변론을 들어요. 지금은 지목된 사람만 채팅할 수 있어요. 곧 찬반 투표를 해요.`;
|
||||
if (ph.accused === me) return `${head} 내가 지목됐어요! [전체] 채팅으로 내가 왜 마피아가 아닌지 마지막으로 말해요. 지금은 나만 말할 수 있어요.${unl ? '\n시간 제한이 없어요. 다 말했으면 [반론 마치기]를 눌러요.' : ''}`;
|
||||
return `${head} ${ph.accused ? n(ph.accused) : '지목된 사람'}의 마지막 변론을 들어요. 지금은 지목된 사람만 채팅할 수 있어요. ${unl ? '지목된 사람이 [반론 마치기]를 누르면 찬반 투표를 해요.' : '곧 찬반 투표를 해요.'}`;
|
||||
case 'confirm': {
|
||||
const who = ph.accused ? n(ph.accused) : '지목된 사람';
|
||||
if (!my.canConfirm) return `${head} 다른 사람들이 나를 탈락시킬지 찬반 투표를 하고 있어요. 결과를 기다려 주세요.`;
|
||||
const now = my.ballot ? `지금 ${my.ballot === 'yes' ? '찬성' : '반대'}했어요. 시간 안에는 바꿀 수 있어요.` : '안 누르면 집계에서 빠져요.';
|
||||
const now = unl
|
||||
? `${my.ballot ? `지금 ${my.ballot === 'yes' ? '찬성' : '반대'}했어요. ` : ''}시간 제한이 없어요. 모두 고르면 바로 결과가 나와요${count}.`
|
||||
: my.ballot
|
||||
? `지금 ${my.ballot === 'yes' ? '찬성' : '반대'}했어요. 시간 안에는 바꿀 수 있어요.`
|
||||
: '안 누르면 집계에서 빠져요.';
|
||||
return `${head} ${who}을 탈락시킬지 정해요. [찬성 (탈락)] 또는 [반대 (살리기)]를 눌러요.\n찬성이 반대보다 많아야 탈락해요. ${now}${idle}`;
|
||||
}
|
||||
case 'night':
|
||||
return nightHelp(v, me, n) + idle;
|
||||
return nightHelp(v, me, n) + (unl ? `\n밤 시간은 무제한이에요. ${my.ready ? '[밤 마치기]를 눌렀어요. 다른 사람을 기다려요' : '할 일을 마쳤으면 [밤 마치기]를 눌러요. 살아 있는 사람이 모두 누르면 아침이 와요'}${count}.` : '') + idle;
|
||||
}
|
||||
return head;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { Channel, ChatView, MafiaOptions, MafiaView, PlayerView, PrivateRes
|
||||
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, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { ChatMessage, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
|
||||
@@ -57,6 +57,28 @@ const PHASE_EVENT: Record<Exclude<MafiaView['phase']['kind'], 'ended'>, string>
|
||||
};
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
|
||||
/** Game sounds on top of the shared palette (site volume applies). */
|
||||
const mfSound = {
|
||||
/** Night falls: a low falling hum. */
|
||||
night: () => {
|
||||
tone(392, 520, 'sine', 0.1, 0, { slideTo: 196 });
|
||||
tone(294, 620, 'sine', 0.06, 180, { slideTo: 147 });
|
||||
},
|
||||
/** Morning: a small rising chime. */
|
||||
morning: () => [523, 659, 784].forEach((f, i) => tone(f, 160, 'triangle', 0.09, i * 110)),
|
||||
/** Judge's gavel (executed). */
|
||||
gavel: () => {
|
||||
noise(70, 0.35, 0, 'lowpass', 500);
|
||||
tone(120, 160, 'square', 0.08);
|
||||
noise(60, 0.25, 220, 'lowpass', 500);
|
||||
},
|
||||
/** Someone was taken in the night. */
|
||||
death: () => {
|
||||
tone(220, 380, 'sawtooth', 0.06, 0, { slideTo: 110 });
|
||||
tone(233, 380, 'sawtooth', 0.04, 40, { slideTo: 116 });
|
||||
},
|
||||
};
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const isNight = (v: MafiaView) => v.phase.kind === 'night' || v.phase.kind === 'roleReveal';
|
||||
|
||||
@@ -136,6 +158,11 @@ button.mf-tile { cursor: pointer; }
|
||||
.mf-log { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 3px; max-height: 320px; overflow: auto; }
|
||||
.mf-rules td, .mf-rules th { padding: 4px 6px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--border); }
|
||||
@keyframes mf-pop { from { transform: scale(.96); opacity: 0; } to { transform: none; opacity: 1; } }
|
||||
.mf-unl { font-size: 1.6rem; }
|
||||
.mf-unl small { display: block; font-size: .7rem; font-weight: 800; }
|
||||
.mf-tile[aria-pressed='true'] { animation: mf-pick .28s ease-out; }
|
||||
@keyframes mf-pick { 50% { transform: scale(1.07); } }
|
||||
.mf-rolecard[data-show='true'] { animation: anim-flip .35s ease both; }
|
||||
@keyframes mf-grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }
|
||||
@media (max-width: 1099px) {
|
||||
.mf { height: auto; }
|
||||
@@ -155,14 +182,20 @@ button.mf-tile { cursor: pointer; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.mf-banner { transition: none; }
|
||||
.mf-news, .mf-bar .tr i { animation: none; }
|
||||
.mf-news, .mf-bar .tr i, .mf-tile[aria-pressed='true'], .mf-rolecard[data-show='true'] { animation: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- small parts
|
||||
|
||||
function Clock({ endsAt }: { endsAt: number | null }) {
|
||||
function Clock({ endsAt, unlimited }: { endsAt: number | null; unlimited: boolean }) {
|
||||
const now = useServerNow(500);
|
||||
if (unlimited)
|
||||
return (
|
||||
<span className="mf-clock mf-unl" role="timer" aria-label="시간 제한 없음">
|
||||
∞<small>무제한</small>
|
||||
</span>
|
||||
);
|
||||
if (endsAt === null) return null;
|
||||
const sec = Math.max(0, Math.ceil((endsAt - now) / 1000));
|
||||
const text = sec >= 60 ? `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}` : `${sec}`;
|
||||
@@ -547,7 +580,7 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
body = (
|
||||
<>
|
||||
<p className="mf-prompt">{ph.kind === 'greeting' ? '인사 시간이에요. 오늘은 투표가 없어요.' : '토론 시간이에요. 마피아가 누구일까요?'}</p>
|
||||
{ph.kind === 'discussion' && v.options.timeAdjust && (
|
||||
{ph.kind === 'discussion' && v.options.timeAdjust && ph.endsAt !== null && (
|
||||
<div className="mf-big" role="group" aria-label="토론 시간 바꾸기">
|
||||
<button type="button" className="btn btn-secondary" disabled={pending || !my.canAdjust} onClick={() => act({ type: 'adjustTime', delta: 15 })} aria-label="토론 시간 15초 늘리기">
|
||||
+15초
|
||||
@@ -557,21 +590,24 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{ph.kind === 'discussion' && !my.canAdjust && v.options.timeAdjust && <span className="small muted">시간 바꾸기는 하루에 한 번만 할 수 있어요.</span>}
|
||||
{ph.kind === 'discussion' && !my.canAdjust && v.options.timeAdjust && ph.endsAt !== null && <span className="small muted">시간 바꾸기는 하루에 한 번만 할 수 있어요.</span>}
|
||||
<div className="mf-big">
|
||||
<button type="button" className="btn btn-primary" disabled={pending || !my.canReady} onClick={() => act({ type: 'readyEarly' })}>
|
||||
{my.ready ? `기다리는 중 (${ph.readyCount}/${ph.readyNeeded})` : `${ph.kind === 'greeting' ? '인사 끝내기' : '토론 끝내기'} (${ph.readyCount}/${ph.readyNeeded})`}
|
||||
{my.ready ? '기다리는 중' : ph.kind === 'greeting' ? '인사 끝내기' : '토론 끝내기'} <Count v={v} />
|
||||
</button>
|
||||
</div>
|
||||
<span className="small muted">살아 있는 사람이 모두 누르면 바로 다음으로 넘어가요.</span>
|
||||
<span className="small muted">{ph.endsAt === null ? '토론 시간이 무제한이에요. ' : ''}살아 있는 사람이 모두 누르면 바로 다음으로 넘어가요.</span>
|
||||
</>
|
||||
);
|
||||
} else if (ph.kind === 'vote') {
|
||||
body = (
|
||||
<>
|
||||
<p className="mf-prompt">마피아로 의심되는 사람을 골라 주세요</p>
|
||||
<span className="small">초록 테두리 사람을 누르면 지목해요. 시간 안에는 바꿀 수 있어요.</span>
|
||||
<strong>{my.vote === null ? '아직 고르지 않았어요 (안 고르면 기권)' : my.vote === 'abstain' ? '기권했어요' : `${n(my.vote)}을 지목했어요`}</strong>
|
||||
<span className="small">
|
||||
{ph.endsAt === null ? '초록 테두리 사람을 누르면 지목해요. 모두 투표하면 바로 결과가 나와요. ' : '초록 테두리 사람을 누르면 지목해요. 시간 안에는 바꿀 수 있어요.'}
|
||||
{ph.endsAt === null && <Count v={v} />}
|
||||
</span>
|
||||
<strong>{my.vote === null ? `아직 고르지 않았어요${ph.endsAt === null ? '' : ' (안 고르면 기권)'}` : my.vote === 'abstain' ? '기권했어요' : `${n(my.vote)}을 지목했어요`}</strong>
|
||||
<div className="mf-big">
|
||||
<button type="button" className="btn btn-secondary" disabled={pending || my.vote === 'abstain'} onClick={() => act({ type: 'vote', target: 'abstain' })}>
|
||||
기권
|
||||
@@ -580,7 +616,19 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
</>
|
||||
);
|
||||
} else if (ph.kind === 'defense') {
|
||||
body = <p className="mf-prompt">{ph.accused === me ? '지목됐어요. 전체 채팅으로 최후의 반론을 해 주세요!' : `${n(ph.accused!)}의 최후의 반론을 들어 주세요.`}</p>;
|
||||
body = (
|
||||
<>
|
||||
<p className="mf-prompt">{ph.accused === me ? '지목됐어요. 전체 채팅으로 최후의 반론을 해 주세요!' : `${n(ph.accused!)}의 최후의 반론을 들어 주세요.`}</p>
|
||||
{ph.endsAt === null && my.canReady && (
|
||||
<div className="mf-big">
|
||||
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'readyEarly' })}>
|
||||
반론 마치기
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{ph.endsAt === null && <span className="small muted">시간 제한이 없어요. {ph.accused === me ? '다 말했으면 [반론 마치기]를 눌러요.' : '지목된 사람이 [반론 마치기]를 누르면 찬반 투표로 넘어가요.'}</span>}
|
||||
</>
|
||||
);
|
||||
} else if (ph.kind === 'confirm') {
|
||||
body = my.canConfirm ? (
|
||||
<>
|
||||
@@ -593,7 +641,16 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
반대 (살리기)
|
||||
</button>
|
||||
</div>
|
||||
<span className="small muted">{my.ballot ? `${my.ballot === 'yes' ? '찬성' : '반대'}했어요. 시간 안에는 바꿀 수 있어요.` : '고르지 않으면 집계에서 빠져요.'}</span>
|
||||
<span className="small muted">
|
||||
{ph.endsAt === null
|
||||
? my.ballot
|
||||
? `${my.ballot === 'yes' ? '찬성' : '반대'}했어요. 모두 고르면 바로 결과가 나와요. `
|
||||
: '모두 고르면 바로 결과가 나와요. '
|
||||
: my.ballot
|
||||
? `${my.ballot === 'yes' ? '찬성' : '반대'}했어요. 시간 안에는 바꿀 수 있어요.`
|
||||
: '고르지 않으면 집계에서 빠져요.'}
|
||||
{ph.endsAt === null && <Count v={v} />}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<p className="mf-prompt">다른 사람들이 찬반 투표를 하고 있어요.</p>
|
||||
@@ -605,7 +662,7 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
<p className="mf-prompt">{nv.prompt}</p>
|
||||
{nv.action && nv.targets.length > 0 && (
|
||||
<>
|
||||
<span className="small">초록 테두리 사람을 누르면 골라요. 밤이 끝날 때 고른 사람으로 정해져요.</span>
|
||||
<span className="small">초록 테두리 사람을 누르면 골라요. 밤이 끝날 때 고른 사람으로 정해져요.{ph.endsAt === null ? ' 고른 다음 [밤 마치기]를 눌러요.' : ''}</span>
|
||||
<strong>{nv.choice ? `고른 사람: ${n(nv.choice)}${nv.pickedBy && nv.pickedBy !== me ? ` (${n(nv.pickedBy)}이 골랐어요)` : ''}` : '아직 고르지 않았어요'}</strong>
|
||||
{nv.action === 'mafiaTarget' && nv.choice && (
|
||||
<div className="mf-big">
|
||||
@@ -617,6 +674,16 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
</>
|
||||
)}
|
||||
{!nv.action && <span className="small muted">밤이 지나면 아침 발표가 있어요.</span>}
|
||||
{ph.endsAt === null && (
|
||||
<>
|
||||
<div className="mf-big">
|
||||
<button type="button" className="btn btn-primary" disabled={pending || !my.canReady} onClick={() => act({ type: 'readyEarly' })}>
|
||||
{my.ready ? '아침을 기다리는 중' : '밤 마치기'} <Count v={v} />
|
||||
</button>
|
||||
</div>
|
||||
<span className="small muted">밤 시간이 무제한이에요. 살아 있는 사람이 모두 누르면 아침이 와요.</span>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -639,6 +706,17 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
);
|
||||
}
|
||||
|
||||
/** "(3/5)": how many are done in this phase; bumps when it changes (someone else pressed / voted). */
|
||||
function Count({ v }: { v: MafiaView }) {
|
||||
const { readyCount: c, readyNeeded: n } = v.phase;
|
||||
if (!n) return null;
|
||||
return (
|
||||
<span key={c} className="anim-bump" style={{ display: 'inline-block' }}>
|
||||
({c}/{n})
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function FinalReveal({ v, players }: { v: MafiaView; players: Record<string, PublicUser> }) {
|
||||
const f = v.final!;
|
||||
return (
|
||||
@@ -680,6 +758,39 @@ function FinalReveal({ v, players }: { v: MafiaView; players: Record<string, Pub
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
/** Sounds for what anyone did: announcements (votes, deaths, saves, the end), choices, the done count. */
|
||||
function useMafiaSounds(v: MafiaView): void {
|
||||
const prev = useRef(v);
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
if (p === v) return;
|
||||
const last = p.events.at(-1)?.n ?? 0;
|
||||
const fresh = v.events.filter((e) => e.n > last);
|
||||
let played = false;
|
||||
const play = (f: () => void) => {
|
||||
if (played) return;
|
||||
played = true;
|
||||
f();
|
||||
};
|
||||
// The most telling announcement wins (one sound per update); the room plays win / lose at the end.
|
||||
if (fresh.some((e) => e.t === 'end')) return;
|
||||
for (const e of fresh) {
|
||||
if (e.t === 'death') play(e.by === 'mafia' ? mfSound.death : e.by === 'vote' ? mfSound.gavel : sfx.whoosh);
|
||||
else if (e.t === 'confirm' && e.outcome !== 'executed') play(sfx.good);
|
||||
else if (e.t === 'healed' || e.t === 'soldier') play(sfx.good);
|
||||
}
|
||||
if (fresh.some((e) => e.t === 'vote')) play(() => sfx.chips(3));
|
||||
if (fresh.some((e) => e.t === 'adjust')) play(sfx.tick);
|
||||
if (fresh.length) return;
|
||||
// Same phase: my own pick (vote, ballot, night target incl. a mafia mate's) or someone else being done.
|
||||
const my = v.my;
|
||||
const pm = p.my;
|
||||
if (my && pm && (my.vote !== pm.vote || my.ballot !== pm.ballot || my.night?.choice !== pm.night?.choice)) return play(sfx.select);
|
||||
if (v.phase.readyCount > p.phase.readyCount && v.phase.kind === p.phase.kind) play(sfx.chip);
|
||||
}, [v]);
|
||||
}
|
||||
|
||||
function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView>) {
|
||||
const ph = v.phase;
|
||||
const my = v.my;
|
||||
@@ -692,11 +803,13 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
return;
|
||||
}
|
||||
setAnnounce(`${v.day}일차 ${PHASE_KO[ph.kind]}`);
|
||||
if (my?.alive && (ph.kind === 'vote' || (ph.kind === 'confirm' && my.canConfirm) || ph.kind === 'night' || ph.kind === 'discussion')) {
|
||||
haptic(40);
|
||||
sounds.myTurn();
|
||||
}
|
||||
if (my?.alive && (ph.kind === 'vote' || (ph.kind === 'confirm' && my.canConfirm) || ph.kind === 'night' || ph.kind === 'discussion')) haptic(40);
|
||||
// Night and morning have their own sound; a vote I must cast gets the "my turn" sound.
|
||||
if (ph.kind === 'night') mfSound.night();
|
||||
else if (ph.kind === 'discussion' || ph.kind === 'greeting') mfSound.morning();
|
||||
else if (my?.alive && (ph.kind === 'vote' || (ph.kind === 'confirm' && my.canConfirm) || (ph.kind === 'defense' && ph.accused === me))) sounds.myTurn();
|
||||
}, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useMafiaSounds(v);
|
||||
|
||||
let pick: Pick = null;
|
||||
if (my?.alive && ph.kind === 'vote') pick = { ids: my.voteTargets, chosen: my.vote === 'abstain' ? null : my.vote, onPick: (id) => act({ type: 'vote', target: id }) };
|
||||
@@ -721,10 +834,12 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
<span className="d">
|
||||
{time === 'night' ? '🌙' : time === 'end' ? '🏁' : '☀️'} {v.day}일차
|
||||
</span>
|
||||
<strong>{PHASE_KO[ph.kind]}</strong>
|
||||
<strong key={phaseKey} className="anim-slide-up">
|
||||
{PHASE_KO[ph.kind]}
|
||||
</strong>
|
||||
<span className="s">{sub}</span>
|
||||
</span>
|
||||
<Clock endsAt={ph.endsAt} />
|
||||
<Clock endsAt={ph.endsAt} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
|
||||
{my && <RoleCard role={my.role} mates={my.mates} players={players} always={!!v.winner || !my.alive} />}
|
||||
</section>
|
||||
<News v={v} players={players} />
|
||||
@@ -834,7 +949,7 @@ function statusText(v: MafiaView, me: string | null, players: Record<string, Pub
|
||||
|
||||
// ---------------------------------------------------------------- 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]) => (
|
||||
@@ -861,6 +976,8 @@ const onOff: [boolean, string][] = [
|
||||
[false, '끄기'],
|
||||
];
|
||||
const secs = <T extends number>(...v: T[]): [T, string][] => v.map((x) => [x, `${x}초`]);
|
||||
/** Seconds plus 무제한 (null). */
|
||||
const secsU = <T extends number>(...v: T[]): [T | null, string][] => [...secs(...v), [null, '무제한']];
|
||||
const EXTRA_KO: Record<keyof MafiaOptions['extraRoles'], string> = { soldier: '군인', politician: '정치인', medium: '영매', lovers: '연인(2명)' };
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<MafiaOptions>) {
|
||||
@@ -903,7 +1020,8 @@ function Options({ value: o, onChange }: OptionsProps<MafiaOptions>) {
|
||||
/>
|
||||
</Field>
|
||||
<Field label="밤 시간">
|
||||
<Seg label="밤 시간" value={o.nightSeconds} options={secs(15, 20, 30, 45, 60, 90)} onChange={(nightSeconds) => set({ nightSeconds })} />
|
||||
<Seg label="밤 시간" value={o.nightSeconds} options={secsU(15, 20, 30, 45, 60, 90)} onChange={(nightSeconds) => set({ nightSeconds })} />
|
||||
{o.nightSeconds === null && <span className="small muted">살아 있는 사람이 모두 [밤 마치기]를 누르면 아침이 와요(직업과 상관없이 모두 눌러요).</span>}
|
||||
</Field>
|
||||
<Field label="탈락한 사람 공개">
|
||||
<Seg
|
||||
@@ -923,26 +1041,34 @@ function Options({ value: o, onChange }: OptionsProps<MafiaOptions>) {
|
||||
{more && (
|
||||
<>
|
||||
<Field label="토론 시간(살아 있는 사람 1명당)">
|
||||
<Seg label="토론 시간(1명당)" value={o.discussionPerAlive} options={secs(10, 15, 20)} onChange={(discussionPerAlive) => set({ discussionPerAlive })} />
|
||||
<Seg label="토론 시간(1명당)" value={o.discussionPerAlive} options={secsU(10, 15, 20)} onChange={(discussionPerAlive) => set({ discussionPerAlive })} />
|
||||
</Field>
|
||||
<Field label="토론 시간 최소">
|
||||
<Seg label="토론 시간 최소" value={o.discussionMin} options={secs(30, 45, 60, 90, 120)} onChange={(discussionMin) => set({ discussionMin })} />
|
||||
{o.discussionPerAlive === null ? (
|
||||
<span className="small muted">토론 시간이 무제한이에요. 살아 있는 사람이 모두 [토론 끝내기]를 누르면 투표로 넘어가요(최소·최대·±15초는 쓰지 않아요).</span>
|
||||
) : (
|
||||
<>
|
||||
<Field label="토론 시간 최소">
|
||||
<Seg label="토론 시간 최소" value={o.discussionMin} options={secs(30, 45, 60, 90, 120)} onChange={(discussionMin) => set({ discussionMin })} />
|
||||
</Field>
|
||||
<Field label="토론 시간 최대">
|
||||
<Seg label="토론 시간 최대" value={o.discussionMax} options={secs(60, 120, 180, 240, 300)} onChange={(discussionMax) => set({ discussionMax })} />
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
<Field label="지목 투표 시간" help={o.voteSeconds === null ? '모두 투표(기권 포함)하면 바로 결과가 나와요.' : undefined}>
|
||||
<Seg label="지목 투표 시간" value={o.voteSeconds} options={secsU(10, 15, 20, 30, 45, 60)} onChange={(voteSeconds) => set({ voteSeconds })} />
|
||||
</Field>
|
||||
<Field label="토론 시간 최대">
|
||||
<Seg label="토론 시간 최대" value={o.discussionMax} options={secs(60, 120, 180, 240, 300)} onChange={(discussionMax) => set({ discussionMax })} />
|
||||
<Field label="최후의 반론 시간" help={o.defenseSeconds === null ? '지목된 사람이 [반론 마치기]를 누르면 찬반 투표로 넘어가요.' : undefined}>
|
||||
<Seg label="최후의 반론 시간" value={o.defenseSeconds} options={secsU(10, 15, 20, 30, 45, 60)} onChange={(defenseSeconds) => set({ defenseSeconds })} />
|
||||
</Field>
|
||||
<Field label="지목 투표 시간">
|
||||
<Seg label="지목 투표 시간" value={o.voteSeconds} options={secs(10, 15, 20, 30, 45, 60)} onChange={(voteSeconds) => set({ voteSeconds })} />
|
||||
</Field>
|
||||
<Field label="최후의 반론 시간">
|
||||
<Seg label="최후의 반론 시간" value={o.defenseSeconds} options={secs(10, 15, 20, 30, 45, 60)} onChange={(defenseSeconds) => set({ defenseSeconds })} />
|
||||
</Field>
|
||||
<Field label="찬반 투표 시간">
|
||||
<Seg label="찬반 투표 시간" value={o.confirmSeconds} options={secs(5, 10, 15, 20, 30)} onChange={(confirmSeconds) => set({ confirmSeconds })} />
|
||||
</Field>
|
||||
<Field label="하루 한 번 토론 시간 ±15초">
|
||||
<Seg label="토론 시간 바꾸기" value={o.timeAdjust} options={onOff} onChange={(timeAdjust) => set({ timeAdjust })} />
|
||||
<Field label="찬반 투표 시간" help={o.confirmSeconds === null ? '지목된 사람을 뺀 모두가 고르면 바로 결과가 나와요.' : undefined}>
|
||||
<Seg label="찬반 투표 시간" value={o.confirmSeconds} options={secsU(5, 10, 15, 20, 30)} onChange={(confirmSeconds) => set({ confirmSeconds })} />
|
||||
</Field>
|
||||
{o.discussionPerAlive !== null && (
|
||||
<Field label="하루 한 번 토론 시간 ±15초">
|
||||
<Seg label="토론 시간 바꾸기" value={o.timeAdjust} options={onOff} onChange={(timeAdjust) => set({ timeAdjust })} />
|
||||
</Field>
|
||||
)}
|
||||
<Field label="지목 투표에서 누가 누구를 골랐는지 공개">
|
||||
<Seg label="투표 공개" value={o.openVote} options={onOff} onChange={(openVote) => set({ openVote })} />
|
||||
</Field>
|
||||
@@ -985,7 +1111,8 @@ function optionsSummary(o: MafiaOptions): string {
|
||||
const extras = (Object.keys(EXTRA_KO) as (keyof MafiaOptions['extraRoles'])[]).filter((k) => o.extraRoles[k]).map((k) => EXTRA_KO[k]);
|
||||
const parts = [o.mafiaCount === 'auto' ? '마피아 자동' : `마피아 ${o.mafiaCount}명`];
|
||||
if (extras.length) parts.push(`추가: ${extras.join('·')}`);
|
||||
parts.push(o.firstPhase === 'day' ? '낮부터' : '밤부터', `밤 ${o.nightSeconds}초`, `투표 ${o.voteSeconds}초`);
|
||||
parts.push(o.firstPhase === 'day' ? '낮부터' : '밤부터', o.nightSeconds === null ? '밤 무제한' : `밤 ${o.nightSeconds}초`, o.voteSeconds === null ? '투표 무제한' : `투표 ${o.voteSeconds}초`);
|
||||
if (o.discussionPerAlive === null) parts.push('토론 무제한');
|
||||
parts.push(o.deathReveal === 'none' ? '탈락자 비공개' : o.deathReveal === 'team' ? '탈락 시 마피아 여부 공개' : '탈락 시 직업 공개');
|
||||
return parts.join(' · ');
|
||||
}
|
||||
@@ -1006,6 +1133,10 @@ function Rules() {
|
||||
<p>
|
||||
밤에는 낮 채팅이 잠겨요. 마피아는 마피아 채팅으로, 연인은 연인 채팅으로 몰래 이야기해요. 탈락한 사람은 죽은 사람 채팅에서만 이야기할 수 있어요(영매는 밤에 함께해요).
|
||||
</p>
|
||||
<p>
|
||||
<strong>시간 무제한</strong>: 단계마다 시간을 무제한으로 할 수 있어요. 그러면 토론은 모두 [토론 끝내기], 투표는 모두 투표, 반론은 지목된 사람이 [반론 마치기], 밤은 모두 [밤 마치기]를 누를 때
|
||||
넘어가요. 연결이 끊긴 채 돌아오지 않는 사람은 잠시 뒤 기권·마침으로 처리돼요.
|
||||
</p>
|
||||
<table className="mf-rules small" style={{ borderCollapse: 'collapse', width: '100%' }}>
|
||||
<tbody>
|
||||
{ROLE_ORDER.map((r) => (
|
||||
|
||||
@@ -5,7 +5,7 @@ import { RACERS, type RacerId } from '@bg/games/magical-athlete/racers';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -20,6 +20,27 @@ const seatColor = (v: MagicalAthleteView, p: string) => COLORS[v.seats.indexOf(p
|
||||
const rname = (id: RacerId) => `${RACERS[id].emoji} ${RACERS[id].name}`;
|
||||
const who = (players: Record<string, PublicUser>, me: string | null, p: string) => (p === me ? '나' : nick(players, p));
|
||||
|
||||
/** Game sounds on top of the shared palette (site volume applies); `d` = delay in ms (after the dice lands). */
|
||||
const maSound = {
|
||||
/** Footsteps along the track. */
|
||||
steps: (d: number) => {
|
||||
for (let i = 0; i < 3; i++) tone(i % 2 ? 560 : 470, 45, 'triangle', 0.09, d + i * 90);
|
||||
},
|
||||
/** A racer's power: a quick sparkle up. */
|
||||
power: (d: number) => [880, 1175, 1568].forEach((f, i) => tone(f, 90, 'triangle', 0.08, d + i * 60)),
|
||||
/** Star space (+1 point). */
|
||||
star: (d: number) => {
|
||||
tone(1318, 70, 'square', 0.05, d);
|
||||
tone(1976, 160, 'square', 0.05, d + 70);
|
||||
},
|
||||
/** Rock space: tripped. */
|
||||
trip: (d: number) => tone(300, 200, 'sawtooth', 0.05, d, { slideTo: 150 }),
|
||||
/** Arrow space: slide forward / back. */
|
||||
arrow: (d: number, up: boolean) => tone(up ? 500 : 900, 220, 'sine', 0.09, d, { slideTo: up ? 1000 : 450 }),
|
||||
/** Crossing the finish line. */
|
||||
finish: (d: number) => [784, 988, 1318].forEach((f, i) => tone(f, 130, 'triangle', 0.1, d + i * 90)),
|
||||
};
|
||||
|
||||
const CSS = `
|
||||
.ma-wrap { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 10px; }
|
||||
/* Taller than the play area on PC: start at the top (centring would cut the top off where nobody can scroll to). */
|
||||
@@ -42,6 +63,10 @@ const CSS = `
|
||||
.ma-tok circle { stroke: #1f2937; stroke-width: 2; }
|
||||
.ma-tok.cur circle { stroke: var(--focus); stroke-width: 4; }
|
||||
.ma-tok.trip { opacity: .55; }
|
||||
.ma-hop { transform-box: fill-box; transform-origin: center; animation: ma-hop .45s ease-out; }
|
||||
@keyframes ma-hop { 30% { transform: translateY(-10px) scale(1.12); } 60% { transform: translateY(0) scale(.96); } }
|
||||
.ma-hop.tripped { animation: anim-shake .45s ease both; }
|
||||
.ma-medal { transform-box: fill-box; transform-origin: center; animation: anim-pop .32s cubic-bezier(.3,1.6,.5,1) both; }
|
||||
.ma-emoji { font-size: 16px; }
|
||||
.ma-lower { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; align-items: start; }
|
||||
.ma-panel { padding: 12px; display: flex; flex-direction: column; gap: 10px; }
|
||||
@@ -97,7 +122,7 @@ button.ma-card:hover:not(:disabled) { border-color: var(--primary); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ma-tok { transition: none; }
|
||||
.ma-die.rolling, .ma-news .fresh { animation: none; }
|
||||
.ma-die.rolling, .ma-news .fresh, .ma-hop, .ma-medal { animation: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -209,12 +234,15 @@ function Track({ v, me, players }: { v: MagicalAthleteView; me: string | null; p
|
||||
const isCur = r.cur === x.id;
|
||||
return (
|
||||
<g key={x.id} className={`ma-tok${isCur ? ' cur' : ''}${x.tripped ? ' trip' : ''}`} style={{ transform: `translate(${ox}px, ${oy}px)` }}>
|
||||
<circle r={n === 1 ? 17 : size} fill={seatColor(v, x.owner)} />
|
||||
<text className="ma-emoji" textAnchor="middle" dy={n === 1 ? 6 : 4} fontSize={n === 1 ? 17 : size + 2} transform={x.tripped ? 'rotate(90)' : undefined}>
|
||||
{RACERS[x.id].emoji}
|
||||
</text>
|
||||
{/* Remounted on every move / trip: a hop (or a stumble) while the token slides. */}
|
||||
<g key={`${x.pos}-${x.tripped}`} className={`ma-hop${x.tripped ? ' tripped' : ''}`}>
|
||||
<circle r={n === 1 ? 17 : size} fill={seatColor(v, x.owner)} />
|
||||
<text className="ma-emoji" textAnchor="middle" dy={n === 1 ? 6 : 4} fontSize={n === 1 ? 17 : size + 2} transform={x.tripped ? 'rotate(90)' : undefined}>
|
||||
{RACERS[x.id].emoji}
|
||||
</text>
|
||||
</g>
|
||||
{x.place && (
|
||||
<text textAnchor="middle" x={n === 1 ? 14 : size} y={n === 1 ? 19 : size + 2} fontSize={n === 1 ? 13 : 10}>
|
||||
<text className="ma-medal" textAnchor="middle" x={n === 1 ? 14 : size} y={n === 1 ? 19 : size + 2} fontSize={n === 1 ? 13 : 10}>
|
||||
{x.place === 1 ? '🥇' : '🥈'}
|
||||
</text>
|
||||
)}
|
||||
@@ -293,9 +321,11 @@ function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthlet
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="small muted" style={{ margin: 0 }}>
|
||||
시간이 지나면 {pr.timeoutText}.
|
||||
</p>
|
||||
{v.options.turnSeconds !== null && (
|
||||
<p className="small muted" style={{ margin: 0 }}>
|
||||
시간이 지나면 {pr.timeoutText}.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="muted small" style={{ margin: 0 }}>
|
||||
@@ -325,7 +355,7 @@ function Draft({ v, me, players, act, pending }: { v: MagicalAthleteView; me: st
|
||||
</p>
|
||||
<div className="ma-cards" role="group" aria-label="펼쳐진 선수">
|
||||
{d.line.map((id) => (
|
||||
<button key={id} type="button" className="ma-card" disabled={!mine || pending} aria-label={`${RACERS[id].name}: ${RACERS[id].text}${mine ? ' 누르면 뽑아요' : ''}`} onClick={() => act({ type: 'DRAFT', racer: id })}>
|
||||
<button key={id} type="button" className="ma-card anim-deal" disabled={!mine || pending} aria-label={`${RACERS[id].name}: ${RACERS[id].text}${mine ? ' 누르면 뽑아요' : ''}`} onClick={() => act({ type: 'DRAFT', racer: id })}>
|
||||
<span className="em" aria-hidden>
|
||||
{RACERS[id].emoji}
|
||||
</span>
|
||||
@@ -487,6 +517,8 @@ function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthlete
|
||||
const prevRace = useRef<number>(v.race?.no ?? 0);
|
||||
const [fresh, setFresh] = useState(prevLog.current);
|
||||
const prevTurn = useRef(v.turnSeq);
|
||||
const soundReady = useRef(false);
|
||||
const rollHeard = useRef(v.rollSeq);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (v.rollSeq <= prevRoll.current) {
|
||||
@@ -494,12 +526,10 @@ function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthlete
|
||||
return;
|
||||
}
|
||||
prevRoll.current = v.rollSeq;
|
||||
if (reducedMotion()) return sounds.stone();
|
||||
sfx.dice();
|
||||
if (reducedMotion()) return;
|
||||
setRolling(true);
|
||||
const t = setTimeout(() => {
|
||||
setRolling(false);
|
||||
sounds.stone();
|
||||
}, ROLL_MS);
|
||||
const t = setTimeout(() => setRolling(false), ROLL_MS);
|
||||
return () => clearTimeout(t);
|
||||
}, [v.rollSeq]);
|
||||
|
||||
@@ -513,14 +543,38 @@ function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthlete
|
||||
}
|
||||
const last = r.log.at(-1)?.n ?? 0;
|
||||
if (last <= prevLog.current) return;
|
||||
const first = prevLog.current === 0 && !soundReady.current;
|
||||
const added = r.log.filter((l) => l.n > prevLog.current && l.kind !== 'turn');
|
||||
setFresh(prevLog.current);
|
||||
prevLog.current = last;
|
||||
soundReady.current = true;
|
||||
if (added.length) setAnnounce(added.slice(-4).map((l) => l.text).join(' '));
|
||||
if (added.some((l) => l.kind === 'power')) haptic(30);
|
||||
if (added.some((l) => l.kind === 'finish')) sounds.ding();
|
||||
// One sound per update, after the dice lands when this update rolled (the dice has its own sound).
|
||||
if (first) return;
|
||||
const d = v.rollSeq > rollHeard.current && !reducedMotion() ? ROLL_MS : 0;
|
||||
rollHeard.current = v.rollSeq;
|
||||
const sp = added.filter((l) => l.kind === 'space');
|
||||
if (added.some((l) => l.kind === 'finish')) maSound.finish(d);
|
||||
else if (added.some((l) => l.kind === 'power')) maSound.power(d);
|
||||
else if (sp.some((l) => l.text.includes('별'))) maSound.star(d);
|
||||
else if (sp.some((l) => l.text.includes('돌'))) maSound.trip(d);
|
||||
else if (sp.length) maSound.arrow(d, sp.some((l) => l.text.includes('앞 화살표')));
|
||||
else if (added.some((l) => l.kind === 'move')) maSound.steps(d);
|
||||
}, [v.race?.log.at(-1)?.n, v.race?.no]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Draft picks, race selections and a new race, whoever made them.
|
||||
const drafted = Object.values(v.teams).flat().length;
|
||||
const pickedN = Object.values(v.picked).filter(Boolean).length;
|
||||
const prevPhase = useRef({ phase: v.phase, drafted, picked: pickedN, race: v.raceNo });
|
||||
useEffect(() => {
|
||||
const p = prevPhase.current;
|
||||
prevPhase.current = { phase: v.phase, drafted, picked: pickedN, race: v.raceNo };
|
||||
if (v.phase === 'race' && (p.phase !== 'race' || p.race !== v.raceNo)) return sfx.whoosh();
|
||||
if (v.phase === 'draft' && drafted > p.drafted) return sfx.cardDeal();
|
||||
if (v.phase === 'select' && pickedN > p.picked) sfx.chip();
|
||||
}, [v.phase, drafted, pickedN, v.raceNo]);
|
||||
|
||||
useEffect(() => {
|
||||
if (v.turnSeq === prevTurn.current) return;
|
||||
prevTurn.current = v.turnSeq;
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `timeLimitSec` | 제한 시간 | 60(1분) / 120(2분) / 180(3분) | 120 (원작) |
|
||||
| `timeLimitSec` | 제한 시간 | 60(1분) / 120(2분) / 180(3분) / 무제한 | 120 (원작) |
|
||||
|
||||
- 판 크기는 원작의 17×10으로 **고정**한다(단순하게). 휴대폰에서는 판을 돌려서 보여 주므로 작은 판 옵션은 넣지 않았다.
|
||||
|
||||
@@ -43,17 +43,17 @@
|
||||
### 8.1 상태(State)
|
||||
```ts
|
||||
interface AppleState {
|
||||
options: { timeLimitSec: 60 | 120 | 180 };
|
||||
options: { timeLimitSec: 60 | 120 | 180 | null }; // null = 무제한
|
||||
order: PlayerId[];
|
||||
initial: string; // 170자 '1'..'9' (행 우선), 공용 시작 판
|
||||
boards: Record<PlayerId, string>; // 각자 판, 지운 칸은 '0'
|
||||
score: Record<PlayerId, number>;
|
||||
clears: Record<PlayerId, number>; // 지운 횟수
|
||||
status: Record<PlayerId, 'playing' | 'stuck' | 'left'>;
|
||||
status: Record<PlayerId, 'playing' | 'stuck' | 'done' | 'left'>; // done = 무제한에서 「여기까지」
|
||||
recent: Record<PlayerId, number[]>; // 최근 고르기 서버 시각(속도 제한)
|
||||
phase: 'countdown' | 'playing' | 'ended';
|
||||
countdownEndsAt: number;
|
||||
endsAt: number; // countdownEndsAt + timeLimitSec
|
||||
endsAt: number | null; // countdownEndsAt + timeLimitSec (무제한이면 null)
|
||||
final: AppleFinal | null;
|
||||
}
|
||||
```
|
||||
@@ -63,6 +63,7 @@ interface AppleState {
|
||||
| type | payload | 누가 / 언제 | 검증 조건 |
|
||||
|---|---|---|---|
|
||||
| `select` | `r0, c0, r1, c1` (행 0~9, 열 0~16, 정수) | 게임 중인 사람, 카운트다운 끝 ~ 마감 전 | 나가지 않음, 막히지 않음, 1초에 5번 이하, 안에 사과 1개 이상, 합 = 10 |
|
||||
| `stop` | — | 「여기까지」, 무제한 방에서 게임 중인 사람 | 시작 뒤, 아직 `playing` |
|
||||
| `tick` | — | 서버 타이머 전용(스키마에 없음) | — |
|
||||
| `leave` | — | 서버(나가기) 전용 | 아직 게임 중 |
|
||||
|
||||
@@ -78,7 +79,7 @@ interface AppleState {
|
||||
- `setup`의 판 생성만(`ctx.rng`). 모두 같은 판이라 운의 차이가 없다. 컴퓨터 운(셔플 여러 번 중 고르기)도 적용하지 않는다(턴 게임 전략에만 적용, `luckApplies`).
|
||||
|
||||
### 8.5 타이머·시간 초과·연결 끊김
|
||||
- `deadline`: 카운트다운 중 `countdownEndsAt`, 진행 중 `endsAt`(서버 시계). 마감 `tick`으로 끝난다. 마감 뒤 도착한 `select`는 `시간이 다 됐어요.`로 거절.
|
||||
- `deadline`: 카운트다운 중 `countdownEndsAt`, 진행 중 `endsAt`(서버 시계). 마감 `tick`으로 끝난다. 마감 뒤 도착한 `select`는 `시간이 다 됐어요.`로 거절. 무제한이면 진행 중 마감이 없고, 모두 막히거나 「여기까지」(`stop`)를 누르면 끝난다. 연결이 끊긴 채 방의 유예 시간이 지난 사람은 `tick`으로 `done` 처리된다.
|
||||
- `timeoutPlayers`: 게임 중인 모두(막힌 사람 포함).
|
||||
- `timeoutNotBefore` = `deadline`: 연결이 끊긴 사람도 **일찍 시간 초과되지 않는다**(할 행동이 없음). 그 사람 점수는 그대로 남고 마감 때 순위에 들어간다.
|
||||
- 나가기: `leave` → 상태 `left`, 더는 못 고름. 여러 명으로 시작했는데 남은 사람이 1명이면 그 사람이 이긴 것으로 바로 끝, 아무도 안 남으면 끝.
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|---|---|---|---|
|
||||
| `guessMode` | 맞히기 방식 | `multi`(여러 명이 맞힐 때까지) / `firstOnly`(첫 정답자가 나오면 즉시 종료, 원조 캐치마인드식) | `multi` |
|
||||
| `rounds` | 라운드 수(1라운드 = 모두 1번씩 출제) | 1 / 2 / 3 | 2 |
|
||||
| `drawSeconds` | 그리기 제한 시간 | 60 / 80 / 100 / 120 | 80 |
|
||||
| `drawSeconds` | 그리기 제한 시간 | 60 / 80 / 100 / 120 / 무제한 | 80 |
|
||||
| `wordChoice` | 출제자가 3개 중 고르기 | on / off(무작위 1개) | on |
|
||||
| `categories` | 사용할 단어 분야 | 3.2 분야 다중 선택 | 전체 |
|
||||
| `difficulty` | 단어 난이도 | `easy` / `normal` / `mixed` | `mixed` |
|
||||
@@ -63,6 +63,7 @@
|
||||
|
||||
### 5.2 그리기 종료 조건
|
||||
- 시간 만료.
|
||||
- `drawSeconds` 무제한(null): 마감이 없다. 출제자가 `giveUp`(「정답 공개하고 넘기기」, 두 번 눌러 확인)으로 끝낼 수 있다(`endReason: giveUp`, 출제자 점수는 평소처럼 맞힌 사람 수로). 힌트(`full`)와 속도 보너스는 80초 기준(40초 초성, 60초 한 글자). 연결이 끊긴 출제자는 평소처럼 10초 뒤 `drawerAway`.
|
||||
- `multi`: 출제자를 제외한 접속 중인 전원이 맞힘.
|
||||
- `firstOnly`: 첫 정답자가 나오는 즉시.
|
||||
- 출제자 연결 끊김 10초 경과(출제자 0점, 정답 공개).
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `movement` | 이동 방식 | `dice` 주사위 2개로 복도 이동(원작처럼) / `free` 빠르게(아무 방이나 바로) | `dice` |
|
||||
| `turnSeconds` | 차례 제한 시간(이동·추리·고발) | 30 / 45 / 60 / 90초 | 60 |
|
||||
| `turnSeconds` | 차례 제한 시간(이동·추리·고발) | 30 / 45 / 60 / 90초 / 무제한 | 60 |
|
||||
|
||||
카드 보여 주기(반증)는 옵션 없이 20초. `free`는 노트 파일의 "이동을 줄이는 옵션이 있으면 좋다"를 반영한 하우스 룰이다.
|
||||
|
||||
@@ -120,6 +120,7 @@ interface ClueState {
|
||||
|
||||
### 8.5 타이머·시간 초과·연결 끊김
|
||||
- 차례 `turnSeconds`, 반증 20초. 내 차례를 3번 연속 시간 초과로 넘기면 그 사람 차례는 10초.
|
||||
- `turnSeconds` 무제한(null): 차례와 반증 모두 마감이 없다. 연결이 끊긴 채 방의 유예 시간이 지난 사람만 아래처럼 자동 진행되고, 그렇게 3번 넘긴 사람은 무제한 방에서도 10초 차례가 된다.
|
||||
- 내 차례 시간 초과: 차례 하나를 통째로 자동 진행 — 주사위를 굴려 가장 가까운 닿는 방에 들어가고(없으면 가장 가까운 방 쪽으로 걸음), 추리 없이 끝낸다. 빠른 이동이면 가장 가까운 방.
|
||||
- 반증 시간 초과: 맞는 카드 중 첫 장(용의자→흉기→방 순)을 보여 준다.
|
||||
- 아직 고발하지 않은 사람이 모두 3번 연속 시간 초과 상태면 아무도 못 이기고 끝난다(`timeout`). 혼자 남은 자리 비운 사람 때문에 판이 끝나지 않는 것을 막는다.
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|---|---|---|---|
|
||||
| `endMode` | 종료 방식 | `lastStanding`(한 명이 모든 카드를 가질 때까지, 국내 통상 규칙) / `official`(2명 남으면 다음 종 판정으로 종료, 원작 규칙) | `lastStanding` |
|
||||
| `timeLimitMin` | 전체 제한 시간(분). 만료 시 카드 많은 사람 승 | 5 / 10 / 15 / 없음 | 10 |
|
||||
| `flipSeconds` | 자기 차례에 뒤집기 제한 시간(초과 시 자동 뒤집기) | 2 / 3 / 5 / 8 | 3 |
|
||||
| `flipSeconds` | 자기 차례에 뒤집기 제한 시간(초과 시 자동 뒤집기) | 2 / 3 / 5 / 8 / 무제한 | 3 |
|
||||
| `autoFlip` | 모든 뒤집기를 서버가 일정 간격으로 자동 진행 | on / off | off |
|
||||
| `flipGuardMs` | 뒤집기 직후 다음 뒤집기를 받지 않는 시간(지연 공정성) | 400 / 600 / 1000 | 600 |
|
||||
| `wrongRingLockoutMs` | 틀린 종 후 그 사람의 종 잠금 시간 | 0 / 1000 / 2000 | 1000 |
|
||||
@@ -55,7 +55,7 @@
|
||||
### 5.1 뒤집기
|
||||
- 차례인 플레이어는 자기 덱 맨 위 카드를 뒤집어 자기 공개 더미 위에 놓는다. 그 다음 시계 방향으로 다음 "참가 중" 플레이어 차례.
|
||||
- 각 플레이어의 공개 더미 **맨 위 카드만** 셈에 들어간다.
|
||||
- `flipSeconds` 안에 뒤집지 않으면 서버가 자동으로 뒤집는다.
|
||||
- `flipSeconds` 안에 뒤집지 않으면 서버가 자동으로 뒤집는다. `무제한`(null)이면 차례 플레이어가 뒤집을 때까지 기다린다(연결이 끊긴 사람만 방의 유예 시간 뒤 자동 뒤집기). `autoFlip`과 함께면 3초(어린이 모드 8초) 간격으로 서버가 뒤집는다.
|
||||
- 뒤집은 직후 `flipGuardMs` 동안은 다음 사람의 뒤집기를 받지 않는다(예약해 두었다가 시간이 지나면 처리). 지연이 큰 사람도 같은 화면을 보고 종을 칠 시간을 보장하기 위함.
|
||||
|
||||
### 5.2 종 치기
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
| `topic` | 주제 | `random` / 과일·동물·직업·음식·장소·운동·탈것·물건·나라·동화 주인공 | `random` |
|
||||
| `foolMode` | 바보 모드: 라이어도 같은 주제의 다른 단어를 받고 자기가 라이어인지 모른다 | on / off | off |
|
||||
| `rounds` | 설명 바퀴 수(두 번째 바퀴는 거꾸로) | 1 / 2 | 2 |
|
||||
| `describeSeconds` | 한 사람 설명 시간 | 15 / 20 / 30 / 45 / 60 | 30 |
|
||||
| `discussionSeconds` | 자유 토론 시간 | 30 / 60 / 90 / 120 / 180 | 90 |
|
||||
| `voteSeconds` | 투표 시간(재투표도 같은 시간) | 15 / 20 / 30 / 45 | 30 |
|
||||
| `describeSeconds` | 한 사람 설명 시간 | 15 / 20 / 30 / 45 / 60 / 무제한 | 30 |
|
||||
| `discussionSeconds` | 자유 토론 시간 | 30 / 60 / 90 / 120 / 180 / 무제한 | 90 |
|
||||
| `voteSeconds` | 투표 시간(재투표도 같은 시간) | 15 / 20 / 30 / 45 / 무제한 | 30 |
|
||||
| `guessMode` | 라이어의 정답 맞히기 | `text`(직접 적기) / `choice`(주제 단어 목록에서 고르기) | `text` |
|
||||
| `guessSeconds` | 정답 맞히기 시간 | 20 / 30 / 45 / 60 | 30 |
|
||||
| `guessSeconds` | 정답 맞히기 시간 | 20 / 30 / 45 / 60 / 무제한 | 30 |
|
||||
| `kidSafeChat` | 고운 말 필터(욕설·링크·전화번호 막기, 마피아와 같은 필터) | on / off | on |
|
||||
|
||||
## 3. 구성물
|
||||
@@ -97,7 +97,7 @@ interface LiarState {
|
||||
| `ready` | — | 확인 시간·토론 | 아직 안 누름 |
|
||||
| `vote` | `target` | 투표 | 나 말고, 후보(재투표는 동점자) 중 |
|
||||
| `guess` | `text` | 정답 맞히기의 라이어 | 1~20자, `choice`면 주제 단어 |
|
||||
| `phaseTimeout` | — | 서버(시계) | `endsAt` 이후 |
|
||||
| `phaseTimeout` | — | 서버(시계) | `endsAt` 이후 (무제한 단계: 아직 안 마친 사람만, 방의 연결 끊김 유예 뒤) |
|
||||
| `leave` | — | 서버(나감) | 아직 안 나감 |
|
||||
|
||||
### 8.3 공개/비공개 정보 (view)
|
||||
@@ -115,6 +115,10 @@ interface LiarState {
|
||||
- 시간 초과: 확인 → 첫 설명, 설명 → 넘김, 토론 → 투표, 투표 → 집계, 정답 맞히기 → 틀림.
|
||||
- 나가기(`onLeave`): 그 사람은 이후 차례·투표·"모두 동의"에서 빠진다. 설명 차례였으면 다음 사람. 투표 중이면 그 사람 표와 그 사람이 받은 표를 지우고, 남은 사람이 다 투표했으면 바로 집계. 라이어가 나가면 시민 승리, 시민이 모두 나가면 라이어 승리.
|
||||
|
||||
- **시간 무제한**(단계별 옵션 값 `null`): 그 단계는 `endsAt: null`. 설명은 차례인 사람이 말할 때까지, 토론은 모두 [토론 끝내기], 투표는 모두 투표, 정답 맞히기는 라이어가 답할 때까지 기다린다. 제시어 확인(10초)은 그대로.
|
||||
- 시간 초과 대상(`timeoutPlayers`)은 아직 안 마친 사람들. 연결이 끊긴 채 방의 유예 시간이 지나면 그 사람의 `phaseTimeout`이 넘김(설명 `text: null`, 토론 끝, 표 없음 `passed`, 답 없음 → 시민 승리)으로 처리된다.
|
||||
- 컴퓨터는 무제한 단계를 기본 시간(설명 30초, 토론 90초, 투표·맞히기 30초)처럼 맞춰 행동한다.
|
||||
|
||||
### 8.6 종료 조건과 결과(GameResult)
|
||||
6절 표. `reason: 'normal'`, `summary` 예: "라이어 승리! 라이어가 아닌 사람이 지목됐어요. 제시어는 '수박'이었어요."
|
||||
|
||||
|
||||
@@ -16,13 +16,13 @@
|
||||
| `mafiaCount` | 마피아 수 | `auto` / 1~4 | `auto`(4장 표) |
|
||||
| `extraRoles` | 추가 직업(시민 자리를 대체) | `soldier`, `politician`, `medium`, `lovers` 다중 선택 | 없음 |
|
||||
| `firstPhase` | 시작 페이즈 | `day`(투표 없는 인사 낮) / `night` | `day` |
|
||||
| `discussionPerAlive` | 토론 시간 = 생존자 수 × 이 값 | 10 / 15 / 20 | 15 |
|
||||
| `discussionPerAlive` | 토론 시간 = 생존자 수 × 이 값 | 10 / 15 / 20 / 무제한 | 15 |
|
||||
| `discussionMin` / `discussionMax` | 토론 시간 하한/상한 | 30~300 | 60 / 180 |
|
||||
| `timeAdjust` | 낮마다 생존자 1인 1회 시간 연장/단축(±15초) | on / off | on |
|
||||
| `voteSeconds` | 지목 투표 시간 | 10~60 | 20 |
|
||||
| `defenseSeconds` | 최후의 반론 시간 | 10~60 | 20 |
|
||||
| `confirmSeconds` | 찬반 투표 시간 | 5~30 | 10 |
|
||||
| `nightSeconds` | 밤 시간 | 15~90 | 30 |
|
||||
| `voteSeconds` | 지목 투표 시간 | 10~60 / 무제한 | 20 |
|
||||
| `defenseSeconds` | 최후의 반론 시간 | 10~60 / 무제한 | 20 |
|
||||
| `confirmSeconds` | 찬반 투표 시간 | 5~30 / 무제한 | 10 |
|
||||
| `nightSeconds` | 밤 시간 | 15~90 / 무제한 | 30 |
|
||||
| `deathReveal` | 사망 시 공개 정보 | `none` / `team`(마피아 여부) / `role`(직업) | `team` |
|
||||
| `openVote` | 지목 투표에서 누가 누구를 찍었는지 공개 | on / off | on |
|
||||
| `doctorSelfHeal` | 의사 자기 치료 허용 | on / off | on |
|
||||
@@ -183,7 +183,7 @@ interface MafiaState {
|
||||
| `heal` | `{ target }` | 살아 있는 의사, night | 대상 생존, 자기면 `doctorSelfHeal`, 연속이면 `doctorRepeat` |
|
||||
| `mediumPeek` | `{ target }` | 살아 있는 영매, night | 대상 사망자 |
|
||||
| `phaseTimeout` | `{}` | 서버 내부(타이머) | `now >= phase.endsAt` |
|
||||
| `readyEarly` | `{}` | 생존자, discussion | 생존자 전원이 누르면 토론 즉시 종료(선택 기능) |
|
||||
| `readyEarly` | `{}` | 생존자, discussion (무제한 night: 생존자 「밤 마치기」, 무제한 defense: 피고 「반론 마치기」) | 생존자 전원이 누르면 토론 즉시 종료(선택 기능) |
|
||||
|
||||
페이즈 전환은 서버 타이머가 `phaseTimeout`을 apply하는 방식으로 일관되게 처리한다(재생 가능).
|
||||
|
||||
@@ -205,6 +205,12 @@ interface MafiaState {
|
||||
- 연결 끊김: 진행은 멈추지 않는다. 같은 플레이어가 연속 2번의 낮 동안 접속하지 않으면 "자리 비움 탈락" 처리(사망과 동일, `deathReveal` 적용). 이후 승리 판정.
|
||||
- 재접속 시 현재 view 전체(허용된 채팅 기록 포함) 재전송.
|
||||
|
||||
- **시간 무제한**(단계별 옵션 값 `null`, `discussionPerAlive: null`이면 토론 무제한·최소/최대/±15초 안 씀): 그 단계는 `endsAt: null`이고 마감 대신 "모두 마침"으로 넘어간다.
|
||||
- 토론: 생존자 전원 `readyEarly`. 지목 투표: 생존자 전원이 투표(기권 포함)하면 즉시 집계. 최후의 반론: 피고의 `readyEarly`. 찬반 투표: 피고를 뺀 생존자 전원이 찬반. 밤: 생존자 전원이 `readyEarly`(직업과 상관없이 모두 눌러서 누가 밤 행동을 하는지 드러나지 않음).
|
||||
- 시간 초과 대상(`timeoutPlayers`)은 아직 안 마친 사람들. 연결이 끊긴 채 방의 유예 시간이 지나면 그 사람의 `phaseTimeout`이 "넘김"(투표 기권, 찬반 미투표, 토론·밤 마침, 피고면 반론 끝)으로 처리된다. 자리 비움(`idleDays`) 규칙은 그대로.
|
||||
- 직업 확인·인사 시간은 고정 시간 그대로.
|
||||
- 컴퓨터는 무제한 단계를 기본 시간(토론 90초, 투표·반론 20초, 찬반 10초, 밤 30초)처럼 맞춰 행동하고 버튼을 누른다.
|
||||
|
||||
### 8.6 종료 조건과 결과(GameResult)
|
||||
```ts
|
||||
interface MafiaResult {
|
||||
|
||||
@@ -2469,12 +2469,12 @@ const PLANS: Record<string, Plan> = {
|
||||
},
|
||||
},
|
||||
catchmind: {
|
||||
// PC host + phone guest, 1 round of 60 s: each player draws once with real mouse strokes; the other sees the strokes
|
||||
// PC host + phone guest, 1 round with no drawing time limit (무제한): each player draws once with real mouse strokes; the other sees the strokes
|
||||
// (stroke count + pixels), guesses wrong, gets "아까워요" for a near miss, then the right answer; scores update.
|
||||
lobby: async (host) => {
|
||||
await host.getByRole('group', { name: '라운드 수' }).getByRole('button', { name: '1라운드' }).click();
|
||||
await host.getByRole('group', { name: '그리기 시간' }).getByRole('button', { name: '60초' }).click();
|
||||
await host.getByText(/^여러 명 맞히기 · 1라운드 · 60초/).first().waitFor();
|
||||
await host.getByRole('group', { name: '그리기 시간' }).getByRole('button', { name: '무제한' }).click();
|
||||
await host.getByText(/^여러 명 맞히기 · 1라운드 · 그리기 무제한/).first().waitFor();
|
||||
},
|
||||
drive: async (pages) => {
|
||||
const [host, guest] = pages as [Page, Page];
|
||||
@@ -2503,7 +2503,10 @@ const PLANS: Record<string, Plan> = {
|
||||
players: 3,
|
||||
lobby: async (host) => {
|
||||
await host.getByRole('group', { name: '설명 바퀴 수' }).getByRole('button', { name: '한 바퀴' }).click();
|
||||
await host.getByText(/한 바퀴 · 설명 30초/).first().waitFor();
|
||||
// Every phase without a clock (무제한): the flow below only moves on by what people do.
|
||||
await host.getByRole('button', { name: '▼ 자세한 설정' }).click();
|
||||
for (const g of ['설명 시간', '토론 시간', '투표 시간', '정답 맞히기 시간']) await host.getByRole('group', { name: g }).getByRole('button', { name: '무제한' }).click();
|
||||
await host.getByText(/한 바퀴 · 설명 무제한 · 토론 무제한/).first().waitFor();
|
||||
},
|
||||
drive: async (pages) => {
|
||||
const [host, phone] = pages as [Page, Page, Page];
|
||||
@@ -2601,10 +2604,11 @@ const PLANS: Record<string, Plan> = {
|
||||
// Night cannot end early (only its clock advances it), so give the night's chat+3 picks ample room under load.
|
||||
await host.getByRole('group', { name: '밤 시간' }).getByRole('button', { name: '45초' }).click();
|
||||
await host.getByRole('button', { name: '▼ 자세한 설정' }).click();
|
||||
await host.getByRole('group', { name: '지목 투표 시간' }).getByRole('button', { name: '10초', exact: true }).click();
|
||||
// 지목 투표·찬반 투표 무제한: they end as soon as everybody alive has voted.
|
||||
await host.getByRole('group', { name: '지목 투표 시간' }).getByRole('button', { name: '무제한' }).click();
|
||||
await host.getByRole('group', { name: '최후의 반론 시간' }).getByRole('button', { name: '10초', exact: true }).click();
|
||||
await host.getByRole('group', { name: '찬반 투표 시간' }).getByRole('button', { name: '5초', exact: true }).click();
|
||||
await host.getByText(/밤 45초 · 투표 10초/).first().waitFor();
|
||||
await host.getByRole('group', { name: '찬반 투표 시간' }).getByRole('button', { name: '무제한' }).click();
|
||||
await host.getByText(/밤 45초 · 투표 무제한/).first().waitFor();
|
||||
},
|
||||
drive: async (pages) => {
|
||||
const [host, phone] = pages as [Page, Page, Page, Page];
|
||||
@@ -2667,8 +2671,11 @@ const PLANS: Record<string, Plan> = {
|
||||
|
||||
for (const i of [M, P, D]) await mafiaBanner(pages[i]!, '지목 투표', 15_000);
|
||||
await mafiaPick(pages[P]!, MAFIA_NICKS[M]!);
|
||||
await pages[P]!.getByRole('timer', { name: '시간 제한 없음' }).waitFor();
|
||||
await mafiaShots(pages, '3b-vote-unlimited');
|
||||
await mafiaPick(pages[D]!, MAFIA_NICKS[M]!);
|
||||
await mafiaPick(pages[M]!, MAFIA_NICKS[P]!);
|
||||
// The last vote ends the 무제한 vote at once (no pressed state to wait for).
|
||||
await pages[M]!.locator('button.mf-tile[data-target="ok"]', { has: pages[M]!.locator('.nm', { hasText: new RegExp(`^${MAFIA_NICKS[P]}( \\(나\\))?$`) }) }).click();
|
||||
await mafiaBanner(host, '최후의 반론', 20_000);
|
||||
await pages[M]!.locator('.mf-news', { hasText: '지목 투표 결과' }).waitFor();
|
||||
if (await pages[P]!.getByLabel('전체 채팅 메시지').count()) throw new Error('others can talk during the last defense');
|
||||
@@ -2677,8 +2684,8 @@ const PLANS: Record<string, Plan> = {
|
||||
await mafiaShots(pages, '4-defense');
|
||||
await mafiaBanner(pages[P]!, '찬반 투표', 20_000);
|
||||
await pages[P]!.getByRole('button', { name: '찬성 (탈락)' }).click();
|
||||
await pages[D]!.getByRole('button', { name: '찬성 (탈락)' }).click();
|
||||
await pages[P]!.getByRole('button', { name: '찬성 (탈락)', pressed: true }).waitFor();
|
||||
await pages[D]!.getByRole('button', { name: '찬성 (탈락)' }).click();
|
||||
|
||||
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
|
||||
for (const p of pages) await p.locator('.mf-final', { hasText: '시민 팀 승리' }).waitFor();
|
||||
@@ -2808,8 +2815,8 @@ const PLANS: Record<string, Plan> = {
|
||||
// and the refuter see the shown card. After 8 suggestions everybody accuses a guess, so the game ends.
|
||||
players: 3,
|
||||
lobby: async (host) => {
|
||||
await host.getByRole('group', { name: '차례 제한 시간' }).getByRole('button', { name: '30초' }).click();
|
||||
await host.getByText(/주사위 이동 · 차례 30초/).first().waitFor();
|
||||
await host.getByRole('group', { name: '차례 제한 시간' }).getByRole('button', { name: '무제한' }).click();
|
||||
await host.getByText(/주사위 이동 · 차례 시간 무제한/).first().waitFor();
|
||||
},
|
||||
drive: async (pages) => {
|
||||
const [host, guest] = pages as [Page, Page, Page];
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -202,7 +202,7 @@ describe('점수(§6)', () => {
|
||||
test('multi: 아무도 못 맞히면 출제자 0점, 시간 만료로 공개', () => {
|
||||
let s = drawWith(make(3), '기린');
|
||||
const d = s.turn.drawer;
|
||||
s = act(s, d, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, d, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.phase).toBe('reveal');
|
||||
expect(s.turn.endReason).toBe('time');
|
||||
expect(s.scores[d]).toBe(0);
|
||||
@@ -224,11 +224,42 @@ describe('점수(§6)', () => {
|
||||
test('speedBonus: 남은 시간 비율 × 5점 추가', () => {
|
||||
let s = drawWith(make(3, { speedBonus: true }), '기린', T0);
|
||||
const g = guessers(s)[0]!;
|
||||
const dur = s.turn.endsAt - s.turn.startedAt;
|
||||
const dur = s.turn.endsAt! - s.turn.startedAt;
|
||||
s = act(s, g, guess('기린'), T0 + dur / 2);
|
||||
expect(s.scores[g]).toBe(10 + 3); // round(2.5)
|
||||
});
|
||||
|
||||
test('그리기 무제한: 마감 없음(힌트는 80초 기준), 출제자 정답 공개로 넘기기, 시간 제한 방에서는 거절', () => {
|
||||
let s = drawWith(make(3, { drawSeconds: null, speedBonus: true }), '아이스크림', T0);
|
||||
const d = s.turn.drawer;
|
||||
const [a, b] = guessers(s) as [string, string];
|
||||
expect(s.turn.endsAt).toBeNull();
|
||||
expect(view(s, a).phaseMs).toBeNull();
|
||||
// Hints still come, at 40 s and 60 s (the 80 s reference); after them nothing is due.
|
||||
expect(cm.deadline!(s)).toBe(T0 + 40_000);
|
||||
s = act(s, d, { type: 'tick' }, T0 + 40_000);
|
||||
expect(s.turn.hintStage).toBe(1);
|
||||
s = act(s, d, { type: 'tick' }, T0 + 60_000);
|
||||
expect(s.turn.hintStage).toBe(2);
|
||||
expect(cm.deadline!(s)).toBeNull();
|
||||
// A guess long after "80 s" is still taken (speed bonus 0 by then).
|
||||
s = act(s, a, guess('아이스크림'), T0 + 600_000);
|
||||
expect(s.scores[a]).toBe(10);
|
||||
expect(reason(s, a, { type: 'giveUp' })).toBe('출제자만 정답을 공개할 수 있어요.');
|
||||
s = act(s, d, { type: 'giveUp' }, T0 + 601_000);
|
||||
expect(s.turn.phase).toBe('reveal');
|
||||
expect(s.turn.endReason).toBe('giveUp');
|
||||
expect(s.scores[d]).toBe(2); // one solver in multi mode
|
||||
expect(view(s, b).word).toBe('아이스크림');
|
||||
const timed = drawWith(make(3), '기린');
|
||||
expect(reason(timed, timed.turn.drawer, { type: 'giveUp' })).toBe('제한 시간이 있는 방에서는 시간이 끝날 때까지 그려요.');
|
||||
// An away drawer is still timed out by the room (nothing else due → drawerAway).
|
||||
let w = drawWith(make(3, { drawSeconds: null, hints: 'basic' }), '기린', T0);
|
||||
expect(cm.deadline!(w)).toBeNull();
|
||||
w = act(w, w.turn.drawer, { type: 'tick' }, T0 + 30_000);
|
||||
expect(w.turn.endReason).toBe('drawerAway');
|
||||
});
|
||||
|
||||
test('신고 과반 → 즉시 종료, 출제자 0점(맞힌 사람 점수 유지)', () => {
|
||||
let s = drawWith(make(5), '기린');
|
||||
const d = s.turn.drawer;
|
||||
@@ -367,16 +398,16 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
expect(s.turn.phase).toBe('drawing');
|
||||
expect(s.turn.word!.word).toBe(c0);
|
||||
expect(s.away).toEqual([]);
|
||||
s = act(s, first, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, first, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.phase).toBe('reveal');
|
||||
expect(cm.deadline!(s)).toBe(s.turn.startedAt + REVEAL_MS);
|
||||
s = act(s, first, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, first, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.drawer).not.toBe(first);
|
||||
expect(s.turn.no).toBe(2);
|
||||
const second = s.turn.drawer;
|
||||
s = act(s, second, { type: 'chooseWord', index: 2 }, s.turn.startedAt + 1000);
|
||||
s = act(s, second, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, second, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, second, { type: 'tick' }, s.turn.endsAt!);
|
||||
s = act(s, second, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.finished).toBe(true);
|
||||
const r = cm.result(s)!;
|
||||
expect(r.ranking.flat().sort()).toEqual(['p1', 'p2']);
|
||||
@@ -410,15 +441,15 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
// Skipped while away: the next drawers are the others.
|
||||
const seen: string[] = [];
|
||||
for (let i = 0; i < 2; i++) {
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
seen.push(s.turn.drawer);
|
||||
s = act(s, s.turn.drawer, { type: 'chooseWord', index: 0 }, s.turn.startedAt + 100);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
}
|
||||
expect(seen).not.toContain(d);
|
||||
// "돌아왔어요" clears the mark.
|
||||
expect(reason(s, d, { type: 'back' })).toBeNull();
|
||||
s = act(s, d, { type: 'back' }, s.turn.endsAt - 1);
|
||||
s = act(s, d, { type: 'back' }, s.turn.endsAt! - 1);
|
||||
expect(s.away).toEqual([]);
|
||||
expect(reason(s, d, { type: 'back' })).not.toBeNull();
|
||||
});
|
||||
@@ -431,7 +462,7 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
expect(s.turn.phase).toBe('reveal');
|
||||
expect(s.turn.endReason).toBe('drawerLeft');
|
||||
expect(cm.onLeave!(s, d)).toBeNull();
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.drawer).not.toBe(d);
|
||||
const other = s.order.find((p) => p !== d && p !== s.turn.drawer)!;
|
||||
s = act(s, other, { type: 'leave' }, s.turn.startedAt + 100);
|
||||
@@ -454,7 +485,7 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
let s = drawWith(make(4, { guessMode: 'firstOnly', answererDraws: true }), '기린');
|
||||
const g = guessers(s)[2]!;
|
||||
s = act(s, g, guess('기린'), T0 + 2000);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.drawer).toBe(g);
|
||||
});
|
||||
|
||||
@@ -466,7 +497,7 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
s.turnsPlayed = s.totalTurns - 1;
|
||||
s.round = s.options.rounds;
|
||||
s.turn.drawer = s.order.at(-1)!;
|
||||
const r = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
const r = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(r.finished).toBe(true);
|
||||
expect(cm.result(r)!.ranking.map((g) => [...g].sort())).toEqual([['p2'], ['p1', 'p3'], ['p4']]);
|
||||
expect(r.final!.ranking.map((x) => x.rank)).toEqual([1, 2, 2, 4]);
|
||||
@@ -540,7 +571,8 @@ function fastPlayout(players: PlayerId[], options: CatchmindOptions, seed: RngSt
|
||||
invariants(s, poolSize);
|
||||
if (cm.result(s)) return { state: s, trace, steps: step };
|
||||
// Timer: the drawer's tick when due (as the room would), otherwise a random actor.
|
||||
const due = cm.deadline!(s)!;
|
||||
// 무제한 drawing without hints has no deadline: only the random "away drawer" ticks below.
|
||||
const due = cm.deadline!(s) ?? Infinity;
|
||||
let p: PlayerId;
|
||||
let a: CatchmindAction;
|
||||
if (now >= due || pick.int(12) === 0) {
|
||||
@@ -603,7 +635,7 @@ describe('무작위 대국(§10, docs/09 §7)', () => {
|
||||
const options = opts({
|
||||
guessMode: pk.int(3) === 0 ? 'firstOnly' : 'multi',
|
||||
rounds: (1 + pk.int(3)) as 1 | 2 | 3,
|
||||
drawSeconds: ([60, 80, 100, 120] as const)[pk.int(4)]!,
|
||||
drawSeconds: ([60, 80, 100, 120, null] as const)[pk.int(5)]!,
|
||||
wordChoice: pk.int(4) !== 0,
|
||||
hints: (['none', 'basic', 'full'] as const)[pk.int(3)]!,
|
||||
letterReport: pk.int(3) !== 0,
|
||||
|
||||
@@ -118,11 +118,16 @@ export function reportsNeeded(s: S): number {
|
||||
return Math.floor(voters / 2) + 1;
|
||||
}
|
||||
|
||||
/** 무제한 drawings time their hints and the speed bonus as if they had the default 80 seconds. */
|
||||
export const UNLIMITED_REF_MS = 80_000;
|
||||
/** The drawing's length for hints / speed bonus (무제한: the 80 s reference). */
|
||||
const drawLen = (t: Turn) => (t.endsAt === null ? UNLIMITED_REF_MS : t.endsAt - t.startedAt);
|
||||
|
||||
/** Next hint time while drawing (`hints: full` only): 50% → initials, 75% → one letter (skipped for ≤ 2 letters). */
|
||||
export function nextHintAt(s: S): number | null {
|
||||
const t = s.turn;
|
||||
if (s.finished || t.phase !== 'drawing' || s.options.hints !== 'full' || !t.word) return null;
|
||||
const dur = t.endsAt - t.startedAt;
|
||||
const dur = drawLen(t);
|
||||
if (t.hintStage === 0) return t.startedAt + Math.round(dur * 0.5);
|
||||
if (t.hintStage === 1 && letters(t.word.word) > 2) return t.startedAt + Math.round(dur * 0.75);
|
||||
return null;
|
||||
@@ -178,7 +183,7 @@ function beginDrawing(s: S, index: number, ctx: Ctx): void {
|
||||
t.choices = [];
|
||||
t.phase = 'drawing';
|
||||
t.startedAt = ctx.now;
|
||||
t.endsAt = ctx.now + s.options.drawSeconds * 1000;
|
||||
t.endsAt = s.options.drawSeconds === null ? null : ctx.now + s.options.drawSeconds * 1000;
|
||||
t.hintStage = 0;
|
||||
ctx.events.push({ type: 'drawing', no: t.no, drawer: t.drawer });
|
||||
}
|
||||
@@ -297,7 +302,7 @@ function guess(s: S, p: PlayerId, raw: string, ctx: Ctx): void {
|
||||
if (j === 'correct') {
|
||||
const k = t.solvers.length + 1;
|
||||
let points = s.options.guessMode === 'multi' ? Math.max(10 - 2 * (k - 1), 4) : 10;
|
||||
if (s.options.speedBonus) points += Math.round((5 * Math.max(0, t.endsAt - ctx.now)) / Math.max(1, t.endsAt - t.startedAt));
|
||||
if (s.options.speedBonus) points += Math.round((5 * Math.max(0, t.startedAt + drawLen(t) - ctx.now)) / Math.max(1, drawLen(t)));
|
||||
t.solvers.push({ id: p, at: ctx.now, points });
|
||||
s.scores[p] = (s.scores[p] ?? 0) + points;
|
||||
s.correctCounts[p] = (s.correctCounts[p] ?? 0) + 1;
|
||||
@@ -318,7 +323,7 @@ function tick(s: S, ctx: Ctx): void {
|
||||
const t = s.turn;
|
||||
if (t.phase === 'choosing') {
|
||||
// Only a disconnected drawer is timed out before the 10 s are up (room grace hook): skip them next time.
|
||||
if (ctx.now < t.endsAt) markAway(s, t.drawer);
|
||||
if (ctx.now < t.endsAt!) markAway(s, t.drawer);
|
||||
beginDrawing(s, 0, ctx);
|
||||
return;
|
||||
}
|
||||
@@ -328,7 +333,7 @@ function tick(s: S, ctx: Ctx): void {
|
||||
advanceHint(s, ctx);
|
||||
hinted = true;
|
||||
}
|
||||
if (ctx.now >= t.endsAt) return endDrawing(s, 'time', ctx);
|
||||
if (t.endsAt !== null && ctx.now >= t.endsAt) return endDrawing(s, 'time', ctx);
|
||||
if (hinted) return;
|
||||
// Nothing was due: the drawer has been disconnected for DRAWER_AWAY_MS (§5.2) → 0 points, answer revealed.
|
||||
markAway(s, t.drawer);
|
||||
@@ -499,7 +504,7 @@ function buildView(s: S, viewer: PlayerId | null, withCanvas: boolean): Catchmin
|
||||
drawer: t.drawer,
|
||||
startedAt: t.startedAt,
|
||||
endsAt: t.endsAt,
|
||||
phaseMs: t.endsAt - t.startedAt,
|
||||
phaseMs: t.endsAt === null ? null : t.endsAt - t.startedAt,
|
||||
choices: isDrawer && t.phase === 'choosing' && !s.finished ? t.choices.map((w) => ({ word: w.word, category: w.category, difficulty: w.difficulty })) : null,
|
||||
word: knows && t.word ? t.word.word : null,
|
||||
category: knows && t.word ? t.word.category : null,
|
||||
@@ -613,7 +618,7 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
const len = [...cleanText(a.text)].length;
|
||||
if (len < 1) return fail('내용을 입력해 주세요.');
|
||||
if (len > GUESS_MAX) return fail(`${GUESS_MAX}자까지 쓸 수 있어요.`);
|
||||
if (now !== undefined && now >= t.endsAt) return fail('시간이 다 됐어요.');
|
||||
if (now !== undefined && t.endsAt !== null && now >= t.endsAt) return fail('시간이 다 됐어요.');
|
||||
if (!rateOk(s.msgTimes[actor], GUESS_MSGS_PER_SEC, now)) return fail('조금 천천히 보내 주세요.');
|
||||
return ok;
|
||||
}
|
||||
@@ -632,6 +637,11 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
return ok;
|
||||
case 'back':
|
||||
return s.away.includes(actor) ? ok : fail('이미 게임에 참여하고 있어요.');
|
||||
case 'giveUp':
|
||||
if (actor !== t.drawer) return fail('출제자만 정답을 공개할 수 있어요.');
|
||||
if (t.phase !== 'drawing') return fail('그리는 동안에만 정답을 공개할 수 있어요.');
|
||||
if (s.options.drawSeconds !== null) return fail('제한 시간이 있는 방에서는 시간이 끝날 때까지 그려요.');
|
||||
return ok;
|
||||
case 'report':
|
||||
if (!s.options.letterReport) return fail('이 방은 신고를 쓰지 않아요.');
|
||||
if (t.phase !== 'drawing') return fail('그리는 동안에만 신고할 수 있어요.');
|
||||
@@ -670,6 +680,9 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
case 'back':
|
||||
ctx.events.push({ type: 'back', player: actor });
|
||||
break;
|
||||
case 'giveUp':
|
||||
endDrawing(s, 'giveUp', ctx);
|
||||
break;
|
||||
case 'report':
|
||||
s.turn.reports.push(actor);
|
||||
ctx.events.push({ type: 'report', count: s.turn.reports.length, need: reportsNeeded(s) });
|
||||
@@ -702,7 +715,9 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
deadline(s) {
|
||||
if (s.finished) return null;
|
||||
const h = nextHintAt(s);
|
||||
return h === null ? s.turn.endsAt : Math.min(h, s.turn.endsAt);
|
||||
const e = s.turn.endsAt;
|
||||
if (h === null) return e;
|
||||
return e === null ? h : Math.min(h, e);
|
||||
},
|
||||
|
||||
/** The drawer's clock drives every server tick (choosing, hints, time up, reveal). */
|
||||
@@ -768,7 +783,7 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
out.push({ type: 'draw', op: { k: 'e', s: t.lastStroke } });
|
||||
}
|
||||
if (t.live > 0) out.push({ type: 'draw', op: { k: 'u' } }, { type: 'draw', op: { k: 'x' } });
|
||||
out.push({ type: 'reaction', code: 'almost' });
|
||||
out.push({ type: 'reaction', code: 'almost' }, { type: 'giveUp' });
|
||||
} else {
|
||||
out.push({ type: 'guess', text: t.word!.word }, { type: 'guess', text: '모르겠어요' }, { type: 'guess', text: `${t.word!.word} 맞나` }, { type: 'report' });
|
||||
}
|
||||
|
||||
@@ -53,9 +53,10 @@ export const catchmindOptionsSchema = z.object({
|
||||
rounds: lit<1 | 2 | 3>(1, 2, 3)
|
||||
.default(2)
|
||||
.meta({ title: '라운드 수(모두 한 번씩 그리면 1라운드)', labels: { 1: '1라운드', 2: '2라운드', 3: '3라운드' } }),
|
||||
drawSeconds: lit<60 | 80 | 100 | 120>(60, 80, 100, 120)
|
||||
/** null = 무제한: the drawing goes on until it is solved (or the drawer opens the answer with `giveUp`). */
|
||||
drawSeconds: lit<60 | 80 | 100 | 120 | null>(60, 80, 100, 120, null)
|
||||
.default(80)
|
||||
.meta({ title: '그리기 제한 시간', labels: { 60: '60초', 80: '80초', 100: '100초', 120: '120초' } }),
|
||||
.meta({ title: '그리기 제한 시간', labels: { 60: '60초', 80: '80초', 100: '100초', 120: '120초', null: '무제한(맞히거나 출제자가 넘길 때까지)' } }),
|
||||
wordChoice: z.boolean().default(true).meta({ title: '출제자가 단어 3개 중 고르기(끄면 무작위 1개)' }),
|
||||
categories: z
|
||||
.object(Object.fromEntries(CATEGORIES.map((c) => [c, z.boolean().default(true).meta({ title: CATEGORY_KO[c] })])) as Record<Category, z.ZodDefault<z.ZodBoolean>>)
|
||||
@@ -104,6 +105,8 @@ export const catchmindActionSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('report') }),
|
||||
/** "돌아왔어요": clears the away mark (players marked away are skipped as drawer). */
|
||||
z.object({ type: z.literal('back') }),
|
||||
/** 무제한 only: the drawer opens the answer and ends the drawing (drawer points as usual for those who got it). */
|
||||
z.object({ type: z.literal('giveUp') }),
|
||||
]);
|
||||
/** Client actions plus system-only ones (server timer, leaving) that are not in the schema. */
|
||||
export type CatchmindAction = z.infer<typeof catchmindActionSchema> | { type: 'tick' } | { type: 'leave' };
|
||||
@@ -130,7 +133,7 @@ export interface Solver {
|
||||
points: number;
|
||||
}
|
||||
|
||||
export type TurnEndReason = 'time' | 'allSolved' | 'first' | 'report' | 'drawerAway' | 'drawerLeft';
|
||||
export type TurnEndReason = 'time' | 'allSolved' | 'first' | 'report' | 'drawerAway' | 'drawerLeft' | 'giveUp';
|
||||
|
||||
export interface Turn {
|
||||
/** 1-based turn counter (also the canvas key). */
|
||||
@@ -140,7 +143,8 @@ export interface Turn {
|
||||
choices: WordEntry[];
|
||||
word: WordEntry | null;
|
||||
startedAt: number;
|
||||
endsAt: number;
|
||||
/** null only while drawing with no time limit (무제한). */
|
||||
endsAt: number | null;
|
||||
/** 0 letter count, 1 initial consonants, 2 one letter (§5.4). */
|
||||
hintStage: 0 | 1 | 2;
|
||||
revealIndex: number | null;
|
||||
@@ -243,9 +247,9 @@ export interface CatchmindView {
|
||||
phase: Turn['phase'] | 'ended';
|
||||
drawer: PlayerId;
|
||||
startedAt: number;
|
||||
endsAt: number;
|
||||
/** Length of the current phase (ms), for timer rings. */
|
||||
phaseMs: number;
|
||||
endsAt: number | null;
|
||||
/** Length of the current phase (ms), for timer rings; null = 무제한. */
|
||||
phaseMs: number | null;
|
||||
/** Drawer only, while choosing. */
|
||||
choices: ChoiceView[] | null;
|
||||
/** Drawer, solvers and (after the turn) everyone. */
|
||||
|
||||
@@ -314,6 +314,29 @@ describe('timer and leaving', () => {
|
||||
expect(u.deadlineAt).toBe(clock + 10_000);
|
||||
});
|
||||
|
||||
test('turnSeconds 무제한: no clock on turns or refuting; an away player (room grace) is still moved on and then gets the short clock', () => {
|
||||
let s = rigged(hands, undefined, { turnSeconds: null });
|
||||
// setup's own deadline was computed before rigging; a fresh turn shows the unlimited clock.
|
||||
s = go(s, 'A', { type: 'timeout' });
|
||||
expect(s.current).toBe('B');
|
||||
expect(s.deadlineAt).toBeNull();
|
||||
expect(clue.deadline!(s)).toBeNull();
|
||||
let r = inRoom(rigged(hands, undefined, { turnSeconds: null }), 'A', 'library');
|
||||
r = go(r, 'A', { type: 'suggest', suspect: 'mustard', weapon: 'rope' });
|
||||
expect(r.phase.kind).toBe('refute');
|
||||
expect(r.deadlineAt).toBeNull();
|
||||
let u = rigged(hands, undefined, { turnSeconds: null });
|
||||
u.out.C = true;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
u = go(u, 'A', { type: 'timeout' });
|
||||
u = go(u, 'B', { type: 'roll' });
|
||||
u = go(u, 'B', clue.legalActions!(u, 'B').find((a) => a.type === 'walk' || a.type === 'go')!);
|
||||
if (u.phase.kind === 'suggest') u = go(u, 'B', { type: 'end' });
|
||||
}
|
||||
expect(u.current).toBe('A');
|
||||
expect(u.deadlineAt).toBe(clock + 10_000);
|
||||
});
|
||||
|
||||
test('leaving: cards go face up, the answer chain and turns go on, the last one in the room wins', () => {
|
||||
let s = inRoom(rigged(hands), 'A', 'library');
|
||||
s = go(s, 'A', { type: 'suggest', suspect: 'green', weapon: 'rope' });
|
||||
@@ -407,7 +430,12 @@ describe('random games', () => {
|
||||
test('engine random playouts (secretsOf leak check, JSON round trip)', () => {
|
||||
for (let i = 0; i < playoutSeeds(60); i++) {
|
||||
const n = 3 + (i % 4);
|
||||
const r = randomPlayout(clue, { players: ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n), seed: seedN(i + 1), maxApplyMs: 50 });
|
||||
const r = randomPlayout(clue, {
|
||||
players: ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n),
|
||||
seed: seedN(i + 1),
|
||||
maxApplyMs: 50,
|
||||
...(i % 4 === 3 ? { options: clue.optionsSchema.parse({ turnSeconds: null }) } : {}),
|
||||
});
|
||||
expect(r.finished).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -66,11 +66,14 @@ function refreshDeadline(s: ClueState, now: number): void {
|
||||
s.deadlineAt = null;
|
||||
return;
|
||||
}
|
||||
const unlimited = s.options.turnSeconds === null;
|
||||
if (s.phase.kind === 'refute') {
|
||||
s.deadlineAt = now + REFUTE_MS;
|
||||
s.deadlineAt = unlimited ? null : now + REFUTE_MS;
|
||||
return;
|
||||
}
|
||||
s.deadlineAt = now + ((s.idle[s.current] ?? 0) >= IDLE_TURNS ? IDLE_MS : s.options.turnSeconds * 1000);
|
||||
// Someone who let the clock run out three turns in a row gets a short clock (무제한 too: only away players time out there).
|
||||
if ((s.idle[s.current] ?? 0) >= IDLE_TURNS) s.deadlineAt = now + IDLE_MS;
|
||||
else s.deadlineAt = unlimited ? null : now + s.options.turnSeconds! * 1000;
|
||||
}
|
||||
|
||||
function finish(s: ClueState, winner: PlayerId | null, reason: ClueFinal['reason'], events: GameEvent[]): void {
|
||||
|
||||
@@ -7,7 +7,7 @@ export * from './board';
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
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 clueOptionsSchema = z.object({
|
||||
@@ -15,9 +15,10 @@ export const clueOptionsSchema = z.object({
|
||||
.enum(['dice', 'free'])
|
||||
.default('dice')
|
||||
.meta({ title: '이동 방식', labels: { dice: '주사위 2개로 복도 이동(원작처럼)', free: '빠르게(아무 방이나 바로 이동)' } }),
|
||||
turnSeconds: lit(30, 45, 60, 90)
|
||||
/** null = 무제한: no clock on turns or on showing a card (only players away past the room's grace period are moved on). */
|
||||
turnSeconds: lit<30 | 45 | 60 | 90 | null>(30, 45, 60, 90, null)
|
||||
.default(60)
|
||||
.meta({ title: '차례 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', 90: '90초' } }),
|
||||
.meta({ title: '차례 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', 90: '90초', null: '무제한' } }),
|
||||
});
|
||||
export type ClueOptions = z.infer<typeof clueOptionsSchema>;
|
||||
|
||||
|
||||
@@ -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)', () => {
|
||||
|
||||
@@ -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). */
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -52,6 +52,18 @@ describe('whole games', () => {
|
||||
}, 60_000);
|
||||
}
|
||||
|
||||
test('모든 시간 무제한, 컴퓨터만: 설명·토론 끝내기·투표·맞히기를 해서 모두 끝나요', () => {
|
||||
const options = opts({ describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null });
|
||||
for (const n of [3, 5, 8, 10]) {
|
||||
const r = liveBotPlayout(liar, liarBot, { players: seats(n, 0), options, seed: seedN(900 + n), isBot });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.rejected).toEqual([]);
|
||||
const st = r.state as LiarState;
|
||||
expect(st.descriptions.every((d) => d.text !== null)).toBe(true);
|
||||
expect(r.elapsed).toBeGreaterThan(30_000);
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('컴퓨터는 토론 때 말하고, 라이어 컴퓨터는 자기를 지목하지 않아요', () => {
|
||||
for (let s = 1; s <= 10; s++) {
|
||||
const r = liveBotPlayout(liar, liarBot, { players: seats(6, 0), seed: seedN(300 + s), isBot });
|
||||
|
||||
@@ -130,6 +130,15 @@ function matchAll(m: TopicModel, text: string): Map<string, number> {
|
||||
|
||||
// ---------------------------------------------------------------- the bot
|
||||
|
||||
/** How a computer paces a 무제한 phase: like the default clock of that phase. */
|
||||
const UNLIMITED_PACE_MS: Record<Exclude<LiarView['phase']['kind'], 'ended'>, number> = {
|
||||
reveal: 10_000,
|
||||
describe: 30_000,
|
||||
discussion: 90_000,
|
||||
vote: 30_000,
|
||||
guess: 30_000,
|
||||
};
|
||||
|
||||
class LiarBot {
|
||||
readonly v: LiarView;
|
||||
readonly me: PlayerId;
|
||||
@@ -197,8 +206,11 @@ class LiarBot {
|
||||
return this.v.phase.startedAt;
|
||||
}
|
||||
|
||||
/** Phase length; 무제한 phases are paced like the default clock (so a computer neither rushes nor stalls). */
|
||||
private get phaseLen(): number {
|
||||
return Math.max(1000, (this.v.phase.endsAt ?? this.phaseStart) - this.phaseStart);
|
||||
const ph = this.v.phase;
|
||||
if (ph.endsAt === null && ph.kind !== 'ended') return UNLIMITED_PACE_MS[ph.kind];
|
||||
return Math.max(1000, (ph.endsAt ?? this.phaseStart) - this.phaseStart);
|
||||
}
|
||||
|
||||
/** `lo..hi` seconds into the phase (scaled by pace), never later than `cap` of it. */
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
*
|
||||
* Phases run on the server clock like 마피아: every phase has `endsAt`, and the room applies the system-only
|
||||
* `phaseTimeout` there (one "driver" player; `timeoutNotBefore` keeps an away driver from firing it early).
|
||||
* 무제한 phases (`endsAt` null) end when everyone needed is done; a player away past the room's grace period
|
||||
* is passed by their own `phaseTimeout` (넘김 / no vote / wrong guess).
|
||||
* 제시어 확인 → 차례대로 한 문장 설명(바퀴 수만큼, 두 번째 바퀴는 거꾸로) → 자유 토론 → 투표(동점이면 동점자끼리 재투표 한 번,
|
||||
* 또 동점이면 라이어 승리) → 지목된 사람이 라이어면 제시어 맞히기 → 결과.
|
||||
*
|
||||
@@ -97,6 +99,8 @@ function speakerOf(s: LiarState): PlayerId | null {
|
||||
/** The liar is known to everybody once accused (guess phase) or at the end. */
|
||||
const liarKnown = (s: LiarState) => s.phase.kind === 'guess' || s.final !== null;
|
||||
|
||||
const endsIn = (now: number, sec: number | null) => (sec === null ? null : now + sec * 1000);
|
||||
|
||||
/** Starts the describe turn at `turn` of `round` (skipping people who left), or the next round, or the discussion. */
|
||||
function nextTurn(s: LiarState, now: number, round: number, turn: number): void {
|
||||
for (let r = round; r <= s.options.rounds; r++) {
|
||||
@@ -104,17 +108,17 @@ function nextTurn(s: LiarState, now: number, round: number, turn: number): void
|
||||
for (let t = r === round ? turn : 0; t < order.length; t++) {
|
||||
if (!isPresent(s, order[t])) continue;
|
||||
const fresh = s.phase.kind !== 'describe' || s.phase.round !== r;
|
||||
s.phase = { kind: 'describe', startedAt: now, endsAt: now + s.options.describeSeconds * 1000, round: r, turn: t };
|
||||
s.phase = { kind: 'describe', startedAt: now, endsAt: endsIn(now, s.options.describeSeconds), round: r, turn: t };
|
||||
if (fresh) pushEvent(s, now, { t: 'phase', kind: 'describe', round: r });
|
||||
return;
|
||||
}
|
||||
}
|
||||
s.phase = { kind: 'discussion', startedAt: now, endsAt: now + s.options.discussionSeconds * 1000, ready: [] };
|
||||
s.phase = { kind: 'discussion', startedAt: now, endsAt: endsIn(now, s.options.discussionSeconds), ready: [] };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'discussion' });
|
||||
}
|
||||
|
||||
function startVote(s: LiarState, now: number, round: 1 | 2, candidates: PlayerId[]): void {
|
||||
s.phase = { kind: 'vote', startedAt: now, endsAt: now + s.options.voteSeconds * 1000, round, candidates, votes: {} };
|
||||
s.phase = { kind: 'vote', startedAt: now, endsAt: endsIn(now, s.options.voteSeconds), round, candidates, votes: {} };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'vote', round });
|
||||
}
|
||||
|
||||
@@ -128,7 +132,48 @@ function voteTargets(s: LiarState, voter: PlayerId): PlayerId[] {
|
||||
/** Present players who can vote (someone whose only candidate is themselves sits the revote out). */
|
||||
const voters = (s: LiarState) => present(s).filter((p) => voteTargets(s, p.id).length > 0);
|
||||
|
||||
const allVoted = (s: LiarState) => s.phase.kind === 'vote' && voters(s).every((p) => s.phase.kind === 'vote' && s.phase.votes[p.id] !== undefined);
|
||||
/** Has voted (or, 무제한, was passed while away). */
|
||||
const hasVoted = (ph: Extract<Phase, { kind: 'vote' }>, p: PlayerId) => ph.votes[p] !== undefined || (ph.passed ?? []).includes(p);
|
||||
const allVoted = (s: LiarState) => s.phase.kind === 'vote' && voters(s).every((p) => s.phase.kind === 'vote' && hasVoted(s.phase, p.id));
|
||||
|
||||
/** 무제한 phase: who it still waits for (the speaker, 토론 끝내기, votes, the liar's guess). */
|
||||
function awaited(s: LiarState): PlayerId[] {
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'ended' || ph.endsAt !== null) return [];
|
||||
switch (ph.kind) {
|
||||
case 'describe':
|
||||
return [speakerOf(s)!];
|
||||
case 'discussion':
|
||||
case 'reveal':
|
||||
return present(s)
|
||||
.filter((p) => !ph.ready.includes(p.id))
|
||||
.map((p) => p.id);
|
||||
case 'vote':
|
||||
return voters(s)
|
||||
.filter((p) => !hasVoted(ph, p.id))
|
||||
.map((p) => p.id);
|
||||
case 'guess':
|
||||
return [s.liar];
|
||||
}
|
||||
}
|
||||
|
||||
/** 무제한: the room moved on for `p` (away past the grace period). */
|
||||
function pass(s: LiarState, now: number, p: PlayerId): void {
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'discussion':
|
||||
ph.ready.push(p);
|
||||
if (present(s).every((x) => ph.ready.includes(x.id))) advance(s, now);
|
||||
return;
|
||||
case 'vote':
|
||||
(ph.passed ??= []).push(p);
|
||||
if (allVoted(s)) resolveVote(s, now);
|
||||
return;
|
||||
default:
|
||||
// describe: the speaker's turn is 넘김; guess: no answer (wrong).
|
||||
advance(s, now);
|
||||
}
|
||||
}
|
||||
|
||||
function finish(s: LiarState, now: number, winner: 'liar' | 'citizens', reason: WinReason): void {
|
||||
const word = s.word;
|
||||
@@ -176,7 +221,7 @@ function resolveVote(s: LiarState, now: number): void {
|
||||
const isLiar = accused === s.liar;
|
||||
pushEvent(s, now, { t: 'accused', p: accused, liar: isLiar });
|
||||
if (!isLiar) return finish(s, now, 'liar', 'escaped');
|
||||
s.phase = { kind: 'guess', startedAt: now, endsAt: now + s.options.guessSeconds * 1000 };
|
||||
s.phase = { kind: 'guess', startedAt: now, endsAt: endsIn(now, s.options.guessSeconds) };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'guess' });
|
||||
}
|
||||
|
||||
@@ -273,6 +318,8 @@ function validate(s: LiarState, actor: PlayerId, a: LiarAction, ctx?: { now: num
|
||||
if (s.final || ph.kind === 'ended') return fail('게임이 이미 끝났어요.');
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
// 무제한: only for someone the phase waits on (the room passes a player away past the grace period).
|
||||
if (ph.endsAt === null) return awaited(s).includes(actor) ? ok : fail('아직 기다리는 중이에요.');
|
||||
return ctx && ctx.now < ph.endsAt ? fail('아직 시간이 남았어요.') : ok;
|
||||
case 'leave':
|
||||
return p.left ? fail('이미 나갔어요.') : ok;
|
||||
@@ -359,7 +406,7 @@ function view(s: LiarState, viewer: PlayerId | null): LiarView {
|
||||
readyNeeded: readyPhase ? present(s).length : 0,
|
||||
voteRound: ph.kind === 'vote' ? ph.round : null,
|
||||
candidates: ph.kind === 'vote' ? [...ph.candidates] : [],
|
||||
votedCount: ph.kind === 'vote' ? Object.keys(ph.votes).length : 0,
|
||||
votedCount: ph.kind === 'vote' ? voters(s).filter((p) => hasVoted(ph, p.id)).length : 0,
|
||||
liar: ph.kind === 'guess' ? s.liar : null,
|
||||
choices: ph.kind === 'guess' && s.options.guessMode === 'choice' ? topicById(s.topic).words.map((x) => x.word).sort((a, b) => a.localeCompare(b, 'ko')) : [],
|
||||
},
|
||||
@@ -368,7 +415,7 @@ function view(s: LiarState, viewer: PlayerId | null): LiarView {
|
||||
players: s.players.map((p) => ({
|
||||
id: p.id,
|
||||
left: p.left,
|
||||
voted: ph.kind === 'vote' && ph.votes[p.id] !== undefined,
|
||||
voted: ph.kind === 'vote' && hasVoted(ph, p.id),
|
||||
liar: known ? p.id === s.liar : null,
|
||||
})),
|
||||
descriptions: s.descriptions.map((d) => ({ ...d })),
|
||||
@@ -392,7 +439,7 @@ function activePlayers(s: LiarState): PlayerId[] {
|
||||
return [s.liar];
|
||||
case 'vote':
|
||||
return voters(s)
|
||||
.filter((p) => ph.votes[p.id] === undefined)
|
||||
.filter((p) => !hasVoted(ph, p.id))
|
||||
.map((p) => p.id);
|
||||
default:
|
||||
return present(s).map((p) => p.id);
|
||||
@@ -455,7 +502,8 @@ export const liar: Def = {
|
||||
const ph = s.phase;
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
advance(s, now);
|
||||
if (ph.kind !== 'ended' && ph.endsAt === null) pass(s, now, actor);
|
||||
else advance(s, now);
|
||||
break;
|
||||
case 'leave':
|
||||
leave(s, now, p);
|
||||
@@ -498,9 +546,10 @@ export const liar: Def = {
|
||||
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
|
||||
},
|
||||
|
||||
/** One player drives the phase clock (the deadline is shared by everybody). */
|
||||
/** One player drives the phase clock (the deadline is shared by everybody); 무제한: those still awaited (only the away ones time out). */
|
||||
timeoutPlayers(s) {
|
||||
return s.phase.kind === 'ended' ? [] : [s.players[0]!.id];
|
||||
if (s.phase.kind === 'ended') return [];
|
||||
return s.phase.endsAt === null ? awaited(s) : [s.players[0]!.id];
|
||||
},
|
||||
|
||||
/** An away driver must not end a phase early. */
|
||||
@@ -540,7 +589,7 @@ export const liar: Def = {
|
||||
const p = P(s, player);
|
||||
if (!p || s.final || s.phase.kind === 'ended') return [];
|
||||
const out: LiarAction[] = [{ type: 'phaseTimeout' }];
|
||||
if (p.left) return out;
|
||||
if (p.left) return out.filter((a) => validate(s, player, a).ok);
|
||||
const me = myView(s, p);
|
||||
if (me.canChat) out.push({ type: 'chat', text: `m${s.seq}-${player}` });
|
||||
if (me.canReady) out.push({ type: 'ready' });
|
||||
|
||||
@@ -52,7 +52,7 @@ function reject(s: LiarState, actor: PlayerId, a: LiarAction, now?: number): str
|
||||
}
|
||||
const tick = (s: LiarState) => {
|
||||
if (s.phase.kind === 'ended') throw new Error('tick after the end');
|
||||
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt);
|
||||
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt!);
|
||||
};
|
||||
function until(s: LiarState, kind: LiarState['phase']['kind']): LiarState {
|
||||
for (let i = 0; i < 60 && s.phase.kind !== kind && s.phase.kind !== 'ended'; i++) s = tick(s);
|
||||
@@ -231,7 +231,7 @@ describe('차례대로 설명 (§5.2)', () => {
|
||||
|
||||
test('한 바퀴 옵션, 시간 초과는 넘김, 설명은 80자까지', () => {
|
||||
let s = tick(rig(3, { rounds: 1, describeSeconds: 15 }));
|
||||
expect(s.phase.kind === 'describe' && s.phase.endsAt - s.phase.startedAt).toBe(15_000);
|
||||
expect(s.phase.kind === 'describe' && s.phase.endsAt! - s.phase.startedAt).toBe(15_000);
|
||||
expect(reject(s, 'P0', { type: 'chat', text: '가'.repeat(81) })).toContain('80자');
|
||||
s = tick(s);
|
||||
expect(s.descriptions[0]).toMatchObject({ from: 'P0', text: null });
|
||||
@@ -381,6 +381,54 @@ describe('나가기 (§8.5)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('시간 무제한 (§8.5)', () => {
|
||||
const U = { describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null };
|
||||
|
||||
test('설명·토론·투표·맞히기 모두 무제한: 마감 없이 할 일을 마칠 때까지, 기다리는 사람만 시간 초과 대상', () => {
|
||||
let s = tick(rig(3, { ...U, rounds: 1 }));
|
||||
expect(s.phase.kind === 'describe' && s.phase.endsAt).toBeNull();
|
||||
expect(liar.deadline!(s)).toBeNull();
|
||||
expect(liar.timeoutPlayers!(s)).toEqual(['P0']);
|
||||
expect(reject(s, 'P1', { type: 'phaseTimeout' })).toBe('아직 기다리는 중이에요.');
|
||||
for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'chat', text: `${p} 설명` }, T0 + 3_600_000);
|
||||
expect(s.phase.kind).toBe('discussion');
|
||||
expect(liar.timeoutPlayers!(s)).toEqual(['P0', 'P1', 'P2']);
|
||||
for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'ready' });
|
||||
expect(s.phase.kind).toBe('vote');
|
||||
s = votes(s, { P0: 'P2', P1: 'P2' });
|
||||
expect(liar.timeoutPlayers!(s)).toEqual(['P2']);
|
||||
s = act(s, 'P2', { type: 'vote', target: 'P0' });
|
||||
expect(s.phase.kind).toBe('guess');
|
||||
expect(liar.timeoutPlayers!(s)).toEqual(['P2']);
|
||||
s = act(s, 'P2', { type: 'guess', text: '수박' }, T0 + 7_200_000);
|
||||
expect(s.final!.reason).toBe('guessed');
|
||||
});
|
||||
|
||||
test('자리 비운 사람은 방의 유예 시간 뒤 자기 차례만 넘김: 설명 넘김·토론 끝·표 없음·답 없음', () => {
|
||||
let s = tick(rig(4, { ...U, rounds: 1 }));
|
||||
s = act(s, 'P0', liar.onTimeout(s, 'P0'));
|
||||
expect(s.descriptions[0]).toMatchObject({ from: 'P0', text: null });
|
||||
for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'chat', text: `${p} 설명` });
|
||||
for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'ready' });
|
||||
s = act(s, 'P0', liar.onTimeout(s, 'P0'));
|
||||
expect(s.phase.kind).toBe('vote');
|
||||
s = votes(s, { P1: 'P3', P2: 'P3', P3: 'P1' });
|
||||
expect(liar.view(s, null).players.find((p) => p.id === 'P0')!.voted).toBe(false);
|
||||
s = act(s, 'P0', liar.onTimeout(s, 'P0'));
|
||||
expect(lastEv(s, 'vote')).toMatchObject({ accused: 'P3', votes: { P1: 'P3', P2: 'P3', P3: 'P1' } });
|
||||
s = act(s, 'P3', liar.onTimeout(s, 'P3'));
|
||||
expect(s.final).toMatchObject({ winner: 'citizens', reason: 'caught', guess: null });
|
||||
});
|
||||
|
||||
test('무작위 대국(모두 무제한)도 끝나요', () => {
|
||||
for (let k = 1; k <= playoutSeeds(40); k++) {
|
||||
const n = 3 + (k % 8);
|
||||
const r = randomPlayout(liar, { players: ids(n), options: opts(U), seed: seedN(5000 + k), maxSteps: 3000 });
|
||||
expect(r.finished).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- engine checks
|
||||
|
||||
describe('무작위 대국 (엔진 공통 검사)', () => {
|
||||
|
||||
@@ -5,9 +5,11 @@ import { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics';
|
||||
|
||||
export { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics';
|
||||
|
||||
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>[]]);
|
||||
const secLabels = (...vals: number[]) => Object.fromEntries(vals.map((v) => [v, `${v}초`]));
|
||||
/** Labels plus 무제한 (null): that phase has no clock (§8.5). */
|
||||
const secLabelsU = (unl: string, ...vals: number[]) => ({ ...secLabels(...vals), null: unl });
|
||||
|
||||
export const liarOptionsSchema = z.object({
|
||||
topic: z
|
||||
@@ -18,22 +20,23 @@ export const liarOptionsSchema = z.object({
|
||||
rounds: lit(1, 2)
|
||||
.default(2)
|
||||
.meta({ title: '설명 바퀴 수', labels: { 1: '한 바퀴', 2: '두 바퀴(두 번째는 거꾸로)' } }),
|
||||
describeSeconds: lit(15, 20, 30, 45, 60)
|
||||
/** null = 무제한 (each such phase ends when everyone needed is done; away players are passed after the room's grace period). */
|
||||
describeSeconds: lit<15 | 20 | 30 | 45 | 60 | null>(15, 20, 30, 45, 60, null)
|
||||
.default(30)
|
||||
.meta({ title: '한 사람 설명 시간', labels: secLabels(15, 20, 30, 45, 60) }),
|
||||
discussionSeconds: lit(30, 60, 90, 120, 180)
|
||||
.meta({ title: '한 사람 설명 시간', labels: secLabelsU('무제한(설명을 보낼 때까지)', 15, 20, 30, 45, 60) }),
|
||||
discussionSeconds: lit<30 | 60 | 90 | 120 | 180 | null>(30, 60, 90, 120, 180, null)
|
||||
.default(90)
|
||||
.meta({ title: '자유 토론 시간', labels: secLabels(30, 60, 90, 120, 180) }),
|
||||
voteSeconds: lit(15, 20, 30, 45)
|
||||
.meta({ title: '자유 토론 시간', labels: secLabelsU('무제한(모두 토론 끝내기를 누를 때까지)', 30, 60, 90, 120, 180) }),
|
||||
voteSeconds: lit<15 | 20 | 30 | 45 | null>(15, 20, 30, 45, null)
|
||||
.default(30)
|
||||
.meta({ title: '투표 시간', labels: secLabels(15, 20, 30, 45) }),
|
||||
.meta({ title: '투표 시간', labels: secLabelsU('무제한(모두 투표할 때까지)', 15, 20, 30, 45) }),
|
||||
guessMode: z
|
||||
.enum(['text', 'choice'])
|
||||
.default('text')
|
||||
.meta({ title: '라이어의 정답 맞히기', labels: { text: '직접 적기', choice: '주제 단어 목록에서 고르기' } }),
|
||||
guessSeconds: lit(20, 30, 45, 60)
|
||||
guessSeconds: lit<20 | 30 | 45 | 60 | null>(20, 30, 45, 60, null)
|
||||
.default(30)
|
||||
.meta({ title: '정답 맞히기 시간', labels: secLabels(20, 30, 45, 60) }),
|
||||
.meta({ title: '정답 맞히기 시간', labels: secLabelsU('무제한(라이어가 답할 때까지)', 20, 30, 45, 60) }),
|
||||
kidSafeChat: z.boolean().default(true).meta({ title: '고운 말 필터(욕설·링크·전화번호 막기)' }),
|
||||
});
|
||||
export type LiarOptions = z.infer<typeof liarOptionsSchema>;
|
||||
@@ -54,10 +57,12 @@ export type LiarAction = LiarClientAction | { type: 'phaseTimeout' } | { type: '
|
||||
|
||||
export type Phase =
|
||||
| { kind: 'reveal'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'describe'; startedAt: number; endsAt: number; round: number; turn: number }
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number; round: 1 | 2; candidates: PlayerId[]; votes: Record<PlayerId, PlayerId> }
|
||||
| { kind: 'guess'; startedAt: number; endsAt: number }
|
||||
// endsAt null = 무제한: describe/guess wait for the speaker/liar, discussion for everyone's 「투표하자」, vote for every vote.
|
||||
| { kind: 'describe'; startedAt: number; endsAt: number | null; round: number; turn: number }
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number | null; ready: PlayerId[] }
|
||||
/** `passed`: 무제한 only, voters the room moved on while away (no vote). */
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number | null; round: 1 | 2; candidates: PlayerId[]; votes: Record<PlayerId, PlayerId>; passed?: PlayerId[] }
|
||||
| { kind: 'guess'; startedAt: number; endsAt: number | null }
|
||||
| { kind: 'ended' };
|
||||
export type PhaseKind = Phase['kind'];
|
||||
|
||||
|
||||
@@ -64,6 +64,17 @@ describe('whole games', () => {
|
||||
}, 60_000);
|
||||
}
|
||||
|
||||
test('every phase 무제한, computers only: they press 토론 끝내기·밤 마치기·반론 마치기 and vote, so every game ends', () => {
|
||||
const options = opts({ discussionPerAlive: null, voteSeconds: null, defenseSeconds: null, confirmSeconds: null, nightSeconds: null });
|
||||
for (const n of [4, 6, 9, 12]) {
|
||||
const r = liveBotPlayout(mafia, mafiaBot, { players: seats(n, 0), options, seed: seedN(700 + n), isBot });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.rejected).toEqual([]);
|
||||
// Paced like the default clocks: neither instant nor endless.
|
||||
expect(r.elapsed).toBeGreaterThan(60_000);
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('a mafia computer never points at its own team in the day chat', () => {
|
||||
for (let s = 1; s <= 12; s++) {
|
||||
const r = liveBotPlayout(mafia, mafiaBot, { players: seats(8, 0), seed: seedN(500 + s), isBot });
|
||||
@@ -118,7 +129,7 @@ describe('timing and answers', () => {
|
||||
const rng = SeededRng.fromSeed(seedN(10));
|
||||
let now = 0;
|
||||
while (st.phase.kind !== kind) {
|
||||
now = st.phase.kind === 'ended' ? now : st.phase.endsAt;
|
||||
now = st.phase.kind === 'ended' ? now : st.phase.endsAt!;
|
||||
st = mafia.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng, now }).state;
|
||||
}
|
||||
return { st, now, rng, players };
|
||||
@@ -131,7 +142,7 @@ describe('timing and answers', () => {
|
||||
const quick = firstAction(st, bot, { smart: true, pace: 0.7, chatty: 0.8 }, names, 'vote')!;
|
||||
const slow = firstAction(st, bot, { smart: true, pace: 1.5, chatty: 0.8 }, names, 'vote')!;
|
||||
expect(quick.at).toBeLessThan(slow.at);
|
||||
expect(slow.at).toBeLessThan(st.options.voteSeconds * 1000);
|
||||
expect(slow.at).toBeLessThan(st.options.voteSeconds! * 1000);
|
||||
});
|
||||
|
||||
test('asked "컴퓨터 3 직업 뭐야?", computer 3 answers within seconds — and a mafia says it is a citizen', () => {
|
||||
|
||||
@@ -148,6 +148,17 @@ interface Mention {
|
||||
tail: string;
|
||||
}
|
||||
|
||||
/** How a computer paces a 무제한 phase: like the default clock of that phase. */
|
||||
const UNLIMITED_PACE_MS: Record<Exclude<MafiaView['phase']['kind'], 'ended'>, number> = {
|
||||
roleReveal: 8_000,
|
||||
greeting: 60_000,
|
||||
discussion: 90_000,
|
||||
vote: 20_000,
|
||||
defense: 20_000,
|
||||
confirm: 10_000,
|
||||
night: 30_000,
|
||||
};
|
||||
|
||||
class Reader {
|
||||
readonly v: MafiaView;
|
||||
readonly me: PlayerId;
|
||||
@@ -305,8 +316,11 @@ class MafiaBot {
|
||||
return this.v.phase.startedAt;
|
||||
}
|
||||
|
||||
/** Phase length; 무제한 phases are paced like the default clock (so a computer neither rushes nor stalls). */
|
||||
private get phaseLen(): number {
|
||||
return Math.max(1000, (this.v.phase.endsAt ?? this.phaseStart) - this.phaseStart);
|
||||
const ph = this.v.phase;
|
||||
if (ph.endsAt === null && ph.kind !== 'ended') return UNLIMITED_PACE_MS[ph.kind];
|
||||
return Math.max(1000, (ph.endsAt ?? this.phaseStart) - this.phaseStart);
|
||||
}
|
||||
|
||||
/** A moment inside the phase: `lo..hi` seconds after it started (scaled by pace), never later than `cap` of it. */
|
||||
@@ -512,6 +526,8 @@ class MafiaBot {
|
||||
if (k === 'defense' && v.phase.accused === this.me) {
|
||||
out.push({ key: key('def1'), due: this.inPhase(1.5, 4, 'def1'), make: () => this.say('day', this.defenseLine(true)) });
|
||||
if (this.smart || this.h('def2', v.day) < 0.5) out.push({ key: key('def2'), due: this.inPhase(7, 12, 'def2', 0.75), make: () => this.say('day', this.defenseLine(false)) });
|
||||
// 무제한: 반론 마치기 after the last line.
|
||||
if (this.my.canReady) out.push({ key: key('defEnd'), due: this.inPhase(13, 17, 'defEnd', 0.95), make: () => ({ type: 'readyEarly' }) });
|
||||
}
|
||||
|
||||
if (k === 'confirm' && this.my.canConfirm && this.my.ballot === null) {
|
||||
@@ -530,6 +546,8 @@ class MafiaBot {
|
||||
}
|
||||
|
||||
if (k === 'night') out.push(...this.night(key));
|
||||
// 무제한 night: 밤 마치기 after the night action (its latest time is earlier for the same pace).
|
||||
if (k === 'night' && this.my.canReady) out.push({ key: key('nready'), due: this.inPhase(18, 24, 'nready', 0.95), make: () => ({ type: 'readyEarly' }) });
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
*
|
||||
* The server runs the phases: every phase has `endsAt`; the room timer applies the system-only
|
||||
* `phaseTimeout` there (one "driver" player, `timeoutNotBefore` keeps away players from firing it
|
||||
* early). Chat lives in the state and the view filters it by channel permission (§5.6, §8.3).
|
||||
* early). 무제한 phases (`endsAt` null) end when everyone needed is done instead; a player away past the
|
||||
* room's grace period is passed by their own `phaseTimeout`. Chat lives in the state and the view filters
|
||||
* it by channel permission (§5.6, §8.3).
|
||||
*/
|
||||
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine';
|
||||
import {
|
||||
@@ -126,13 +128,73 @@ const alive = (s: MafiaState) => s.players.filter((p) => p.alive);
|
||||
const isAlive = (s: MafiaState, id: PlayerId | null) => !!id && !!P(s, id)?.alive;
|
||||
type NightPhase = Extract<Phase, { kind: 'night' }>;
|
||||
|
||||
function discussionMs(s: MafiaState): number {
|
||||
/** Discussion length; null = 무제한. */
|
||||
function discussionMs(s: MafiaState): number | null {
|
||||
const o = s.options;
|
||||
if (o.discussionPerAlive === null) return null;
|
||||
const lo = o.discussionMin;
|
||||
const hi = Math.max(o.discussionMin, o.discussionMax);
|
||||
return Math.min(hi, Math.max(lo, alive(s).length * o.discussionPerAlive)) * 1000;
|
||||
}
|
||||
|
||||
const ends = (now: number, ms: number | null) => (ms === null ? null : now + ms);
|
||||
const endsIn = (now: number, sec: number | null) => (sec === null ? null : now + sec * 1000);
|
||||
|
||||
/** 무제한 phase: the living players it still waits for (votes, ballots, 토론 끝내기 / 밤 마치기, the accused's 반론 마치기). */
|
||||
function awaited(s: MafiaState): PlayerId[] {
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'ended' || ph.endsAt !== null) return [];
|
||||
const live = alive(s).map((p) => p.id);
|
||||
switch (ph.kind) {
|
||||
case 'greeting':
|
||||
case 'discussion':
|
||||
return live.filter((p) => !ph.ready.includes(p));
|
||||
case 'night':
|
||||
return live.filter((p) => !(ph.ready ?? []).includes(p));
|
||||
case 'vote':
|
||||
return live.filter((p) => ph.votes[p] === undefined);
|
||||
case 'defense':
|
||||
return isAlive(s, ph.accused) ? [ph.accused] : [];
|
||||
case 'confirm':
|
||||
return live.filter((p) => p !== ph.accused && ph.ballots[p] === undefined && !(ph.passed ?? []).includes(p));
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** 무제한: the phase ends once nobody is awaited. */
|
||||
function settle(s: MafiaState, now: number, rng: Rng): void {
|
||||
const ph = s.phase;
|
||||
if (s.winner || ph.kind === 'ended' || ph.endsAt !== null || ph.kind === 'roleReveal') return;
|
||||
if (awaited(s).length === 0) advance(s, now, rng);
|
||||
}
|
||||
|
||||
/** 무제한: the room moved on for `p` (away past the grace period): no vote / no ballot / done. */
|
||||
function pass(s: MafiaState, now: number, rng: Rng, p: PlayerId): void {
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'greeting':
|
||||
case 'discussion':
|
||||
if (!ph.ready.includes(p)) ph.ready.push(p);
|
||||
break;
|
||||
case 'night':
|
||||
(ph.ready ??= []).push(p);
|
||||
break;
|
||||
case 'vote':
|
||||
ph.votes[p] = 'abstain';
|
||||
break;
|
||||
case 'defense':
|
||||
advance(s, now, rng);
|
||||
return;
|
||||
case 'confirm':
|
||||
(ph.passed ??= []).push(p);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
settle(s, now, rng);
|
||||
}
|
||||
|
||||
function pushEvent(s: MafiaState, now: number, e: DistributiveOmit<PublicEvent, 'n' | 'at' | 'day'>, day = s.day): void {
|
||||
s.events.push({ ...e, n: s.events.length + 1, at: now, day } as PublicEvent);
|
||||
}
|
||||
@@ -144,13 +206,14 @@ function startPhase(s: MafiaState, now: number, kind: 'greeting' | 'discussion'
|
||||
s.phase = { kind, startedAt: now, endsAt: now + GREETING_MS, ready: [] };
|
||||
break;
|
||||
case 'discussion':
|
||||
s.phase = { kind, startedAt: now, endsAt: now + discussionMs(s), adjustedBy: [], ready: [] };
|
||||
s.phase = { kind, startedAt: now, endsAt: ends(now, discussionMs(s)), adjustedBy: [], ready: [] };
|
||||
break;
|
||||
case 'vote':
|
||||
s.phase = { kind, startedAt: now, endsAt: now + s.options.voteSeconds * 1000, votes: {} };
|
||||
s.phase = { kind, startedAt: now, endsAt: endsIn(now, s.options.voteSeconds), votes: {} };
|
||||
break;
|
||||
case 'night':
|
||||
s.phase = { kind, startedAt: now, endsAt: now + s.options.nightSeconds * 1000, mafiaTarget: null, mafiaPickedBy: null, investigate: null, heal: null, mediumPeek: null };
|
||||
s.phase = { kind, startedAt: now, endsAt: endsIn(now, s.options.nightSeconds), mafiaTarget: null, mafiaPickedBy: null, investigate: null, heal: null, mediumPeek: null };
|
||||
if (s.phase.endsAt === null) s.phase.ready = [];
|
||||
break;
|
||||
}
|
||||
pushEvent(s, now, { t: 'phase', kind });
|
||||
@@ -318,7 +381,7 @@ function advance(s: MafiaState, now: number, rng: Rng): void {
|
||||
case 'vote': {
|
||||
const accused = resolveVote(s, now);
|
||||
if (accused) {
|
||||
s.phase = { kind: 'defense', startedAt: now, endsAt: now + s.options.defenseSeconds * 1000, accused };
|
||||
s.phase = { kind: 'defense', startedAt: now, endsAt: endsIn(now, s.options.defenseSeconds), accused };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'defense' });
|
||||
return;
|
||||
}
|
||||
@@ -326,7 +389,7 @@ function advance(s: MafiaState, now: number, rng: Rng): void {
|
||||
return;
|
||||
}
|
||||
case 'defense':
|
||||
s.phase = { kind: 'confirm', startedAt: now, endsAt: now + s.options.confirmSeconds * 1000, accused: ph.accused, ballots: {} };
|
||||
s.phase = { kind: 'confirm', startedAt: now, endsAt: endsIn(now, s.options.confirmSeconds), accused: ph.accused, ballots: {} };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'confirm' });
|
||||
return;
|
||||
case 'confirm':
|
||||
@@ -450,6 +513,8 @@ function validate(s: MafiaState, actor: PlayerId, a: MafiaAction, ctx?: { now: n
|
||||
if (ph.kind === 'ended') return fail('게임이 이미 끝났어요.');
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
// 무제한: only for someone the phase waits on (the room passes a player away past the grace period).
|
||||
if (ph.endsAt === null) return awaited(s).includes(actor) ? ok : fail('아직 기다리는 중이에요.');
|
||||
return ctx && ctx.now < ph.endsAt ? fail('아직 시간이 남았어요.') : ok;
|
||||
case 'leave':
|
||||
return p.alive ? ok : fail('이미 탈락했어요.');
|
||||
@@ -470,9 +535,12 @@ function validate(s: MafiaState, actor: PlayerId, a: MafiaAction, ctx?: { now: n
|
||||
case 'adjustTime':
|
||||
if (ph.kind !== 'discussion') return fail('토론 시간에만 시간을 바꿀 수 있어요.');
|
||||
if (!s.options.timeAdjust) return fail('이 방은 토론 시간을 바꿀 수 없어요.');
|
||||
if (ph.endsAt === null) return fail('이 방은 토론 시간이 무제한이에요.');
|
||||
if (ph.adjustedBy.includes(actor)) return fail('시간 바꾸기는 하루에 한 번만 할 수 있어요.');
|
||||
return a.delta === 15 || a.delta === -15 ? ok : fail('15초씩만 바꿀 수 있어요.');
|
||||
case 'readyEarly':
|
||||
if (ph.kind === 'night' && ph.endsAt === null) return (ph.ready ?? []).includes(actor) ? fail('이미 밤 마치기를 눌렀어요.') : ok;
|
||||
if (ph.kind === 'defense' && ph.endsAt === null) return ph.accused === actor ? ok : fail('지목된 사람만 반론을 마칠 수 있어요.');
|
||||
if (ph.kind !== 'discussion' && ph.kind !== 'greeting') return fail('지금은 토론 시간이 아니에요.');
|
||||
return ph.ready.includes(actor) ? fail('이미 토론 끝내기를 눌렀어요.') : ok;
|
||||
case 'vote':
|
||||
@@ -534,6 +602,8 @@ function myView(s: MafiaState, me: PlayerState): MyView {
|
||||
const ph = s.phase;
|
||||
const mates = me.role === 'mafia' || me.role === 'lover' ? s.players.filter((p) => p.role === me.role && p.id !== me.id).map((p) => p.id) : [];
|
||||
const day = ph.kind === 'greeting' || ph.kind === 'discussion';
|
||||
const nightReady = ph.kind === 'night' && ph.endsAt === null ? (ph.ready ?? []) : null;
|
||||
const defenseEnd = ph.kind === 'defense' && ph.endsAt === null && ph.accused === me.id;
|
||||
return {
|
||||
role: me.role,
|
||||
team: teamOf(me.role),
|
||||
@@ -543,15 +613,24 @@ function myView(s: MafiaState, me: PlayerState): MyView {
|
||||
voteTargets: ph.kind === 'vote' && me.alive ? alive(s).filter((p) => p.id !== me.id).map((p) => p.id) : [],
|
||||
ballot: ph.kind === 'confirm' && me.alive ? (ph.ballots[me.id] ?? null) : null,
|
||||
canConfirm: ph.kind === 'confirm' && me.alive && ph.accused !== me.id,
|
||||
canAdjust: ph.kind === 'discussion' && me.alive && s.options.timeAdjust && !ph.adjustedBy.includes(me.id),
|
||||
canReady: day && me.alive && !ph.ready.includes(me.id),
|
||||
ready: day && ph.ready.includes(me.id),
|
||||
canAdjust: ph.kind === 'discussion' && ph.endsAt !== null && me.alive && s.options.timeAdjust && !ph.adjustedBy.includes(me.id),
|
||||
canReady: me.alive && ((day && !ph.ready.includes(me.id)) || (nightReady !== null && !nightReady.includes(me.id)) || defenseEnd),
|
||||
ready: (day && ph.ready.includes(me.id)) || (nightReady?.includes(me.id) ?? false),
|
||||
night: ph.kind === 'night' && me.alive ? nightView(s, me) : null,
|
||||
results: s.privateResults.filter((r) => r.to === me.id),
|
||||
idleWarning: me.alive && !s.winner && me.idleDays >= AWAY_DAYS - 1 && !me.activeToday,
|
||||
};
|
||||
}
|
||||
|
||||
/** Ready / done counts for the phase banner (무제한 vote, ballots and night too). */
|
||||
function doneCounts(s: MafiaState, day: boolean): { readyCount: number; readyNeeded: number } {
|
||||
const ph = s.phase;
|
||||
if (day && (ph.kind === 'greeting' || ph.kind === 'discussion')) return { readyCount: ph.ready.length, readyNeeded: alive(s).length };
|
||||
if (ph.kind === 'ended' || ph.endsAt !== null || (ph.kind !== 'vote' && ph.kind !== 'confirm' && ph.kind !== 'night')) return { readyCount: 0, readyNeeded: 0 };
|
||||
const need = ph.kind === 'confirm' ? alive(s).filter((p) => p.id !== ph.accused).length : alive(s).length;
|
||||
return { readyCount: need - awaited(s).length, readyNeeded: need };
|
||||
}
|
||||
|
||||
function view(s: MafiaState, viewer: PlayerId | null): MafiaView {
|
||||
const me = viewer ? (P(s, viewer) ?? null) : null;
|
||||
const ph = s.phase;
|
||||
@@ -573,8 +652,7 @@ function view(s: MafiaState, viewer: PlayerId | null): MafiaView {
|
||||
endsAt: ph.kind === 'ended' ? null : ph.endsAt,
|
||||
accused: ph.kind === 'defense' || ph.kind === 'confirm' ? ph.accused : null,
|
||||
adjustedBy: ph.kind === 'discussion' ? [...ph.adjustedBy] : [],
|
||||
readyCount: day ? ph.ready.length : 0,
|
||||
readyNeeded: day ? alive(s).length : 0,
|
||||
...doneCounts(s, day),
|
||||
},
|
||||
players: s.players.map((p) => {
|
||||
const known = roleKnown(s, p, me);
|
||||
@@ -661,7 +739,8 @@ export const mafia: Def = {
|
||||
if (a.type !== 'phaseTimeout' && a.type !== 'leave') p.activeToday = true;
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
advance(s, now, rng);
|
||||
if (ph.kind !== 'ended' && ph.endsAt === null) pass(s, now, rng, actor);
|
||||
else advance(s, now, rng);
|
||||
break;
|
||||
case 'leave':
|
||||
leave(s, now, rng, p);
|
||||
@@ -676,10 +755,19 @@ export const mafia: Def = {
|
||||
case 'adjustTime':
|
||||
if (ph.kind !== 'discussion') throw new Error('mafia: adjustTime outside discussion');
|
||||
ph.adjustedBy.push(actor);
|
||||
if (ph.endsAt === null) throw new Error('mafia: adjustTime in a 무제한 discussion');
|
||||
ph.endsAt = a.delta > 0 ? ph.endsAt + ADJUST_MS : Math.max(ph.endsAt - ADJUST_MS, Math.min(ph.endsAt, now + ADJUST_FLOOR_MS));
|
||||
pushEvent(s, now, { t: 'adjust', p: actor, delta: a.delta });
|
||||
break;
|
||||
case 'readyEarly':
|
||||
if (ph.kind === 'defense') {
|
||||
advance(s, now, rng);
|
||||
break;
|
||||
}
|
||||
if (ph.kind === 'night') {
|
||||
(ph.ready ??= []).push(actor);
|
||||
break;
|
||||
}
|
||||
if (ph.kind !== 'discussion' && ph.kind !== 'greeting') throw new Error('mafia: readyEarly outside discussion');
|
||||
ph.ready.push(actor);
|
||||
if (alive(s).every((x) => ph.ready.includes(x.id))) advance(s, now, rng);
|
||||
@@ -704,6 +792,7 @@ export const mafia: Def = {
|
||||
ph[a.type] = a.target;
|
||||
break;
|
||||
}
|
||||
if (a.type !== 'chat') settle(s, now, rng);
|
||||
// Only public announcements become events (chat and night choices stay in the filtered view).
|
||||
const events: GameEvent[] = s.events.slice(before).map((e) => ({ ...e, type: e.t }));
|
||||
return { state: s, events };
|
||||
@@ -717,9 +806,10 @@ export const mafia: Def = {
|
||||
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
|
||||
},
|
||||
|
||||
/** One player drives the phase clock (the deadline is shared by everybody). */
|
||||
/** One player drives the phase clock (the deadline is shared by everybody); 무제한: those still awaited (only the away ones time out). */
|
||||
timeoutPlayers(s) {
|
||||
return s.phase.kind === 'ended' ? [] : [s.players[0]!.id];
|
||||
if (s.phase.kind === 'ended') return [];
|
||||
return s.phase.endsAt === null ? awaited(s) : [s.players[0]!.id];
|
||||
},
|
||||
|
||||
/** An away driver must not end a phase early. */
|
||||
@@ -756,7 +846,7 @@ export const mafia: Def = {
|
||||
if (!p || s.winner || s.phase.kind === 'ended') return [];
|
||||
const out: MafiaAction[] = [{ type: 'phaseTimeout' }];
|
||||
for (const ch of CHANNELS) if (!writeBlock(s, p, ch)) out.push({ type: 'chat', channel: ch, text: `m${s.seq}-${player}-${ch}` });
|
||||
if (!p.alive) return out;
|
||||
if (!p.alive) return out.filter((a) => validate(s, player, a).ok);
|
||||
const ph = s.phase;
|
||||
const me = myView(s, p);
|
||||
if (me.canReady) out.push({ type: 'readyEarly' });
|
||||
@@ -781,4 +871,4 @@ export const mafia: Def = {
|
||||
},
|
||||
};
|
||||
|
||||
export const _internal = { canRead, writeBlock, roleKnown, nightTargets, discussionMs };
|
||||
export const _internal = { canRead, writeBlock, roleKnown, nightTargets, discussionMs, awaited };
|
||||
|
||||
@@ -46,7 +46,7 @@ function reject(s: MafiaState, actor: PlayerId, a: MafiaAction, now?: number): s
|
||||
/** The phase clock runs out. */
|
||||
function tick(s: MafiaState): MafiaState {
|
||||
if (s.phase.kind === 'ended') throw new Error('tick after the end');
|
||||
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt);
|
||||
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt!);
|
||||
}
|
||||
/** Ticks until `kind` (stops early if the game ends). */
|
||||
function until(s: MafiaState, kind: MafiaState['phase']['kind']): MafiaState {
|
||||
@@ -135,13 +135,13 @@ describe('직업 배분 (§4)', () => {
|
||||
|
||||
test('토론 시간 = clamp(생존자 × 값, 최소, 최대)', () => {
|
||||
const s = until(busy(until(rig(['mafia', 'police', 'doctor', 'citizen', 'citizen']), 'night')), 'discussion');
|
||||
expect(s.phase.kind === 'discussion' && s.phase.endsAt - s.phase.startedAt).toBe(75_000); // 5 × 15
|
||||
expect(s.phase.kind === 'discussion' && s.phase.endsAt! - s.phase.startedAt).toBe(75_000); // 5 × 15
|
||||
let t = until(rig(['mafia', 'police', 'doctor', 'citizen'], { discussionPerAlive: 10, discussionMin: 60 }), 'night');
|
||||
t = tick(t);
|
||||
expect(t.phase.kind === 'discussion' && t.phase.endsAt - t.phase.startedAt).toBe(60_000);
|
||||
expect(t.phase.kind === 'discussion' && t.phase.endsAt! - t.phase.startedAt).toBe(60_000);
|
||||
let u = until(rig(['mafia', 'mafia', 'mafia', 'police', 'doctor', 'citizen', 'citizen', 'citizen', 'citizen', 'citizen', 'citizen', 'citizen'], { discussionPerAlive: 20, discussionMax: 120 }), 'night');
|
||||
u = tick(u);
|
||||
expect(u.phase.kind === 'discussion' && u.phase.endsAt - u.phase.startedAt).toBe(120_000);
|
||||
expect(u.phase.kind === 'discussion' && u.phase.endsAt! - u.phase.startedAt).toBe(120_000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -610,17 +610,17 @@ describe('시간 조절·자리 비움·나가기 (§5.2, §8.5)', () => {
|
||||
test('timeAdjust: 1인 1일 1회, -15초로 5초 미만 내려가지 않음', () => {
|
||||
let s = day2();
|
||||
const ph0 = s.phase as Extract<MafiaState['phase'], { kind: 'discussion' }>;
|
||||
const end0 = ph0.endsAt;
|
||||
const end0 = ph0.endsAt!;
|
||||
s = act(s, 'P1', { type: 'adjustTime', delta: 15 });
|
||||
expect((s.phase as typeof ph0).endsAt).toBe(end0 + 15_000);
|
||||
expect(reject(s, 'P1', { type: 'adjustTime', delta: -15 })).toBe('시간 바꾸기는 하루에 한 번만 할 수 있어요.');
|
||||
expect(lastEv(s, 'adjust')).toMatchObject({ p: 'P1', delta: 15 });
|
||||
// 끝나기 8초 전에 -15 → 5초 남김
|
||||
s = act(s, 'P2', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt - 8_000);
|
||||
s = act(s, 'P2', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt! - 8_000);
|
||||
const now = end0 + 15_000 - 8_000;
|
||||
expect((s.phase as typeof ph0).endsAt).toBe(now + 5_000);
|
||||
// 이미 5초 미만이면 그대로
|
||||
s = act(s, 'P3', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt - 3_000);
|
||||
s = act(s, 'P3', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt! - 3_000);
|
||||
expect((s.phase as typeof ph0).endsAt).toBe(now + 5_000);
|
||||
expect(mafia.view(s, null).phase.adjustedBy).toEqual(['P1', 'P2', 'P3']);
|
||||
// 다음 날에는 다시 가능
|
||||
@@ -691,6 +691,93 @@ describe('시간 조절·자리 비움·나가기 (§5.2, §8.5)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('시간 무제한 (§8.5)', () => {
|
||||
const U = { discussionPerAlive: null, voteSeconds: null, defenseSeconds: null, confirmSeconds: null, nightSeconds: null };
|
||||
const roles: Role[] = ['mafia', 'police', 'doctor', 'citizen', 'citizen'];
|
||||
const live = (s: MafiaState) => s.players.filter((p) => p.alive).map((p) => p.id);
|
||||
|
||||
test('모든 단계 무제한: 마감 없이 모두 마칠 때까지 기다리고, 기다리는 사람만 시간 초과 대상', () => {
|
||||
// Role reveal and greeting keep their fixed clocks.
|
||||
let s = until(busy(rig(roles, U)), 'night');
|
||||
expect(s.phase.kind === 'night' && s.phase.endsAt).toBeNull();
|
||||
expect(mafia.deadline!(s)).toBeNull();
|
||||
expect(mafia.timeoutNotBefore!(s)).toBeNull();
|
||||
expect(mafia.timeoutPlayers!(s)).toEqual(live(s));
|
||||
s = act(s, 'P0', { type: 'mafiaTarget', target: 'P3' });
|
||||
for (const p of ['P0', 'P1', 'P2', 'P3']) s = act(s, p, { type: 'readyEarly' });
|
||||
expect(reject(s, 'P0', { type: 'readyEarly' })).toBe('이미 밤 마치기를 눌렀어요.');
|
||||
expect(s.phase.kind).toBe('night');
|
||||
expect(mafia.view(s, 'P1').phase).toMatchObject({ readyCount: 4, readyNeeded: 5 });
|
||||
expect(mafia.timeoutPlayers!(s)).toEqual(['P4']);
|
||||
expect(reject(s, 'P1', { type: 'phaseTimeout' })).toBe('아직 기다리는 중이에요.');
|
||||
s = act(s, 'P4', { type: 'readyEarly' }, T0 + 3_600_000);
|
||||
expect(s.phase.kind).toBe('discussion');
|
||||
expect(pl(s, 'P3').alive).toBe(false);
|
||||
// Discussion: no ±15초; everybody alive presses 토론 끝내기.
|
||||
const v = mafia.view(s, 'P1');
|
||||
expect(v.phase.endsAt).toBeNull();
|
||||
expect(v.my!.canAdjust).toBe(false);
|
||||
expect(reject(s, 'P1', { type: 'adjustTime', delta: 15 })).toBe('이 방은 토론 시간이 무제한이에요.');
|
||||
for (const p of live(s)) s = act(s, p, { type: 'readyEarly' });
|
||||
expect(s.phase.kind).toBe('vote');
|
||||
// Vote: ends when every living player voted (abstain counts).
|
||||
s = act(s, 'P1', { type: 'vote', target: 'P0' });
|
||||
s = act(s, 'P2', { type: 'vote', target: 'P0' });
|
||||
s = act(s, 'P0', { type: 'vote', target: 'P1' });
|
||||
expect(mafia.view(s, null).phase).toMatchObject({ readyCount: 3, readyNeeded: 4 });
|
||||
s = act(s, 'P4', { type: 'vote', target: 'abstain' });
|
||||
expect(s.phase.kind === 'defense' && s.phase.accused).toBe('P0');
|
||||
// Defense: only the accused ends it.
|
||||
expect(reject(s, 'P1', { type: 'readyEarly' })).toBe('지목된 사람만 반론을 마칠 수 있어요.');
|
||||
expect(mafia.view(s, 'P0').my!.canReady).toBe(true);
|
||||
expect(mafia.timeoutPlayers!(s)).toEqual(['P0']);
|
||||
s = act(s, 'P0', { type: 'readyEarly' });
|
||||
expect(s.phase.kind).toBe('confirm');
|
||||
// Confirm: every voter but the accused.
|
||||
s = act(s, 'P1', { type: 'confirm', choice: 'yes' });
|
||||
s = act(s, 'P2', { type: 'confirm', choice: 'yes' });
|
||||
expect(s.phase.kind).toBe('confirm');
|
||||
s = act(s, 'P4', { type: 'confirm', choice: 'no' });
|
||||
expect(s.winner).toBe('town');
|
||||
});
|
||||
|
||||
test('자리 비운 사람은 방의 유예 시간 뒤 자기 차례만 넘김(기권·투표 없음·마침), 토론 시간만 무제한도 가능', () => {
|
||||
let s = until(busy(rig(roles, { voteSeconds: null, confirmSeconds: null })), 'vote');
|
||||
for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'vote', target: 'P0' });
|
||||
s = act(s, 'P0', { type: 'vote', target: 'P1' });
|
||||
expect(mafia.timeoutPlayers!(s)).toEqual(['P4']);
|
||||
s = act(s, 'P4', mafia.onTimeout(s, 'P4'));
|
||||
expect(lastEv(s, 'vote')!.votes!.P4).toBe('abstain');
|
||||
// Defense keeps its 20 s clock (driver P0), then a 무제한 confirm.
|
||||
expect(s.phase.kind === 'defense' && s.phase.endsAt! - s.phase.startedAt).toBe(20_000);
|
||||
s = tick(s);
|
||||
expect(s.phase.kind).toBe('confirm');
|
||||
s = act(s, 'P1', { type: 'confirm', choice: 'no' });
|
||||
s = act(s, 'P2', { type: 'confirm', choice: 'no' });
|
||||
s = act(s, 'P3', mafia.onTimeout(s, 'P3'));
|
||||
expect(s.phase.kind).toBe('confirm');
|
||||
s = act(s, 'P4', mafia.onTimeout(s, 'P4'));
|
||||
expect(lastEv(s, 'confirm')).toMatchObject({ yes: 0, no: 2, outcome: 'spared' });
|
||||
expect(s.phase.kind).toBe('night');
|
||||
expect(s.phase.kind === 'night' && s.phase.endsAt! - s.phase.startedAt).toBe(30_000);
|
||||
// Only the discussion without a clock.
|
||||
let d = until(busy(until(rig(roles, { discussionPerAlive: null }), 'night')), 'discussion');
|
||||
expect(d.phase.kind === 'discussion' && d.phase.endsAt).toBeNull();
|
||||
for (const p of live(d).slice(1)) d = act(d, p, { type: 'readyEarly' });
|
||||
d = act(d, 'P0', mafia.onTimeout(d, 'P0'));
|
||||
expect(d.phase.kind === 'vote' && d.phase.endsAt! - d.phase.startedAt).toBe(20_000);
|
||||
});
|
||||
|
||||
test('무작위 대국(모든 단계 무제한)도 끝나고, 시간 초과 행동은 기다리는 사람에게 항상 합법', () => {
|
||||
for (let i = 1; i <= 120; i++) {
|
||||
const n = 4 + (i % 9);
|
||||
const options = { ...presetFor(i, n), ...U } as MafiaOptions;
|
||||
const a = fastPlayout(ids(n), options, seedN(9000 + i), 6000);
|
||||
if (!a.finished) throw new Error(`seed ${i} (${n} players) did not finish`);
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe('스키마', () => {
|
||||
test('옵션에 한국어 메타, 기본값', () => {
|
||||
const shape = (mafia.optionsSchema as unknown as { shape: Record<string, { meta(): { title?: string } | undefined }> }).shape;
|
||||
@@ -783,7 +870,12 @@ function fastPlayout(players: PlayerId[], options: MafiaOptions, seed: RngState,
|
||||
const pool = pick < 2 ? players : mafia.activePlayers(s);
|
||||
actor = pool[chooser.int(pool.length)]!;
|
||||
const legal = mafia.legalActions!(s, actor);
|
||||
action = legal.length ? legal[chooser.int(legal.length)]! : mafia.onTimeout(s, actor);
|
||||
if (legal.length) action = legal[chooser.int(legal.length)]!;
|
||||
else {
|
||||
// Nothing to do (무제한: not awaited): the room's timeout for someone the phase waits on instead.
|
||||
actor = mafia.timeoutPlayers!(s)[0] ?? actor;
|
||||
action = mafia.onTimeout(s, actor);
|
||||
}
|
||||
}
|
||||
const v = mafia.validate(s, actor, action);
|
||||
if (!v.ok) throw new Error(`generated action rejected: ${v.reason} ${JSON.stringify(action)}`);
|
||||
@@ -858,8 +950,8 @@ describe(`무작위 대국 (시드 ${SEEDS}개, 4~12명)`, () => {
|
||||
while (!s.winner) {
|
||||
for (const p of [...s.players.map((x) => x.id)]) expect(mafia.validate(s, p, mafia.onTimeout(s, p)).ok).toBe(true);
|
||||
const ph = s.phase as Exclude<MafiaState['phase'], { kind: 'ended' }>;
|
||||
expect(mafia.validate(s, 'P0', mafia.onTimeout(s, 'P0'), { now: ph.endsAt }).ok).toBe(true);
|
||||
s = mafia.apply(s, 'P0', mafia.onTimeout(s, 'P0'), { rng: r, now: ph.endsAt }).state;
|
||||
expect(mafia.validate(s, 'P0', mafia.onTimeout(s, 'P0'), { now: ph.endsAt! }).ok).toBe(true);
|
||||
s = mafia.apply(s, 'P0', mafia.onTimeout(s, 'P0'), { rng: r, now: ph.endsAt! }).state;
|
||||
}
|
||||
// Only timeouts: nobody acts, so away eliminations end the game.
|
||||
expect(s.final!.cause === 'disconnect' || s.final!.cause === 'night').toBe(true);
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
import { z } from 'zod';
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
|
||||
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>[]]);
|
||||
const secLabels = (...vals: number[]) => Object.fromEntries(vals.map((v) => [v, `${v}초`]));
|
||||
/** Labels plus 무제한 (null): that phase has no clock and ends when everyone needed is done (§8.5). */
|
||||
const secLabelsU = (unl: string, ...vals: number[]) => ({ ...secLabels(...vals), null: unl });
|
||||
|
||||
export const ROLES = ['mafia', 'police', 'doctor', 'citizen', 'soldier', 'politician', 'medium', 'lover'] as const;
|
||||
export type Role = (typeof ROLES)[number];
|
||||
@@ -34,9 +36,10 @@ export const mafiaOptionsSchema = z.object({
|
||||
.enum(['day', 'night'])
|
||||
.default('day')
|
||||
.meta({ title: '시작 페이즈', labels: { day: '인사하는 낮부터(투표 없음)', night: '밤부터' } }),
|
||||
discussionPerAlive: lit(10, 15, 20)
|
||||
/** null = 무제한 토론: ends when every living player pressed 토론 끝내기 (min/max and ±15초 do not apply). */
|
||||
discussionPerAlive: lit<10 | 15 | 20 | null>(10, 15, 20, null)
|
||||
.default(15)
|
||||
.meta({ title: '토론 시간(살아 있는 사람 1명당)', labels: secLabels(10, 15, 20) }),
|
||||
.meta({ title: '토론 시간(살아 있는 사람 1명당)', labels: secLabelsU('무제한(모두 토론 끝내기를 누를 때까지)', 10, 15, 20) }),
|
||||
discussionMin: lit(30, 45, 60, 90, 120)
|
||||
.default(60)
|
||||
.meta({ title: '토론 시간 최소', labels: secLabels(30, 45, 60, 90, 120) }),
|
||||
@@ -44,18 +47,18 @@ export const mafiaOptionsSchema = z.object({
|
||||
.default(180)
|
||||
.meta({ title: '토론 시간 최대', labels: secLabels(60, 120, 180, 240, 300) }),
|
||||
timeAdjust: z.boolean().default(true).meta({ title: '하루 한 번 토론 시간 늘리기·줄이기(±15초)' }),
|
||||
voteSeconds: lit(10, 15, 20, 30, 45, 60)
|
||||
voteSeconds: lit<10 | 15 | 20 | 30 | 45 | 60 | null>(10, 15, 20, 30, 45, 60, null)
|
||||
.default(20)
|
||||
.meta({ title: '지목 투표 시간', labels: secLabels(10, 15, 20, 30, 45, 60) }),
|
||||
defenseSeconds: lit(10, 15, 20, 30, 45, 60)
|
||||
.meta({ title: '지목 투표 시간', labels: secLabelsU('무제한(모두 투표할 때까지)', 10, 15, 20, 30, 45, 60) }),
|
||||
defenseSeconds: lit<10 | 15 | 20 | 30 | 45 | 60 | null>(10, 15, 20, 30, 45, 60, null)
|
||||
.default(20)
|
||||
.meta({ title: '최후의 반론 시간', labels: secLabels(10, 15, 20, 30, 45, 60) }),
|
||||
confirmSeconds: lit(5, 10, 15, 20, 30)
|
||||
.meta({ title: '최후의 반론 시간', labels: secLabelsU('무제한(지목된 사람이 반론 마치기를 누를 때까지)', 10, 15, 20, 30, 45, 60) }),
|
||||
confirmSeconds: lit<5 | 10 | 15 | 20 | 30 | null>(5, 10, 15, 20, 30, null)
|
||||
.default(10)
|
||||
.meta({ title: '찬반 투표 시간', labels: secLabels(5, 10, 15, 20, 30) }),
|
||||
nightSeconds: lit(15, 20, 30, 45, 60, 90)
|
||||
.meta({ title: '찬반 투표 시간', labels: secLabelsU('무제한(모두 투표할 때까지)', 5, 10, 15, 20, 30) }),
|
||||
nightSeconds: lit<15 | 20 | 30 | 45 | 60 | 90 | null>(15, 20, 30, 45, 60, 90, null)
|
||||
.default(30)
|
||||
.meta({ title: '밤 시간', labels: secLabels(15, 20, 30, 45, 60, 90) }),
|
||||
.meta({ title: '밤 시간', labels: secLabelsU('무제한(모두 밤 마치기를 누를 때까지)', 15, 20, 30, 45, 60, 90) }),
|
||||
deathReveal: z
|
||||
.enum(['none', 'team', 'role'])
|
||||
.default('team')
|
||||
@@ -113,14 +116,18 @@ export interface PlayerState {
|
||||
export type Phase =
|
||||
| { kind: 'roleReveal'; startedAt: number; endsAt: number }
|
||||
| { kind: 'greeting'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number; adjustedBy: PlayerId[]; ready: PlayerId[] }
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number; votes: Record<PlayerId, PlayerId | 'abstain'> }
|
||||
| { kind: 'defense'; startedAt: number; endsAt: number; accused: PlayerId }
|
||||
| { kind: 'confirm'; startedAt: number; endsAt: number; accused: PlayerId; ballots: Record<PlayerId, 'yes' | 'no'> }
|
||||
// endsAt null = 무제한 (that phase's seconds option is null): it ends when everyone needed is done (§8.5).
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number | null; adjustedBy: PlayerId[]; ready: PlayerId[] }
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number | null; votes: Record<PlayerId, PlayerId | 'abstain'> }
|
||||
| { kind: 'defense'; startedAt: number; endsAt: number | null; accused: PlayerId }
|
||||
/** `passed`: 무제한 only, voters the room moved on while away (no ballot). */
|
||||
| { kind: 'confirm'; startedAt: number; endsAt: number | null; accused: PlayerId; ballots: Record<PlayerId, 'yes' | 'no'>; passed?: PlayerId[] }
|
||||
| {
|
||||
kind: 'night';
|
||||
startedAt: number;
|
||||
endsAt: number;
|
||||
endsAt: number | null;
|
||||
/** 무제한 only: who pressed 밤 마치기 (everybody alive must, so it shows nothing about roles). */
|
||||
ready?: PlayerId[];
|
||||
mafiaTarget: PlayerId | null;
|
||||
mafiaPickedBy: PlayerId | null;
|
||||
investigate: PlayerId | null;
|
||||
@@ -270,6 +277,7 @@ export interface MafiaView {
|
||||
accused: PlayerId | null;
|
||||
/** Discussion: who used ±15초 today (public). */
|
||||
adjustedBy: PlayerId[];
|
||||
/** Greeting/discussion: 토론 끝내기; 무제한 vote/confirm/night: how many are done. */
|
||||
readyCount: number;
|
||||
readyNeeded: number;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user