Files
joke-app/packages/games/src/mafia/index.ts

875 lines
37 KiB
TypeScript

/**
* 마피아 (docs/games/mafia.md). Pure and deterministic; state is JSON.
*
* 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). 무제한 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 {
CHANNELS,
EXTRA_ROLES,
mafiaActionSchema,
mafiaOptionsSchema,
type Channel,
type ChatView,
type DiedBy,
type ExtraRole,
type MafiaAction,
type MafiaFinal,
type MafiaOptions,
type MafiaState,
type MafiaView,
type MyView,
type NightActionType,
type NightView,
type Phase,
type PlayerState,
type PrivateResult,
type PublicEvent,
type Role,
type Team,
type WinCause,
} from './types';
export * from './types';
export const ROLE_REVEAL_MS = 8_000;
export const GREETING_MS = 60_000;
export const ADJUST_MS = 15_000;
/** `-15초` never leaves less than this (§5.2). */
export const ADJUST_FLOOR_MS = 5_000;
export const CHAT_MAX = 200;
export const CHAT_GAP_MS = 700;
/** Voting days in a row without any action → 자리 비움 탈락 (§8.5). */
export const AWAY_DAYS = 2;
const CHAT_KEEP = 400;
const CHAT_VIEW = 150;
const EVENTS_VIEW = 120;
export const ROLE_KO: Record<Role, string> = {
mafia: '마피아',
police: '경찰',
doctor: '의사',
citizen: '시민',
soldier: '군인',
politician: '정치인',
medium: '영매',
lover: '연인',
};
export const teamOf = (r: Role): Team => (r === 'mafia' ? 'mafia' : 'town');
/** §4 table: mafia count for `auto`. */
const AUTO_MAFIA: Record<number, number> = { 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 3, 10: 3, 11: 3, 12: 3 };
const EXTRA_SLOTS: Record<ExtraRole, number> = { soldier: 1, politician: 1, medium: 1, lovers: 2 };
const EXTRA_OBJ: Record<ExtraRole, string> = { soldier: '군인을', politician: '정치인을', medium: '영매를', lovers: '연인을' };
export function mafiaCountFor(o: MafiaOptions, n: number): number {
return o.mafiaCount === 'auto' ? (AUTO_MAFIA[n] ?? Math.max(1, Math.floor(n / 4))) : o.mafiaCount;
}
/** Why this composition cannot start (lobby refusal, §4.2), or null. */
export function compositionError(o: MafiaOptions, n: number): string | null {
if (n < 4 || n > 12) return '마피아는 4~12명이 할 수 있어요.';
const m = mafiaCountFor(o, n);
if (m >= n / 2) return `${n}명일 때 마피아는 ${Math.ceil(n / 2) - 1}명까지 정할 수 있어요.`;
let citizens = n - m - 2;
for (const r of EXTRA_ROLES) {
if (!o.extraRoles[r]) continue;
if (citizens < EXTRA_SLOTS[r]) return `인원이 부족해서 ${EXTRA_OBJ[r]} 넣을 수 없어요(시민 자리 ${EXTRA_SLOTS[r]}개 필요).`;
citizens -= EXTRA_SLOTS[r];
}
return null;
}
/** Roles for `n` players before shuffling (§4). */
export function rolesFor(o: MafiaOptions, n: number): Role[] {
const err = compositionError(o, n);
if (err) throw new Error(`mafia: ${err}`);
const m = mafiaCountFor(o, n);
const out: Role[] = [...Array<Role>(m).fill('mafia'), 'police', 'doctor'];
if (o.extraRoles.soldier) out.push('soldier');
if (o.extraRoles.politician) out.push('politician');
if (o.extraRoles.medium) out.push('medium');
if (o.extraRoles.lovers) out.push('lover', 'lover');
while (out.length < n) out.push('citizen');
return out;
}
// ---------------------------------------------------------------- chat filter (kidSafeChat)
const BANNED = ['시발', '씨발', '병신', '좆', '개새끼', '느금', '니애미', 'fuck', 'shit', 'bitch'];
const LINK = /(https?:\/\/|www\.|\b[a-z0-9-]+\.(com|net|org|kr|io|gg|me|ly|co|xyz|app|dev|site|link)\b)/i;
const PHONE = /(01[016789]|0\d{1,2})[-\s.]?\d{3,4}[-\s.]?\d{4}/;
export function cleanChat(text: string): string {
return text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
}
/** Korean reason a message is refused, or null. */
export function chatProblem(text: string, kidSafe: boolean): string | null {
const len = [...text].length;
if (len === 0) return '메시지를 입력해 주세요.';
if (len > CHAT_MAX) return `메시지는 ${CHAT_MAX}자까지 보낼 수 있어요.`;
if (!kidSafe) return null;
const squashed = text.normalize('NFC').toLowerCase().replace(/[\s_.\-*0-9]/g, '');
if (BANNED.some((w) => squashed.includes(w))) return '고운 말을 써 주세요.';
if (LINK.test(text)) return '링크는 보낼 수 없어요.';
if (PHONE.test(text)) return '전화번호 같은 개인 정보는 보낼 수 없어요.';
return null;
}
// ---------------------------------------------------------------- helpers
const P = (s: MafiaState, id: PlayerId): PlayerState | undefined => s.players.find((p) => p.id === id);
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' }>;
/** 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);
}
type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
function startPhase(s: MafiaState, now: number, kind: 'greeting' | 'discussion' | 'vote' | 'night'): void {
switch (kind) {
case 'greeting':
s.phase = { kind, startedAt: now, endsAt: now + GREETING_MS, ready: [] };
break;
case 'discussion':
s.phase = { kind, startedAt: now, endsAt: ends(now, discussionMs(s)), adjustedBy: [], ready: [] };
break;
case 'vote':
s.phase = { kind, startedAt: now, endsAt: endsIn(now, s.options.voteSeconds), votes: {} };
break;
case 'night':
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 });
}
function eliminate(s: MafiaState, now: number, p: PlayerState, by: DiedBy): void {
p.alive = false;
p.diedDay = s.day;
p.diedBy = by;
const reveal = s.options.deathReveal;
pushEvent(s, now, { t: 'death', p: p.id, by, team: reveal === 'none' ? null : teamOf(p.role), role: reveal === 'role' ? p.role : null });
}
function summaryOf(winner: Team, cause: WinCause, day: number): string {
if (winner === 'town') {
if (cause === 'vote') return `시민 팀 승리! ${day}일차 낮 투표로 마지막 마피아를 찾아냈어요.`;
if (cause === 'disconnect') return `시민 팀 승리! ${day}일차에 마지막 마피아가 자리를 비워 탈락했어요.`;
return '시민 팀 승리! 마피아가 모두 탈락했어요.';
}
if (cause === 'vote') return `마피아 팀 승리! ${day}일차 낮 투표 뒤 마피아 수가 시민 수와 같아졌어요.`;
if (cause === 'night') return `마피아 팀 승리! ${day}일차 아침, 마피아 수가 시민 수와 같아졌어요.`;
return `마피아 팀 승리! ${day}일차에 자리 비움 탈락으로 마피아 수가 시민 수와 같아졌어요.`;
}
/** §6: checked after an execution, after the morning news and after an away/leave elimination. */
function checkWin(s: MafiaState, now: number, cause: WinCause): boolean {
const living = alive(s);
const m = living.filter((p) => p.role === 'mafia').length;
const winner: Team | null = m === 0 ? 'town' : m >= living.length - m ? 'mafia' : null;
if (!winner) return false;
s.winner = winner;
s.phase = { kind: 'ended' };
pushEvent(s, now, { t: 'end', winner });
const players = s.players.map((p) => ({
id: p.id,
role: p.role,
team: teamOf(p.role),
alive: p.alive,
diedDay: p.diedDay,
diedBy: p.diedBy,
won: teamOf(p.role) === winner,
}));
const order = (won: boolean) => [...players.filter((p) => p.won === won && p.alive), ...players.filter((p) => p.won === won && !p.alive)].map((p) => p.id);
let mvp: PlayerId | null = null;
for (const p of s.players) if (teamOf(p.role) === 'town' && (s.mvpVotes[p.id] ?? 0) > (mvp ? s.mvpVotes[mvp]! : 0)) mvp = p.id;
s.final = { winner, days: s.day, cause, players, ranking: [...order(true), ...order(false)], mvp, summary: summaryOf(winner, cause, s.day) };
return true;
}
/** End of a voting day: away detection (§8.5), then win check. Returns true when the game ended. */
function endDay(s: MafiaState, now: number): boolean {
const away: PlayerState[] = [];
for (const p of alive(s)) {
p.idleDays = p.activeToday ? 0 : p.idleDays + 1;
p.activeToday = false;
if (p.idleDays >= AWAY_DAYS) away.push(p);
}
for (const p of away) eliminate(s, now, p, 'disconnect');
return away.length > 0 && checkWin(s, now, 'disconnect');
}
function resolveVote(s: MafiaState, now: number): PlayerId | null {
const ph = s.phase as Extract<Phase, { kind: 'vote' }>;
const tally: Record<PlayerId, number> = {};
const votes: Record<PlayerId, PlayerId | 'abstain'> = {};
let abstain = 0;
for (const p of alive(s)) {
const w = p.role === 'politician' ? 2 : 1;
const v = ph.votes[p.id];
if (!v || v === 'abstain' || !isAlive(s, v)) {
abstain += w;
votes[p.id] = 'abstain';
} else {
tally[v] = (tally[v] ?? 0) + w;
votes[p.id] = v;
}
}
const max = Math.max(0, ...Object.values(tally));
const tops = Object.keys(tally).filter((k) => tally[k] === max);
const accused = max >= 1 && tops.length === 1 ? tops[0]! : null;
s.trialVoters = accused ? Object.keys(votes).filter((k) => votes[k] === accused) : [];
pushEvent(s, now, { t: 'vote', tally, abstain, votes: s.options.openVote ? votes : null, accused, tie: tops.length > 1 });
return accused;
}
/** Returns true when the game ended. */
function resolveConfirm(s: MafiaState, now: number): boolean {
const ph = s.phase as Extract<Phase, { kind: 'confirm' }>;
let yes = 0;
let no = 0;
for (const p of alive(s)) {
const b = ph.ballots[p.id];
if (!b || p.id === ph.accused) continue;
const w = p.role === 'politician' ? 2 : 1;
if (b === 'yes') yes += w;
else no += w;
}
const acc = P(s, ph.accused)!;
if (yes <= no || !acc.alive) {
pushEvent(s, now, { t: 'confirm', accused: acc.id, yes, no, outcome: 'spared' });
return false;
}
if (acc.role === 'politician') {
acc.publicRole = true;
pushEvent(s, now, { t: 'confirm', accused: acc.id, yes, no, outcome: 'politician' });
return false;
}
pushEvent(s, now, { t: 'confirm', accused: acc.id, yes, no, outcome: 'executed' });
eliminate(s, now, acc, 'vote');
if (acc.role === 'mafia') {
for (const v of s.trialVoters) if (teamOf(P(s, v)!.role) === 'town') s.mvpVotes[v] = (s.mvpVotes[v] ?? 0) + 1;
}
return checkWin(s, now, 'vote');
}
/** Night resolution in the §5.5 order. Returns true when the game ended. */
function resolveNight(s: MafiaState, now: number, rng: Rng): boolean {
const ph = s.phase as NightPhase;
let target = isAlive(s, ph.mafiaTarget) ? ph.mafiaTarget : null;
const mafiaAlive = alive(s).some((p) => p.role === 'mafia');
if (!target && s.options.mafiaMustKill === 'random' && mafiaAlive) {
const pool = alive(s).filter((p) => p.role !== 'mafia');
if (pool.length) target = pool[rng.int(pool.length)]!.id;
}
if (!target) pushEvent(s, now, { t: 'quiet' });
else if (target === ph.heal) pushEvent(s, now, { t: 'healed' });
else {
const t = P(s, target)!;
if (t.role === 'soldier' && !t.soldierUsed) {
t.soldierUsed = true;
t.publicRole = true;
pushEvent(s, now, { t: 'soldier', p: t.id });
} else eliminate(s, now, t, 'mafia');
}
s.lastHealTarget = ph.heal;
// Private results, delivered at the end of the night (§5.5.5) even if the police/medium died tonight.
const police = s.players.find((p) => p.role === 'police');
if (police && ph.investigate) {
const r = P(s, ph.investigate)!.role;
addResult(s, police.id, 'investigate', ph.investigate, s.options.policeRevealRole ? r : r === 'mafia' ? 'mafia' : 'notMafia');
}
const medium = s.players.find((p) => p.role === 'medium');
if (medium && ph.mediumPeek) addResult(s, medium.id, 'peek', ph.mediumPeek, P(s, ph.mediumPeek)!.role);
s.day += 1;
return checkWin(s, now, 'night');
}
function addResult(s: MafiaState, to: PlayerId, kind: PrivateResult['kind'], target: PlayerId, result: PrivateResult['result']): void {
s.privateResults.push({ id: `res-${s.day}-${kind}-${s.privateResults.length + 1}`, to, day: s.day, kind, target, result });
}
/** The phase timer ran out (or everyone pressed 토론 끝내기). */
function advance(s: MafiaState, now: number, rng: Rng): void {
const ph = s.phase;
switch (ph.kind) {
case 'roleReveal':
startPhase(s, now, s.options.firstPhase === 'day' ? 'greeting' : 'night');
return;
case 'greeting':
startPhase(s, now, 'night');
return;
case 'discussion':
startPhase(s, now, 'vote');
return;
case 'vote': {
const accused = resolveVote(s, now);
if (accused) {
s.phase = { kind: 'defense', startedAt: now, endsAt: endsIn(now, s.options.defenseSeconds), accused };
pushEvent(s, now, { t: 'phase', kind: 'defense' });
return;
}
if (!endDay(s, now)) startPhase(s, now, 'night');
return;
}
case 'defense':
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':
if (resolveConfirm(s, now)) return;
if (!endDay(s, now)) startPhase(s, now, 'night');
return;
case 'night':
if (!resolveNight(s, now, rng)) startPhase(s, now, 'discussion');
return;
case 'ended':
throw new Error('mafia: advance after the end');
}
}
/** A player leaves mid-game: eliminated at once (like 자리 비움), then the phase is repaired. */
function leave(s: MafiaState, now: number, rng: Rng, p: PlayerState): void {
eliminate(s, now, p, 'disconnect');
if (checkWin(s, now, 'disconnect')) return;
const ph = s.phase;
switch (ph.kind) {
case 'greeting':
case 'discussion':
ph.ready = ph.ready.filter((x) => x !== p.id);
if (ph.ready.length > 0 && alive(s).every((x) => ph.ready.includes(x.id))) advance(s, now, rng);
return;
case 'vote':
delete ph.votes[p.id];
return;
case 'defense':
case 'confirm':
if (ph.kind === 'confirm') delete ph.ballots[p.id];
if (ph.accused === p.id && !endDay(s, now)) startPhase(s, now, 'night');
return;
case 'night':
if (ph.mafiaTarget === p.id) {
ph.mafiaTarget = null;
ph.mafiaPickedBy = null;
}
if (ph.investigate === p.id) ph.investigate = null;
if (ph.heal === p.id) ph.heal = null;
return;
}
}
// ---------------------------------------------------------------- permissions
function nightActionOf(r: Role): NightActionType | null {
return r === 'mafia' ? 'mafiaTarget' : r === 'police' ? 'investigate' : r === 'doctor' ? 'heal' : r === 'medium' ? 'mediumPeek' : null;
}
/** Legal targets for a night action. */
function nightTargets(s: MafiaState, me: PlayerState, action: NightActionType): PlayerId[] {
switch (action) {
case 'mafiaTarget':
return alive(s).filter((p) => p.role !== 'mafia').map((p) => p.id);
case 'investigate':
return alive(s).filter((p) => p.id !== me.id).map((p) => p.id);
case 'heal':
return alive(s)
.filter((p) => (p.id !== me.id || s.options.doctorSelfHeal) && (s.options.doctorRepeat || p.id !== s.lastHealTarget))
.map((p) => p.id);
case 'mediumPeek':
return s.players.filter((p) => !p.alive && p.id !== me.id).map((p) => p.id);
}
}
const NIGHT_PROMPT: Record<NightActionType, string> = {
mafiaTarget: '오늘 밤 할 일: 마피아가 노릴 사람을 골라 주세요',
investigate: '오늘 밤 할 일: 조사할 사람을 골라 주세요',
heal: '오늘 밤 할 일: 지켜 줄 사람을 골라 주세요',
mediumPeek: '오늘 밤 할 일: 직업을 알아볼 탈락자를 골라 주세요',
};
function canRead(s: MafiaState, viewer: PlayerState | null, ch: Channel): boolean {
if (ch === 'day') return true;
if (s.winner && s.options.revealChatsAtEnd) return true;
if (!viewer) return false;
switch (ch) {
case 'mafia':
return viewer.role === 'mafia' || (!viewer.alive && s.options.deadSeeAll);
case 'dead':
return !viewer.alive || (viewer.role === 'medium' && s.phase.kind === 'night');
case 'lovers':
return viewer.role === 'lover';
}
}
/** Why `p` cannot write in `ch` now (Korean), or null (§5.6). */
function writeBlock(s: MafiaState, p: PlayerState, ch: Channel): string | null {
const k = s.phase.kind;
if (k === 'ended') return '게임이 끝났어요.';
switch (ch) {
case 'day':
if (!p.alive) return '탈락한 사람은 낮 채팅을 쓸 수 없어요. 죽은 사람 채팅을 써 주세요.';
if (k === 'roleReveal') return '직업을 확인하는 중이에요. 잠시 기다려 주세요.';
if (k === 'night') return '밤에는 낮 채팅을 쓸 수 없어요.';
if (k === 'defense' && s.phase.accused !== p.id) return '최후의 반론 중에는 지목된 사람만 말할 수 있어요.';
return null;
case 'mafia':
if (p.role !== 'mafia') return '마피아만 쓸 수 있어요.';
if (!p.alive) return '탈락한 마피아는 읽기만 할 수 있어요.';
return k === 'night' ? null : '마피아 채팅은 밤에만 쓸 수 있어요.';
case 'dead':
if (!p.alive) return null;
if (p.role !== 'medium') return '탈락한 사람만 쓸 수 있어요.';
return k === 'night' ? null : '영매는 밤에만 죽은 사람과 이야기할 수 있어요.';
case 'lovers':
if (p.role !== 'lover') return '연인만 쓸 수 있어요.';
if (!p.alive) return '탈락하면 연인 채팅은 읽기만 할 수 있어요.';
return k === 'night' ? null : '연인 채팅은 밤에만 쓸 수 있어요.';
}
}
// ---------------------------------------------------------------- validate
function validate(s: MafiaState, actor: PlayerId, a: MafiaAction, ctx?: { now: number }): Validation {
const p = P(s, actor);
if (!p) return fail('이 게임의 플레이어가 아니에요.');
if (s.winner) return fail('게임이 이미 끝났어요.');
const ph = s.phase;
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('이미 탈락했어요.');
case 'chat': {
if (!(CHANNELS as readonly string[]).includes(a.channel)) return fail('채팅방을 골라 주세요.');
const block = writeBlock(s, p, a.channel);
if (block) return fail(block);
const why = chatProblem(cleanChat(a.text), s.options.kidSafeChat);
if (why) return fail(why);
if (ctx && ctx.now - (s.lastChatAt[actor] ?? -Infinity) < CHAT_GAP_MS) return fail('조금 천천히 보내 주세요.');
return ok;
}
default:
break;
}
if (!p.alive) return fail('탈락한 사람은 할 수 없어요.');
switch (a.type) {
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':
if (ph.kind !== 'vote') return fail('지금은 지목 투표 시간이 아니에요.');
if (a.target === 'abstain') return ok;
if (a.target === actor) return fail('나 자신은 지목할 수 없어요.');
return isAlive(s, a.target) ? ok : fail('살아 있는 사람만 지목할 수 있어요.');
case 'confirm':
if (ph.kind !== 'confirm') return fail('지금은 찬반 투표 시간이 아니에요.');
if (ph.accused === actor) return fail('지목된 사람은 찬반 투표를 할 수 없어요.');
return a.choice === 'yes' || a.choice === 'no' ? ok : fail('찬성이나 반대를 골라 주세요.');
case 'mafiaTarget':
case 'investigate':
case 'heal':
case 'mediumPeek': {
if (ph.kind !== 'night') return fail('밤에만 할 수 있어요.');
if (nightActionOf(p.role) !== a.type) return fail('내 직업으로는 할 수 없는 행동이에요.');
if (a.type === 'mafiaTarget' && a.target === null) return ok;
const t = a.target === null ? undefined : P(s, a.target);
if (!t) return fail('이 게임의 플레이어가 아니에요.');
if (nightTargets(s, p, a.type).includes(t.id)) return ok;
if (a.type === 'mediumPeek') return fail(t.alive ? '탈락한 사람만 고를 수 있어요.' : '나 자신은 고를 수 없어요.');
if (!t.alive) return fail('살아 있는 사람만 고를 수 있어요.');
if (a.type === 'mafiaTarget') return fail('마피아끼리는 고를 수 없어요.');
if (a.type === 'heal') return t.id === actor ? fail('이 방은 의사가 자기 자신을 지킬 수 없어요.') : fail('같은 사람을 이틀 연속 지킬 수 없어요.');
return fail('나 자신은 조사할 수 없어요.');
}
}
}
// ---------------------------------------------------------------- view
function roleKnown(s: MafiaState, p: PlayerState, viewer: PlayerState | null): boolean {
if (s.winner) return true;
if (p.publicRole || (!p.alive && s.options.deathReveal === 'role')) return true;
if (!viewer) return false;
if (viewer.id === p.id) return true;
if (viewer.role === 'mafia' && p.role === 'mafia') return true;
if (viewer.role === 'lover' && p.role === 'lover') return true;
return !viewer.alive && s.options.deadSeeAll;
}
function nightView(s: MafiaState, me: PlayerState): NightView {
const ph = s.phase as NightPhase;
const action = nightActionOf(me.role);
if (!action) return { action: null, prompt: '밤이에요. 잠시 기다려 주세요', targets: [], choice: null, pickedBy: null };
const choice = action === 'mafiaTarget' ? ph.mafiaTarget : action === 'investigate' ? ph.investigate : action === 'heal' ? ph.heal : ph.mediumPeek;
const targets = nightTargets(s, me, action);
return {
action,
prompt: action === 'mediumPeek' && targets.length === 0 ? '오늘 밤 할 일: 아직 탈락한 사람이 없어요. 잠시 기다려 주세요' : NIGHT_PROMPT[action],
targets,
choice,
pickedBy: action === 'mafiaTarget' ? ph.mafiaPickedBy : null,
};
}
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),
alive: me.alive,
mates,
vote: ph.kind === 'vote' && me.alive ? (ph.votes[me.id] ?? null) : null,
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' && 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;
const readable = CHANNELS.filter((ch) => canRead(s, me, ch));
const chat: ChatView[] = s.chat
.filter((m) => readable.includes(m.channel))
.slice(-CHAT_VIEW)
.map((m) => ({ key: `${m.channel}:${m.id}`, channel: m.channel, from: m.from, text: m.text, at: m.at, day: m.day }));
const setup: Partial<Record<Role, number>> = {};
for (const p of s.players) setup[p.role] = (setup[p.role] ?? 0) + 1;
const day = ph.kind === 'greeting' || ph.kind === 'discussion';
return {
me: me?.id ?? null,
options: s.options,
day: s.day,
phase: {
kind: ph.kind,
startedAt: ph.kind === 'ended' ? 0 : ph.startedAt,
endsAt: ph.kind === 'ended' ? null : ph.endsAt,
accused: ph.kind === 'defense' || ph.kind === 'confirm' ? ph.accused : null,
adjustedBy: ph.kind === 'discussion' ? [...ph.adjustedBy] : [],
...doneCounts(s, day),
},
players: s.players.map((p) => {
const known = roleKnown(s, p, me);
const teamKnown = known || (!p.alive && s.options.deathReveal === 'team');
return { id: p.id, alive: p.alive, diedDay: p.diedDay, diedBy: p.diedBy, role: known ? p.role : null, team: teamKnown ? teamOf(p.role) : null };
}),
setup,
aliveCount: alive(s).length,
events: s.events.slice(-EVENTS_VIEW),
chat,
channels: me ? readable.map((ch) => ({ channel: ch, canWrite: !writeBlock(s, me, ch), why: writeBlock(s, me, ch) })) : [],
my: me ? myView(s, me) : null,
winner: s.winner,
final: s.final,
};
}
// ---------------------------------------------------------------- definition
function activePlayers(s: MafiaState): PlayerId[] {
const ph = s.phase;
if (ph.kind === 'ended') return [];
if (ph.kind === 'defense') return [ph.accused];
if (ph.kind === 'confirm') return alive(s).filter((p) => p.id !== ph.accused).map((p) => p.id);
// Night: every living player, so the list never reveals who has a night role (§8.3).
return alive(s).map((p) => p.id);
}
type Def = GameDefinition<MafiaState, MafiaAction, MafiaView, MafiaOptions>;
export const mafia: Def = {
id: 'mafia',
nameKo: '마피아',
minPlayers: 4,
maxPlayers: 12,
stateVersion: 1,
defaultOptions: mafiaOptionsSchema.parse({}),
optionsSchema: mafiaOptionsSchema as unknown as Def['optionsSchema'],
actionSchema: mafiaActionSchema as unknown as Def['actionSchema'],
ownChat: true,
playerCountError: compositionError,
setup({ players, options, rng, now }) {
const roles = rng.shuffle(rolesFor(options, players.length));
const ps: PlayerState[] = players.map((id, i) => ({
id,
role: roles[i]!,
alive: true,
soldierUsed: false,
publicRole: false,
diedDay: null,
diedBy: null,
activeToday: false,
idleDays: 0,
}));
return {
options,
players: ps,
day: 1,
phase: { kind: 'roleReveal', startedAt: now, endsAt: now + ROLE_REVEAL_MS },
lastHealTarget: null,
privateResults: [],
chat: [],
chatCount: { day: 0, mafia: 0, dead: 0, lovers: 0 },
lastChatAt: {},
events: [],
trialVoters: [],
mvpVotes: {},
winner: null,
seq: 0,
final: null,
};
},
validate,
apply(prev, actor, a, { rng, now }) {
const s = structuredClone(prev);
const before = s.events.length;
s.seq += 1;
const p = P(s, actor)!;
const ph = s.phase;
if (a.type !== 'phaseTimeout' && a.type !== 'leave') p.activeToday = true;
switch (a.type) {
case 'phaseTimeout':
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);
break;
case 'chat': {
s.chatCount[a.channel] += 1;
s.chat.push({ id: s.chatCount[a.channel], channel: a.channel, from: actor, text: cleanChat(a.text), at: now, day: s.day });
if (s.chat.length > CHAT_KEEP) s.chat.splice(0, s.chat.length - CHAT_KEEP);
s.lastChatAt[actor] = now;
break;
}
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);
break;
case 'vote':
if (ph.kind !== 'vote') throw new Error('mafia: vote outside the vote phase');
ph.votes[actor] = a.target;
break;
case 'confirm':
if (ph.kind !== 'confirm') throw new Error('mafia: confirm outside the confirm phase');
ph.ballots[actor] = a.choice;
break;
case 'mafiaTarget':
if (ph.kind !== 'night') throw new Error('mafia: night action by day');
ph.mafiaTarget = a.target;
ph.mafiaPickedBy = a.target === null ? null : actor;
break;
case 'investigate':
case 'heal':
case 'mediumPeek':
if (ph.kind !== 'night') throw new Error('mafia: night action by day');
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 };
},
view,
activePlayers,
deadline(s) {
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
},
/** One player drives the phase clock (the deadline is shared by everybody); 무제한: those still awaited (only the away ones time out). */
timeoutPlayers(s) {
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. */
timeoutNotBefore(s) {
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
},
/** Phases end on the clock; a missing vote is an abstention and a missing night action is "no action" (§8.5). */
onTimeout() {
return { type: 'phaseTimeout' };
},
onLeave(s, player) {
const p = P(s, player);
if (!p || !p.alive || s.winner) return null;
return { type: 'leave' };
},
result(s): GameResult | null {
const f = s.final;
if (!f) return null;
const won = (id: PlayerId) => f.players.find((p) => p.id === id)!.won;
return {
ranking: [f.ranking.filter(won), f.ranking.filter((id) => !won(id))],
scores: Object.fromEntries(f.players.map((p) => [p.id, p.won ? 1 : 0])),
summary: f.summary,
reason: 'normal',
};
},
/** Test helper: every legal move plus the phase clock and one short message per writable channel. */
legalActions(s, player) {
const p = P(s, player);
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.filter((a) => validate(s, player, a).ok);
const ph = s.phase;
const me = myView(s, p);
if (me.canReady) out.push({ type: 'readyEarly' });
if (me.canAdjust) out.push({ type: 'adjustTime', delta: 15 }, { type: 'adjustTime', delta: -15 });
if (ph.kind === 'vote') {
out.push({ type: 'vote', target: 'abstain' });
for (const t of me.voteTargets) out.push({ type: 'vote', target: t });
}
if (me.canConfirm) out.push({ type: 'confirm', choice: 'yes' }, { type: 'confirm', choice: 'no' });
if (me.night?.action) {
const type = me.night.action;
for (const t of me.night.targets) out.push({ type, target: t } as MafiaAction);
if (type === 'mafiaTarget') out.push({ type, target: null });
}
return out.filter((a) => validate(s, player, a).ok);
},
/** Private result tokens: only their owner may ever see them. */
secretsOf(s, player) {
if (s.winner) return [];
return s.privateResults.filter((r) => r.to === player).map((r) => r.id);
},
};
export const _internal = { canRead, writeBlock, roleKnown, nightTargets, discussionMs, awaited };