마피아: 단계별 시간 무제한(토론·지목 투표·반론·찬반·밤, 모두 마치면 넘어감·연결 끊긴 사람은 유예 뒤 넘김), 밤·아침·판결 소리, 움직임
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -280,7 +280,7 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
const a = v.accusations[v.accusations.length - 1]!;
|
||||
const who = a.by === me ? '내' : `${nick(players, a.by)}님의`;
|
||||
if (a.correct) {
|
||||
sfx.fanfare();
|
||||
// The game ends here: the room plays win / lose.
|
||||
setBanner({ key: `a${v.accusations.length}`, kind: 'ok', text: `⚖️ ${who} 고발이 맞았어요!` });
|
||||
} else {
|
||||
sfx.bad();
|
||||
|
||||
@@ -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 type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
@@ -56,6 +56,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';
|
||||
|
||||
@@ -135,6 +157,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; }
|
||||
@@ -154,14 +181,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}`;
|
||||
@@ -537,7 +570,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초
|
||||
@@ -547,21 +580,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' })}>
|
||||
기권
|
||||
@@ -570,7 +606,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 ? (
|
||||
<>
|
||||
@@ -583,7 +631,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>
|
||||
@@ -595,7 +652,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">
|
||||
@@ -607,6 +664,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>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -629,6 +696,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 (
|
||||
@@ -670,6 +748,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;
|
||||
@@ -682,11 +793,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 }) };
|
||||
@@ -711,10 +824,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} />
|
||||
@@ -824,7 +939,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]) => (
|
||||
@@ -851,6 +966,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>) {
|
||||
@@ -893,7 +1010,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
|
||||
@@ -913,26 +1031,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>
|
||||
@@ -975,7 +1101,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(' · ');
|
||||
}
|
||||
@@ -996,6 +1123,10 @@ function Rules() {
|
||||
<p>
|
||||
밤에는 낮 채팅이 잠겨요. 마피아는 마피아 채팅으로, 연인은 연인 채팅으로 몰래 이야기해요. 탈락한 사람은 죽은 사람 채팅에서만 이야기할 수 있어요(영매는 밤에 함께해요).
|
||||
</p>
|
||||
<p>
|
||||
<strong>시간 무제한</strong>: 단계마다 시간을 무제한으로 할 수 있어요. 그러면 토론은 모두 [토론 끝내기], 투표는 모두 투표, 반론은 지목된 사람이 [반론 마치기], 밤은 모두 [밤 마치기]를 누를 때
|
||||
넘어가요. 연결이 끊긴 채 돌아오지 않는 사람은 잠시 뒤 기권·마침으로 처리돼요.
|
||||
</p>
|
||||
<table className="mf-rules small" style={{ borderCollapse: 'collapse', width: '100%' }}>
|
||||
<tbody>
|
||||
{ROLE_ORDER.map((r) => (
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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