마피아: 단계별 시간 무제한(토론·지목 투표·반론·찬반·밤, 모두 마치면 넘어감·연결 끊긴 사람은 유예 뒤 넘김), 밤·아침·판결 소리, 움직임

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 13:14:54 +09:00
parent b8966db2a6
commit 743e5dc05e
11 changed files with 494 additions and 99 deletions

View File

@@ -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 };