마피아: 단계별 시간 무제한(토론·지목 투표·반론·찬반·밤, 모두 마치면 넘어감·연결 끊긴 사람은 유예 뒤 넘김), 밤·아침·판결 소리, 움직임
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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