마피아 컴퓨터 플레이어: 각자 타이머로 말하고 투표하는 라이브 봇, 똑똑한 편/허술한 편, 반응 속도 차이

- BotDriver live 모드: 컴퓨터마다 자기 타이머로 화면·채팅을 다시 보고 행동 하나
- mafia/bot.ts: 근거 추리(경찰 결과·경찰 주장·투표 기록) vs 느낌·분위기, 존댓말 vs 반말
- 채팅: 인사, 아침 소식, 지목·동의·반박, 이름 불리면 대답, 반론, 마피아 상의
- 연습 방 6명(PRACTICE_PLAYERS), BOT_GAMES에 mafia
- 테스트: 옵션 조합별 전체 판, 똑똑한 편 승률, 자기 팀 지목 금지, 반응 속도, 대답 E2E

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-11 02:54:14 +09:00
parent 009214c9f3
commit 92e8b2100f
15 changed files with 1202 additions and 25 deletions

View File

@@ -4,7 +4,7 @@
* information (other hands, deck order).
*/
import type { AnyGameDefinition, PlayerId } from '@bg/engine';
import type { BotStrategy } from './types';
import type { BotStrategy, LiveBotStrategy } from './types';
import { pick, playable, randomPolicy } from './policy';
import { omokBot } from '../omok/bot';
import { othelloBot } from '../othello/bot';
@@ -28,8 +28,10 @@ import { quoridorBot } from '../quoridor/bot';
import { lasVegasBot } from '../las-vegas/bot';
import { cockroachPokerBot } from '../cockroach-poker/bot';
import { ninetyNineBot } from '../ninety-nine/bot';
import { mafiaBot } from '../mafia/bot';
export type { BotInput, BotStrategy } from './types';
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botPace, botPersona, hash01, type BotPersona } from './persona';
/** Strategy per bot-enabled game (must match `BOT_GAMES` in @bg/shared). */
export const BOT_STRATEGIES: Record<string, BotStrategy> = {
@@ -92,3 +94,8 @@ export function decideBotAction(
const rest = legal.filter(valid);
return rest.length ? pick(playable(rest), random) : null;
}
/** Live strategies (games where everybody acts at once and talks); also in `BOT_GAMES`. */
export const LIVE_BOT_STRATEGIES: Record<string, LiveBotStrategy> = {
mafia: mafiaBot,
};

View File

@@ -0,0 +1,87 @@
/** Test helper: live bots (마피아) play a whole game on a simulated clock, each on its own timer, like `BotDriver`. */
import { SeededRng, type AnyGameDefinition, type PlayerId, type RngState } from '@bg/engine';
import { botPersona, type BotPersona } from './persona';
import type { LiveBotStrategy } from './types';
export interface LiveLine {
at: number;
from: PlayerId;
channel: string;
text: string;
}
export interface LivePlayoutReport {
finished: boolean;
state: unknown;
actions: number;
/** Bot actions the game refused (should stay 0). */
rejected: string[];
chat: LiveLine[];
maxBotMs: number;
/** Simulated time the game took (ms). */
elapsed: number;
}
export function liveBotPlayout(
def: AnyGameDefinition,
strategy: LiveBotStrategy,
opts: {
players: PlayerId[];
options?: unknown;
seed: RngState;
isBot: (p: PlayerId) => boolean;
names?: Record<PlayerId, string>;
/** Override characters (tests): called once after setup with the game state. */
personaOf?: (p: PlayerId, state: unknown) => BotPersona;
maxMs?: number;
},
): LivePlayoutReport {
const rng = SeededRng.fromSeed(opts.seed);
const chooser = SeededRng.fromSeed([opts.seed[2], opts.seed[3], opts.seed[0], opts.seed[1] ^ 0x27d4eb2d]);
const random = () => chooser.next();
const start = 1_700_000_000_000;
let now = start;
let state = def.setup({ players: opts.players, options: opts.options ?? def.defaultOptions, rng, now, gameNo: 1 });
const names = opts.names ?? Object.fromEntries(opts.players.map((p, i) => [p, opts.isBot(p) ? `컴퓨터 ${i + 1}` : `사람${i + 1}`]));
const bots = opts.players.filter(opts.isBot);
const persona = new Map(bots.map((b) => [b, opts.personaOf?.(b, state) ?? botPersona(b)]));
const memory = new Map(bots.map((b) => [b, {} as Record<string, unknown>]));
const due = new Map(bots.map((b) => [b, now + 500 + random() * 1000]));
const rep: LivePlayoutReport = { finished: false, state, actions: 0, rejected: [], chat: [], maxBotMs: 0, elapsed: 0 };
const maxMs = opts.maxMs ?? 3 * 3600_000;
const apply = (actor: PlayerId, action: unknown) => {
state = def.apply(state, actor, action, { rng, now }).state;
rep.actions++;
const a = action as { type?: string; channel?: string; text?: string };
if (a.type === 'chat') rep.chat.push({ at: now - start, from: actor, channel: a.channel!, text: a.text! });
};
while (now - start < maxMs) {
if (def.result(state)) {
rep.finished = true;
break;
}
let bot: PlayerId | null = null;
for (const [b, t] of due) if (bot === null || t < due.get(bot)!) bot = b;
const deadline = def.deadline?.(state) ?? null;
if (deadline !== null && (bot === null || deadline <= due.get(bot)!)) {
now = Math.max(now, deadline);
const who = (def.timeoutPlayers ? def.timeoutPlayers(state) : def.activePlayers(state))[0]!;
apply(who, def.onTimeout(state, who));
continue;
}
if (bot === null) throw new Error(`${def.id}: stalled`);
now = Math.max(now, due.get(bot)!);
const t0 = performance.now();
const d = strategy({ me: bot, view: structuredClone(def.view(state, bot)), now, random, persona: persona.get(bot)!, names, memory: memory.get(bot)! });
rep.maxBotMs = Math.max(rep.maxBotMs, performance.now() - t0);
due.set(bot, now + Math.max(50, d.next));
if (d.action) {
const v = def.validate(state, bot, d.action, { now });
if (!v.ok) rep.rejected.push(`${v.reason} ${JSON.stringify(d.action)}`);
else apply(bot, d.action);
}
}
rep.state = state;
rep.elapsed = now - start;
return rep;
}

View File

@@ -0,0 +1,32 @@
/** Each computer's character, fixed by its id (docs/09-game-engine.md §9). */
/** FNV-1a of the parts → [0, 1). Stable: the same bot decides the same way about the same thing. */
export function hash01(...parts: (string | number)[]): number {
let h = 2166136261;
const s = parts.join('\u0001');
for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
return (h >>> 0) / 2 ** 32;
}
/**
* Each computer's own pace (0.7 quick … 1.5 careful), fixed for the bot id so "컴퓨터 2" keeps its character for the
* whole game, while a new room's 컴퓨터 2 (new id) may be different.
*/
export function botPace(bot: string): number {
let h = 2166136261;
for (let i = 0; i < bot.length; i++) h = Math.imul(h ^ bot.charCodeAt(i), 16777619);
return 0.7 + ((h >>> 0) / 2 ** 32) * 0.8;
}
export interface BotPersona {
/** 똑똑한 편(근거를 보고 추리) / 허술한 편(느낌과 분위기를 따름). About half of the computers each. */
smart: boolean;
/** Reaction speed multiplier (`botPace`): 0.7 quick … 1.5 slow. */
pace: number;
/** 0.5 … 1: how likely it speaks up. */
chatty: number;
}
export function botPersona(bot: string): BotPersona {
return { smart: hash01(bot, 'smart') < 0.5, pace: botPace(bot), chatty: 0.5 + hash01(bot, 'chatty') * 0.5 };
}

View File

@@ -20,3 +20,30 @@ export interface BotInput<V = any, A = any> {
* (e.g. accept an undo request) — the caller validates it and falls back to the default policy.
*/
export type BotStrategy<V = any, A = any> = (input: BotInput<V, A>) => A;
/**
* Live bots: games where everybody acts at once on a phase clock and talks (마피아). Instead of one move when the game
* waits on it, each computer is asked again and again on its own timer and may also do nothing.
*/
export interface LiveBotInput<V = any> {
me: PlayerId;
/** Deep copy of `def.view(state, me)`. */
view: V;
/** Server clock (ms). */
now: number;
random: () => number;
persona: import('./persona').BotPersona;
/** Display names of the players (what people call each other in chat). */
names: Record<PlayerId, string>;
/** The bot's own notes for this game (what it already said or did). Kept by the caller between calls. */
memory: Record<string, unknown>;
}
export interface LiveBotDecision<A = any> {
/** What to do now, or null to keep watching. */
action: A | null;
/** Ask again after this many ms. */
next: number;
}
export type LiveBotStrategy<V = any, A = any> = (input: LiveBotInput<V>) => LiveBotDecision<A>;

View File

@@ -0,0 +1,154 @@
/** 마피아 computers (docs/games/mafia.md §13): legal, never stuck, talk like people, smart ones play better. */
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { botPace, botPersona, type BotPersona } from '../bots/persona';
import { liveBotPlayout } from '../bots/live-playout';
import { _internal, mafiaBot } from './bot';
import { chatProblem, compositionError, mafia, mafiaOptionsSchema, type MafiaOptions, type MafiaState } from './index';
const { fill, Reader } = _internal;
const isBot = (p: string) => p.startsWith('bot:');
const seats = (n: number, humans: number) => Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i + 1}:t${i}`));
const opts = (o: Partial<MafiaOptions> = {}) => mafiaOptionsSchema.parse(o);
const roleOf = (st: unknown, p: string) => (st as MafiaState).players.find((x) => x.id === p)!.role;
describe('Korean lines', () => {
test('josa follows the name: 컴퓨터 3님이 / 2번이 / 철수가 / 영희를', () => {
expect(fill('{X:이} 수상해요', { X: '컴퓨터 3님' })).toBe('컴퓨터 3님이 수상해요');
expect(fill('{X:이} 수상', { X: '2번' })).toBe('2번이 수상');
expect(fill('{X:이} 수상', { X: '철수' })).toBe('철수가 수상');
expect(fill('{X:은} 아니지', { X: '3' })).toBe('3은 아니지');
expect(fill('{X:은} 아니지', { X: '2' })).toBe('2는 아니지');
});
test('reads who is accused or cleared, and every way of writing a computer’s name', () => {
const view = mafia.view(mafia.setup({ players: seats(6, 1), options: opts(), rng: SeededRng.fromSeed(seedN(1)), now: 0 }), 'bot:2:t1');
const names = Object.fromEntries(view.players.map((p, i) => [p.id, i === 0 ? '철수' : `컴퓨터 ${i + 1}`]));
const r = new Reader({ me: 'bot:2:t1', view, now: 0, random: Math.random, persona: botPersona('bot:2:t1'), names, memory: {} });
const id = (n: number) => view.players[n - 1]!.id;
expect(r.stance('3번 마피아 아니야?').accused).toEqual([id(3)]);
expect(r.stance('컴퓨터 3님은 아닌 것 같아요').cleared).toEqual([id(3)]);
expect(r.stance('컴4 수상함').accused).toEqual([id(4)]);
expect(r.stance('컴퓨터2 너지?').accused).toEqual([id(2)]);
expect(r.stance('컴퓨터 3님보다 컴퓨터 5님이 더 수상해요')).toEqual({ accused: [id(5)], cleared: [id(3)] });
expect(r.stance('철수 의심돼요').accused).toEqual([id(1)]);
expect(r.mentions('5번 13번')).toHaveLength(1); // "13번" is not 3번
});
});
describe('whole games', () => {
const variants: [string, Partial<MafiaOptions>][] = [
['default', {}],
['all extra roles, roles revealed', { extraRoles: { soldier: true, politician: true, medium: true, lovers: true }, deathReveal: 'role' }],
['night first, nothing revealed, secret votes', { firstPhase: 'night', deathReveal: 'none', openVote: false, mafiaMustKill: 'random' }],
['house rules, short clock', { policeRevealRole: true, doctorSelfHeal: false, doctorRepeat: false, discussionMin: 30, discussionMax: 60, discussionPerAlive: 10, voteSeconds: 10, confirmSeconds: 5, nightSeconds: 15, defenseSeconds: 10 }],
];
for (const [label, o] of variants) {
test(`${label}: 4~12 players, one idle person + computers, and computers only — every game ends, nothing refused`, () => {
for (const n of [4, 6, 9, 12]) {
const options = opts(o);
if (compositionError(options, n)) continue;
for (const humans of [1, 0]) {
const r = liveBotPlayout(mafia, mafiaBot, { players: seats(n, humans), options, seed: seedN(n * 10 + humans), isBot });
expect(r.finished).toBe(true);
expect(r.rejected).toEqual([]);
expect(r.maxBotMs).toBeLessThan(50);
for (const line of r.chat) {
expect(chatProblem(line.text, true)).toBeNull();
expect(line.text).not.toMatch(/undefined|null|NaN|\{|bot:/);
}
const days = (r.state as MafiaState).day;
expect(r.chat.filter((c) => c.channel === 'day').length).toBeGreaterThanOrEqual(Math.min(days, 3));
}
}
}, 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 });
const st = r.state as MafiaState;
const mafiaIds = st.players.filter((p) => p.role === 'mafia').map((p) => p.id);
const names = Object.fromEntries(st.players.map((p, i) => [p.id, `컴퓨터 ${i + 1}`]));
for (const line of r.chat) {
if (line.channel !== 'day' || !mafiaIds.includes(line.from)) continue;
const view = mafia.view(st, line.from);
const reader = new Reader({ me: line.from, view, now: 0, random: Math.random, persona: botPersona(line.from), names, memory: {} });
for (const x of reader.stance(line.text).accused) expect(mafiaIds.filter((m) => m !== line.from)).not.toContain(x);
}
}
}, 60_000);
test('smart computers play better: smart town beats dumb mafia far more often than dumb town beats smart mafia', () => {
const rate = (townSmart: boolean, mafiaSmart: boolean) => {
let town = 0;
const n = 40;
for (let s = 1; s <= n; s++) {
const r = liveBotPlayout(mafia, mafiaBot, {
players: seats(7, 0),
seed: seedN(s),
isBot,
personaOf: (p, st): BotPersona => ({ smart: roleOf(st, p) === 'mafia' ? mafiaSmart : townSmart, pace: botPace(p), chatty: 0.8 }),
});
if ((r.state as MafiaState).winner === 'town') town++;
}
return town / n;
};
const good = rate(true, false);
const bad = rate(false, true);
expect(good - bad).toBeGreaterThan(0.2);
}, 60_000);
});
describe('timing and answers', () => {
/** Runs one computer alone in the current phase until it does something; returns when (ms after the phase began). */
function firstAction(st: MafiaState, me: string, persona: BotPersona, names: Record<string, string>, type: string): { at: number; action: unknown } | null {
const memory: Record<string, unknown> = {};
const start = st.phase.kind === 'ended' ? 0 : st.phase.startedAt;
for (let now = start; now < start + 120_000; ) {
const d = mafiaBot({ me, view: mafia.view(st, me), now, random: Math.random, persona, names, memory });
if (d.action && (d.action as { type: string }).type === type) return { at: now - start, action: d.action };
now += Math.max(50, d.next);
}
return null;
}
function toPhase(kind: string, players = seats(6, 1)) {
let st = mafia.setup({ players, options: opts(), rng: SeededRng.fromSeed(seedN(9)), now: 0 });
const rng = SeededRng.fromSeed(seedN(10));
let now = 0;
while (st.phase.kind !== kind) {
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 };
}
test('a quick computer votes sooner than a slow one; both vote inside the voting time', () => {
const { st, players } = toPhase('vote');
const names = Object.fromEntries(players.map((p, i) => [p, i ? `컴퓨터 ${i + 1}` : '철수']));
const bot = players[2]!;
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);
});
test('asked "컴퓨터 3 직업 뭐야?", computer 3 answers within seconds — and a mafia says it is a citizen', () => {
const { st, now, rng, players } = toPhase('discussion');
const names = Object.fromEntries(players.map((p, i) => [p, i ? `컴퓨터 ${i + 1}` : '철수']));
const asked = mafia.apply(st, players[0]!, { type: 'chat', channel: 'day', text: '컴퓨터 3 직업 뭐야?' }, { rng, now: now + 1000 }).state;
const bot = players[2]!;
const memory: Record<string, unknown> = {};
let answer: { text: string; at: number } | null = null;
for (let t = now + 1000; t < now + 20_000 && !answer; ) {
const d = mafiaBot({ me: bot, view: mafia.view(asked, bot), now: t, random: Math.random, persona: { smart: true, pace: 1, chatty: 0.8 }, names, memory });
const a = d.action as { type: string; text?: string } | null;
if (a?.type === 'chat' && memory.done && Object.keys(memory.done as object).some((k) => k.includes(':r:'))) answer = { text: a.text!, at: t - now - 1000 };
t += Math.max(50, d.next);
}
expect(answer).not.toBeNull();
expect(answer!.at).toBeLessThan(10_000);
expect(answer!.text).toMatch(/시민/);
});
});

View File

@@ -0,0 +1,736 @@
/**
* 마피아 computer players (docs/games/mafia.md §13). A live bot: the server asks each computer again and again on its
* own timer; it looks only at its own screen (`view`) and the chat, and either does one thing (say something, vote,
* pick at night, press 토론 끝내기) or keeps watching.
*
* Two characters (`persona.smart`):
* - 똑똑한 편: 근거로 추리한다 — 경찰 결과, 경찰이라고 나선 사람의 말, 투표 기록(시민을 처형한 표), 나를 몰아가는 사람,
* 말이 없는 사람. 경찰이면 마피아를 찾았을 때 밝히고, 의사는 경찰이라고 나선 사람을 지키고, 마피아는 경찰을 먼저 노린다.
* 존댓말로 차분하게 말한다.
* - 허술한 편: 느낌과 분위기를 따른다 — 의심이 거의 무작위이고 남이 몰아가면 따라간다. 반말·ㅋㅋ·짧은 말.
* Reaction speed comes from `persona.pace` (0.7 quick … 1.5 slow), so computers answer at different speeds.
*/
import type { PlayerId } from '@bg/engine';
import { hash01 } from '../bots/persona';
import type { LiveBotDecision, LiveBotInput } from '../bots/types';
import type { ChatView, MafiaAction, MafiaView, PlayerView, PrivateResult, PublicEvent } from './types';
type In = LiveBotInput<MafiaView>;
type Done = Record<string, true>;
interface Intent {
key: string;
due: number;
make: () => MafiaAction | null;
}
// ---------------------------------------------------------------- Korean helpers
/** Does the word end in a consonant (받침)? Digits are read in Korean (1 일, 3 삼 …). */
function batchim(word: string): boolean {
const c = word.trim().at(-1) ?? '';
const code = c.charCodeAt(0);
if (code >= 0xac00 && code <= 0xd7a3) return (code - 0xac00) % 28 !== 0;
if (/[0-9]/.test(c)) return '013678'.includes(c);
return /[lmnr]/i.test(c);
}
const JOSA: Record<string, [string, string]> = { 이: ['이', '가'], 은: ['은', '는'], 을: ['을', '를'], 이랑: ['이랑', '랑'], 아: ['아', '야'] };
/** `{X}` name, `{X:이}` name + 이/가 (also 은, 을, 이랑, 아). */
function fill(t: string, vars: Record<string, string>): string {
return t.replace(/\{(\w)(?::([^}]+))?\}/g, (_, k: string, j?: string) => {
const w = vars[k] ?? '';
if (!j) return w;
const pair = JOSA[j];
return pair ? w + (batchim(w) ? pair[0] : pair[1]) : w + j;
});
}
const pickBy = <T>(xs: readonly T[], u: number): T => xs[Math.min(xs.length - 1, Math.floor(u * xs.length))]!;
// ---------------------------------------------------------------- lines (smart: 존댓말, dumb: 반말)
const L = {
greet: {
smart: ['안녕하세요! 잘 부탁드려요', '반가워요~ 이번 판 재밌게 해요', '안녕하세요. 차분하게 찾아봐요', '다들 반가워요! 마피아 꼭 찾아요'],
dumb: ['ㅎㅇㅎㅇ', '안녕ㅋㅋ', '하이~ 나 시민임ㅋㅋ', 'ㅎㅇ 마피아 누구냐', '오 재밌겠다ㅋㅋ'],
},
died: {
smart: ['{V:이} 당했네요...', '{V} 아쉽네요. 오늘은 꼭 찾아봐요', '밤사이 {V:이}... 마피아가 움직였네요'],
dumb: ['헐 {V} 죽었어', '아 {V}ㅠㅠ', '헐 대박', 'ㄷㄷ 누가 {V} 죽였냐'],
},
healed: { smart: ['의사분 나이스예요!', '의사가 살렸네요. 좋아요'], dumb: ['오 의사 최고', '의사 ㄱㅇㄷ', '살았다ㅋㅋ'] },
soldier: { smart: ['{V:이} 군인이었군요!'], dumb: ['ㅋㅋ {V} 군인이네', '오 {V} 군인ㄷㄷ'] },
quiet: { smart: ['조용한 밤이었네요.', '아무도 안 당했네요. 다행이에요'], dumb: ['아무도 안 죽었네?', '오 다 살았다'] },
accuse: {
smart: ['제 생각엔 {X:이} 제일 수상해요.{R}', '{X:이} 좀 의심돼요.{R}', '오늘은 {X} 투표해 보는 게 어때요?{R}'],
dumb: ['{X} 수상함', '느낌상 {X} 마피아 같음ㅋㅋ', '{X} 너지?', '난 {X} 찍을거임', '{X} 뭔가 이상해'],
},
unsure: { smart: ['아직 잘 모르겠어요. 다들 어떻게 생각해요?', '정보가 부족하네요. 의견 들어 볼게요'], dumb: ['몰라ㅋㅋ', '다 수상해 보임'] },
agree: { smart: ['저도 {X:이} 수상하다고 봐요', '동의해요. {X:이} 의심돼요'], dumb: ['ㅇㅈ', '{X} 맞는듯', 'ㄹㅇ {X} 수상'] },
disagree: { smart: ['{X:은} 아닌 것 같아요', '{X}보다는 {Y:이} 더 수상한데요'], dumb: ['{X} 아닌듯?', '에이 {X:은} 아니지'] },
defend: {
smart: [
'저 시민이에요. 오히려 {Y:이} 더 수상해요',
'저 아니에요! 투표 기록 보시면 알 거예요',
'진짜 시민이에요. 저 말고 {Y} 봐 주세요',
'저를 처형하면 시민 한 명 잃는 거예요. 다시 생각해 주세요',
'저 믿어 주세요. 마피아는 {Y} 쪽이라고 봐요',
'억울해요. 저는 처음부터 마피아 찾으려고 했어요',
],
dumb: ['아 나 아니라고ㅠㅠ', '나 시민임 진짜', '왜 나야ㅋㅋㅋ', '억울하다;;', '나 아님 {Y} 의심해', '진짜 아니야 믿어줘', '나 죽이면 후회함'],
},
role: { smart: ['저 시민이에요', '저는 시민이에요. 아직 잘 모르겠어요'], dumb: ['나 시민ㅋㅋ', '비밀ㅋㅋ', '시민이지'] },
called: { smart: ['네?', '저요? 왜요?'], dumb: ['왜', 'ㅇ?', '부름?'] },
copFound: { smart: ['저 경찰이에요. {X} 조사했더니 마피아예요! 오늘 {X} 투표해요'], dumb: ['나 경찰인데 {X} 마피아임!!', '나 경찰임 {X} 마피아래'] },
copClean: { smart: ['저 경찰이에요. {X:은} 시민이었어요'], dumb: ['나 경찰임 {X} 시민이더라'] },
copCounter: { smart: ['제가 진짜 경찰이에요! {S:은} 가짜예요'], dumb: ['내가 경찰인데? {S} 거짓말함'] },
copHeard: { smart: ['경찰분 말 믿어 볼게요', '오 경찰이 나왔네요'], dumb: ['오 경찰 나옴', 'ㄹㅇ?'] },
doctor: { smart: ['저 의사예요. 저 처형하면 시민 팀 손해예요'], dumb: ['나 의사란 말이야ㅠ'] },
voted: { smart: ['{X} 찍었어요'], dumb: ['{X} 찍음', '몰라 {X}'] },
yes: { smart: ['찬성해요'], dumb: ['찬성ㅋㅋ', 'ㅊㅅ'] },
no: { smart: ['반대해요. 아직 확실하지 않아요'], dumb: ['반대', '난 반대'] },
filler: { smart: ['차분하게 생각해 봐요', '투표 기록을 잘 봐야겠어요'], dumb: ['ㅋㅋㅋㅋ', '아 모르겠다', '누구지...', '흠', '마피아 손ㅋㅋ', '나 믿어'] },
propose: { smart: ['오늘은 {X} 어때요?', '{X}부터 처리하죠'], dumb: ['{X} 죽이자', '{X} ㄱ'] },
proposeCop: { smart: ['{X:이} 경찰 같아요. {X}부터 해요'], dumb: ['{X} 경찰인듯 죽이자'] },
ok: { smart: ['좋아요', '그래요'], dumb: ['ㅇㅋ', 'ㄱㄱ'] },
lovers: { smart: ['우리 꼭 살아남아요', '조심해요'], dumb: ['살아남자ㅋㅋ', '너 믿음'] },
dead: { smart: ['아쉽네요. 남은 분들 화이팅!', '꼭 이겨 주세요'], dumb: ['아 억울해ㅋㅋ', '나 왜 죽었냐ㅠ', 'ㅂㅂ'] },
};
type LineKey = keyof typeof L;
// ---------------------------------------------------------------- reading the chat
const ACCUSE = /마피아|마피|수상|의심|범인|찍|투표|죽이|처형|거짓|가짜|너지|이상|맞는|맞음|맞아/;
const CLEAR = /아니|아닌|아님|시민|믿|무죄|살려/;
/** "3번 마피아 아니야?" is an accusation, not a defence. */
const ACCUSE_Q = /마피아\s*(아니(야|에요|지|냐|죠)?\s*\?|아냐|아닌가|아님\?)/;
const ASK = /\?|직업|뭐야|뭐예요|누구/;
const COP_CLAIM = /(저|제가|나|내가|난|전)\s*(는|가)?\s*(진짜\s*)?경찰|경찰(이에요|입니다|임|이야|이다|이예요|인데)/;
const NOT_COP = /경찰\s*(아니|아님)/;
const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/** Ways people write a name: "컴퓨터 3" is also 컴퓨터3, 컴3, 3번. */
function aliases(name: string): string[] {
const m = /^컴퓨터 (\d+)$/.exec(name);
return m ? [name, `컴퓨터${m[1]}`, `컴${m[1]}`, `${m[1]}번`] : [name];
}
interface Mention {
id: PlayerId;
at: number;
/** Text from this mention up to the next one. */
tail: string;
}
class Reader {
readonly v: MafiaView;
readonly me: PlayerId;
readonly smart: boolean;
private res: { id: PlayerId; re: RegExp }[];
constructor(private input: In) {
this.v = input.view;
this.me = input.me;
this.smart = input.persona.smart;
this.res = this.v.players.map((p) => {
const alts = aliases(input.names[p.id] ?? p.id).filter(Boolean).map(escapeRe);
return { id: p.id, re: new RegExp(`(?<![0-9])(${alts.join('|')})(?![0-9])`, 'g') };
});
}
private mentionCache = new Map<string, Mention[]>();
private stanceCache = new Map<string, { accused: PlayerId[]; cleared: PlayerId[] }>();
private claims: PlayerId[] | null = null;
mentions(text: string): Mention[] {
const hit = this.mentionCache.get(text);
if (hit) return hit;
const out: Mention[] = [];
for (const { id, re } of this.res) {
re.lastIndex = 0;
for (let m = re.exec(text); m; m = re.exec(text)) out.push({ id, at: m.index + m[0].length, tail: '' });
}
out.sort((a, b) => a.at - b.at);
for (let i = 0; i < out.length; i++) out[i]!.tail = text.slice(out[i]!.at, out[i + 1]?.at ?? text.length).slice(0, 24);
this.mentionCache.set(text, out);
return out;
}
/** Per message: whom it accuses / clears ("X보다 Y가 수상" clears X). */
stance(text: string): { accused: PlayerId[]; cleared: PlayerId[] } {
const hit = this.stanceCache.get(text);
if (hit) return hit;
const accused: PlayerId[] = [];
const cleared: PlayerId[] = [];
for (const m of this.mentions(text)) {
if (ACCUSE_Q.test(m.tail)) accused.push(m.id);
else if (/^\s*(님)?\s*보다/.test(m.tail) || CLEAR.test(m.tail)) cleared.push(m.id);
else if (ACCUSE.test(m.tail)) accused.push(m.id);
}
const out = { accused, cleared };
this.stanceCache.set(text, out);
return out;
}
private day: ChatView[] | null = null;
get dayChat(): ChatView[] {
return (this.day ??= this.v.chat.filter((m) => m.channel === 'day'));
}
/** People who said they are the police. */
copClaims(): PlayerId[] {
if (this.claims) return this.claims;
const out = new Set<PlayerId>();
for (const m of this.dayChat) if (COP_CLAIM.test(m.text) && !NOT_COP.test(m.text)) out.add(m.from);
return (this.claims = [...out]);
}
/** What a police claimant said about others. */
copSays(claimant: PlayerId): Map<PlayerId, 'mafia' | 'town'> {
const out = new Map<PlayerId, 'mafia' | 'town'>();
for (const m of this.dayChat) {
if (m.from !== claimant) continue;
for (const x of this.mentions(m.text)) {
if (x.id === claimant) continue;
if (/마피아/.test(x.tail) && !/아니|아님/.test(x.tail)) out.set(x.id, 'mafia');
else if (/시민|아니|아님/.test(x.tail)) out.set(x.id, 'town');
}
}
return out;
}
}
// ---------------------------------------------------------------- the bot
class MafiaBot {
private r: Reader;
private v: MafiaView;
private me: PlayerId;
private smart: boolean;
private pace: number;
private done: Done;
private phaseId: string;
private susCache = new Map<PlayerId, number>();
constructor(private input: In) {
this.r = new Reader(input);
this.v = input.view;
this.me = input.me;
this.smart = input.persona.smart;
this.pace = input.persona.pace;
this.done = ((input.memory.done as Done | undefined) ??= {});
this.phaseId = `${this.v.day}:${this.v.phase.kind}:${this.v.phase.startedAt}`;
}
private h(...k: (string | number)[]): number {
return hash01(this.me, ...k);
}
private get my() {
return this.v.my!;
}
private player(id: PlayerId): PlayerView | undefined {
return this.v.players.find((p) => p.id === id);
}
/** How this bot writes a name: 똑똑한 편 "OO님", 허술한 편 "3번"/"OO". */
private name(id: PlayerId): string {
const n = this.input.names[id] ?? '누군가';
if (this.smart) return `${n}님`;
const m = /^컴퓨터 (\d+)$/.exec(n);
return m ? `${m[1]}번` : n;
}
/** A line of this character; skips ones it already said and ones just said by others (people don't echo). */
private line(key: LineKey, salt: string | number, vars?: Record<string, string>): string;
private line(key: LineKey, salt: string | number, vars: Record<string, string>, optional: true): string | null;
private line(key: LineKey, salt: string | number, vars: Record<string, string> = {}, optional = false): string | null {
const set = L[key];
const pool = this.smart ? set.smart : set.dumb;
const used = new Set([
...this.v.chat.filter((m) => m.from === this.me).map((m) => m.text),
...this.v.chat.slice(-12).map((m) => m.text),
]);
const first = Math.floor(this.h('line', key, salt, this.v.day) * pool.length);
for (let i = 0; i < pool.length; i++) {
const text = fill(pool[(first + i) % pool.length]!, vars);
if (!used.has(text)) return text;
}
return optional ? null : fill(pool[first]!, vars);
}
private say(channel: 'day' | 'mafia' | 'dead' | 'lovers', text: string): MafiaAction | null {
const ch = this.v.channels.find((c) => c.channel === channel);
return ch?.canWrite ? { type: 'chat', channel, text } : null;
}
/** Thinking/typing time (ms) for a reaction, scaled by this computer's pace. */
private react(baseMs: number, key: string): number {
return Math.round(baseMs * (0.6 + this.h('react', key) * 0.9) * this.pace);
}
private get phaseStart(): number {
return this.v.phase.startedAt;
}
private get phaseLen(): number {
return Math.max(1000, (this.v.phase.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. */
private inPhase(lo: number, hi: number, key: string, cap = 0.8): number {
const ms = (lo + (hi - lo) * this.h('t', key, this.phaseId)) * 1000 * this.pace;
return this.phaseStart + Math.min(ms, this.phaseLen * cap);
}
private myMessagesThisPhase(): number {
return this.v.chat.filter((m) => m.from === this.me && m.at >= this.phaseStart).length;
}
// ---------------------------------------------------------------- judgement
private aliveOthers(): PlayerView[] {
return this.v.players.filter((p) => p.alive && p.id !== this.me);
}
private isMate(id: PlayerId): boolean {
return this.my.mates.includes(id);
}
private results(): PrivateResult[] {
return this.my.results;
}
/** Town view: how likely `x` is mafia (higher = more suspicious). */
sus(x: PlayerId): number {
const hit = this.susCache.get(x);
if (hit !== undefined) return hit;
const smart = this.smart;
const p = this.player(x);
let s = (this.h('noise', x, this.v.day) - 0.5) * (smart ? 1 : 6);
if (p?.team === 'town' || (this.my.role === 'lover' && this.isMate(x))) s -= 100;
if (p?.team === 'mafia') s += 100;
for (const r of this.results()) {
if (r.kind !== 'investigate' || r.target !== x) continue;
s += r.result === 'mafia' ? 100 : r.result === 'notMafia' ? -100 : 0;
if (r.result !== 'mafia' && r.result !== 'notMafia') s -= 100; // policeRevealRole: a town role
}
const cops = this.r.copClaims().filter((c) => c !== this.me);
if (this.my.role === 'police' && cops.includes(x)) s += smart ? 100 : 5; // someone else claims my job
else if (cops.length >= 2 && cops.includes(x)) s += smart ? 2 : 0.5;
if (cops.length === 1 && cops[0] !== x && this.my.role !== 'police') {
const said = this.r.copSays(cops[0]!).get(x);
if (said === 'mafia') s += smart ? 6 : 4;
if (said === 'town') s -= smart ? 3 : 1;
}
let pile = 0;
let atMe = 0;
for (const m of this.r.dayChat) {
if (m.from === this.me || m.from === x) {
if (m.from === x && this.my.team === 'town' && this.r.stance(m.text).accused.includes(this.me)) atMe++;
continue;
}
if (this.r.stance(m.text).accused.includes(x)) pile++;
}
s += smart ? Math.min(pile * 0.5, 2) : Math.min(pile * 1.2, 4);
s += Math.min(atMe, 2) * (smart ? 1.5 : 0.8);
if (smart) {
s += this.voteEvidence(x);
if (this.v.day >= 2 && !this.r.dayChat.some((m) => m.from === x)) s += 0.7;
}
this.susCache.set(x, s);
return s;
}
/** Votes that sent a town player out are suspicious; votes that caught a mafia are not. */
private voteEvidence(x: PlayerId): number {
let s = 0;
const deaths = new Map<string, PublicEvent & { t: 'death' }>();
for (const e of this.v.events) if (e.t === 'death' && e.by === 'vote') deaths.set(`${e.day}:${e.p}`, e);
for (const e of this.v.events) {
if (e.t !== 'vote' || !e.votes || !e.accused || e.votes[x] !== e.accused) continue;
const d = deaths.get(`${e.day}:${e.accused}`);
if (d?.team === 'town') s += 1.5;
if (d?.team === 'mafia') s -= 1.5;
}
return s;
}
/** Mafia view: whom to push on the town (never a team mate). */
private push(x: PlayerId): number {
if (this.isMate(x)) return -1000;
let s = (this.h('push', x, this.v.day) - 0.5) * (this.smart ? 1 : 6);
if (this.smart) {
for (const m of this.r.dayChat) if (m.from !== this.me && this.r.stance(m.text).accused.includes(x)) s += 0.6;
if (this.r.copClaims().includes(x)) s += 3;
if (this.player(x)?.team === 'town') s -= 50; // a publicly known town role convinces nobody
}
return s;
}
private top(candidates: PlayerId[], score: (x: PlayerId) => number): PlayerId | null {
let best: PlayerId | null = null;
let bs = -Infinity;
for (const c of candidates) {
const s = score(c);
if (s > bs) {
bs = s;
best = c;
}
}
return best;
}
/** Who I'd say is suspicious, as either team. */
private suspect(): PlayerId | null {
const others = this.aliveOthers().map((p) => p.id);
if (this.my.team === 'mafia') return this.top(others, (x) => this.push(x));
const t = this.top(others, (x) => this.sus(x));
return t && this.sus(t) > -50 ? t : null;
}
private reasonFor(x: PlayerId): string {
if (!this.smart) return '';
if (this.my.team === 'mafia') return this.r.copClaims().includes(x) ? ' 경찰이라는 말 못 믿겠어요.' : '';
if (this.results().some((r) => r.target === x && r.result === 'mafia')) return '';
if (this.my.role === 'police' && this.r.copClaims().includes(x)) return ' 경찰은 저예요. 가짜 경찰이에요!';
const cops = this.r.copClaims().filter((c) => c !== this.me);
if (cops.length === 1 && this.r.copSays(cops[0]!).get(x) === 'mafia') return ' 경찰분이 마피아라고 했잖아요.';
if (this.voteEvidence(x) > 0) return ' 시민을 처형하는 쪽에 표를 던졌어요.';
if (this.r.dayChat.some((m) => m.from === x && this.r.stance(m.text).accused.includes(this.me))) return ' 저를 몰아가는 게 이상해요.';
if (this.v.day >= 2 && !this.r.dayChat.some((m) => m.from === x)) return ' 말이 너무 없어요.';
return '';
}
// ---------------------------------------------------------------- what to do
intents(): Intent[] {
const v = this.v;
const k = v.phase.kind;
const out: Intent[] = [];
const key = (s: string) => `${this.phaseId}:${s}`;
if (!this.my.alive) {
const died = this.player(this.me)?.diedDay;
const t = v.events.find((e) => e.t === 'death' && e.p === this.me)?.at;
if (t !== undefined && died != null && this.input.now - t < 60_000 && this.h('deadTalk') < (this.smart ? 0.5 : 0.7)) {
out.push({ key: 'dead', due: t + this.react(6000, 'dead'), make: () => this.say('dead', this.line('dead', 'x')) });
}
return out;
}
const cap = this.smart ? 4 : 5;
const chat = (text: string | null) => (text && this.myMessagesThisPhase() < cap ? this.say('day', text) : null);
if (k === 'greeting') {
if (this.h('greet') < 0.85) out.push({ key: key('greet'), due: this.inPhase(2, 12, 'greet'), make: () => chat(this.line('greet', 'g', {}, true)) });
if (this.my.canReady) out.push({ key: key('ready'), due: this.inPhase(15, 30, 'ready', 0.7), make: () => ({ type: 'readyEarly' }) });
}
if (k === 'discussion') {
const news = v.events.filter((e) => e.at === this.phaseStart && (e.t === 'death' || e.t === 'healed' || e.t === 'soldier' || e.t === 'quiet'));
if (news.length && this.h('news', v.day) < 0.55) {
out.push({
key: key('news'),
due: this.inPhase(1.5, 5, 'news'),
make: () => {
// Two people already said it: no need for a chorus.
if (v.chat.filter((m) => m.channel === 'day' && m.at >= this.phaseStart && m.from !== this.me).length >= 2) return null;
const e = news[0]!;
if (e.t === 'death') return chat(this.line('died', e.p, { V: this.name(e.p) }, true));
if (e.t === 'soldier') return chat(this.line('soldier', e.p, { V: this.name(e.p) }, true));
return chat(this.line(e.t === 'healed' ? 'healed' : 'quiet', v.day, {}, true));
},
});
}
const found = this.copReveal();
if (found) out.push({ key: key('cop'), due: this.inPhase(3, 8, 'cop'), make: () => chat(found()) });
if (this.h('accuse', v.day) < (this.smart ? 0.85 : 0.6) * this.input.persona.chatty * 1.3) {
out.push({
key: key('accuse'),
due: this.inPhase(10, 40, 'accuse', 0.6),
make: () => {
const x = this.suspect();
if (!x || (this.smart && this.my.team === 'town' && this.sus(x) < 0.6)) return chat(this.line('unsure', v.day));
return chat(this.line('accuse', x, { X: this.name(x), R: this.reasonFor(x) }));
},
});
}
if (!this.smart && this.h('filler', v.day) < 0.4) {
out.push({ key: key('filler'), due: this.inPhase(5, 50, 'filler', 0.7), make: () => chat(this.line('filler', v.day, {}, true)) });
}
if (this.my.canReady) out.push({ key: key('ready'), due: this.phaseStart + this.phaseLen * (0.55 + 0.25 * this.h('ready', v.day)), make: () => ({ type: 'readyEarly' }) });
}
if (k === 'greeting' || k === 'discussion' || k === 'vote' || k === 'confirm') out.push(...this.replies(key, chat));
if (k === 'vote' && this.my.vote === null) {
out.push({
key: key('vote'),
due: this.inPhase(this.smart ? 3 : 1.5, this.smart ? 10 : 14, 'vote', 0.75),
make: () => {
const x = this.suspect();
return { type: 'vote', target: x ?? 'abstain' };
},
});
}
if (k === 'vote' && this.my.vote && this.my.vote !== 'abstain' && this.h('votedTalk', v.day) < 0.3) {
const x = this.my.vote;
out.push({ key: key('votedTalk'), due: this.inPhase(1, 4, 'votedTalk') + 2000, make: () => chat(this.line('voted', x, { X: this.name(x) })) });
}
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)) });
}
if (k === 'confirm' && this.my.canConfirm && this.my.ballot === null) {
out.push({
key: key('confirm'),
due: this.inPhase(1.5, this.smart ? 5 : 7, 'confirm', 0.7),
make: () => {
const choice = this.ballot();
return { type: 'confirm', choice };
},
});
}
if (k === 'confirm' && this.my.ballot && this.h('ballotTalk', v.day) < 0.2) {
const b = this.my.ballot;
out.push({ key: key('ballotTalk'), due: this.inPhase(2, 6, 'ballotTalk') + 1000, make: () => chat(this.line(b === 'yes' ? 'yes' : 'no', v.day)) });
}
if (k === 'night') out.push(...this.night(key));
return out;
}
private ballot(): 'yes' | 'no' {
const acc = this.v.phase.accused;
if (!acc) return 'no';
if (this.my.team === 'mafia') {
if (this.isMate(acc)) return 'no';
return this.smart || this.h('ballot', this.v.day) < 0.8 ? 'yes' : 'no';
}
if (!this.smart) return this.sus(acc) > -50 && this.h('ballot', this.v.day) < 0.7 ? 'yes' : 'no';
const others = this.aliveOthers().map((p) => this.sus(p.id)).sort((a, b) => b - a);
const mine = this.sus(acc);
return mine > 1.5 || (others.length > 0 && mine >= others[Math.min(1, others.length - 1)]!) ? 'yes' : 'no';
}
/** Smart police: says it found a mafia (once per result); a dumb police blurts out any result. */
private copReveal(): (() => string | null) | null {
if (this.my.role !== 'police') return null;
const rs = this.results().filter((r) => r.kind === 'investigate' && this.player(r.target)?.alive);
const said = this.r.dayChat.filter((m) => m.from === this.me && /경찰/.test(m.text));
const fresh = rs.filter((r) => !said.some((m) => this.r.mentions(m.text).some((x) => x.id === r.target)));
const mafiaHit = fresh.find((r) => r.result === 'mafia');
if (mafiaHit) return () => this.line('copFound', mafiaHit.target, { X: this.name(mafiaHit.target) });
if (!this.smart && fresh.length && this.h('blurt', this.v.day) < 0.5) {
const r = fresh.at(-1)!;
return () => this.line('copClean', r.target, { X: this.name(r.target) });
}
return null;
}
private defenseLine(first: boolean): string {
const y = this.top(
this.aliveOthers().map((p) => p.id),
(x) => (this.my.team === 'mafia' ? this.push(x) : this.sus(x)),
);
const Y = y ? this.name(y) : '다른 사람';
if (this.my.role === 'police' && (first || this.smart)) {
const rs = this.results().filter((r) => r.kind === 'investigate');
const parts = rs.map((r) => `${this.name(r.target)} ${r.result === 'mafia' ? '마피아' : '시민'}`);
return this.smart ? `저 경찰이에요. 조사 결과: ${parts.join(', ') || '아직 없어요'}. 저를 처형하면 안 돼요` : `나 경찰이라고!! ${parts.join(', ')}`;
}
if (this.my.role === 'doctor' && !first && this.h('docClaim', this.v.day) < 0.6) return this.line('doctor', 'd');
return this.line('defend', first ? 'a' : 'b', { Y });
}
/** Answers to chat: being named, a police claim, someone accusing someone. */
private replies(key: (s: string) => string, chat: (t: string | null) => MafiaAction | null): Intent[] {
const out: Intent[] = [];
const k = this.v.phase.kind;
const talky = k === 'greeting' || k === 'discussion';
const recent = this.r.dayChat.filter((m) => m.from !== this.me && m.at >= this.phaseStart && m.at >= this.input.now - 25_000);
for (const m of recent) {
const named = this.r.mentions(m.text);
const st = this.r.stance(m.text);
const delay = (base: number) => m.at + this.react(base + 60 * [...m.text].length, m.key);
if (named.some((x) => x.id === this.me)) {
// A question or an accusation always gets an answer; just being named, usually.
const must = ASK.test(m.text) || st.accused.includes(this.me);
if (!must && this.h('reply', m.key) > (this.smart ? 0.9 : 0.7)) continue;
out.push({
key: key(`r:${m.key}`),
due: delay(2500),
make: () => {
const copSaysMe = COP_CLAIM.test(m.text) && st.accused.includes(this.me);
if (copSaysMe && this.my.team === 'mafia' && this.smart && this.h('counter', m.key) < 0.5) {
return chat(this.line('copCounter', m.key, { S: this.name(m.from) }));
}
if (st.accused.includes(this.me)) return chat(this.defenseLine(true));
if (ASK.test(m.text)) return chat(this.line('role', m.key));
if (st.cleared.includes(this.me)) return chat(this.smart ? '감사해요!' : 'ㅇㅇ 고마움');
return chat(this.line('called', m.key));
},
});
continue;
}
if (!talky) continue;
if (COP_CLAIM.test(m.text) && !NOT_COP.test(m.text)) {
const realCop = this.my.role === 'police';
const counter = this.my.team === 'mafia' && this.smart && st.accused.some((x) => x === this.me || this.isMate(x)) && this.h('counter', m.key) < 0.5;
if (realCop || counter) {
out.push({ key: key(`c:${m.key}`), due: delay(2000), make: () => chat(this.line('copCounter', m.key, { S: this.name(m.from) })) });
continue;
}
if (this.h('heard', m.key) < 0.3) out.push({ key: key(`h:${m.key}`), due: delay(3000), make: () => chat(this.line('copHeard', m.key, {}, true)) });
continue;
}
const x = st.accused.find((id) => id !== this.me && id !== m.from);
if (!x || this.h('chime', m.key) > (this.smart ? 0.25 : 0.3)) continue;
out.push({
key: key(`a:${m.key}`),
due: delay(3500),
make: () => {
const fine = this.my.team === 'mafia' ? !this.isMate(x) : this.sus(x) >= 0.5 || !this.smart;
if (fine) return chat(this.line('agree', m.key, { X: this.name(x) }));
const y = this.suspect();
return chat(this.line('disagree', m.key, { X: this.name(x), Y: y && y !== x ? this.name(y) : '다른 사람' }));
},
});
}
return out;
}
private night(key: (s: string) => string): Intent[] {
const out: Intent[] = [];
const n = this.my.night;
if (this.my.role === 'lover' && this.h('lovers', this.v.day) < 0.4) {
out.push({ key: key('lovers'), due: this.inPhase(3, 12, 'lovers'), make: () => this.say('lovers', this.line('lovers', this.v.day)) });
}
if (!n?.action || n.targets.length === 0) return out;
if (n.action === 'mafiaTarget') return [...out, ...this.mafiaNight(key)];
if (n.choice !== null) return out;
out.push({
key: key('act'),
due: this.inPhase(3, 12, 'act', 0.7),
make: () => {
const t = this.nightPick();
return t ? ({ type: n.action, target: t } as MafiaAction) : null;
},
});
return out;
}
private nightPick(): PlayerId | null {
const n = this.my.night!;
const ts = n.targets;
const rnd = (salt: string) => pickBy(ts, this.h('night', salt, this.v.day));
if (!this.smart) return rnd(n.action ?? '');
switch (n.action) {
case 'investigate': {
const seen = new Set(this.results().map((r) => r.target));
const fresh = ts.filter((t) => !seen.has(t));
return this.top(fresh.length ? fresh : ts, (x) => this.sus(x));
}
case 'heal': {
const cops = this.r.copClaims().filter((c) => ts.includes(c) && c !== this.me);
if (cops.length === 1) return cops[0]!;
if (ts.includes(this.me) && this.h('self', this.v.day) < 0.5) return this.me;
return this.top(ts, (x) => -this.sus(x) + this.h('heal', x, this.v.day));
}
case 'mediumPeek': {
const seen = new Set(this.results().map((r) => r.target));
return ts.find((t) => !seen.has(t)) ?? rnd('peek');
}
default:
return rnd('x');
}
}
/** Mafia at night: suggest in the mafia chat (or follow a mate's suggestion), then pick if nobody has. */
private mafiaNight(key: (s: string) => string): Intent[] {
const n = this.my.night!;
const mafiaChat = this.v.chat.filter((m) => m.channel === 'mafia' && m.at >= this.phaseStart);
const proposal = (): PlayerId | null => {
for (const m of [...mafiaChat].reverse()) {
if (m.from === this.me) continue;
const x = this.r.mentions(m.text).find((t) => n.targets.includes(t.id));
if (x) return x.id;
}
return null;
};
const own = (): PlayerId | null => {
if (!this.smart) return pickBy(n.targets, this.h('kill', this.v.day));
const cops = this.r.copClaims().filter((c) => n.targets.includes(c));
if (cops.length) return cops[0]!;
let best: PlayerId | null = null;
let bs = -Infinity;
for (const t of n.targets) {
let s = this.h('kill', t, this.v.day);
for (const m of this.r.dayChat) if (m.from === t && this.r.stance(m.text).accused.some((x) => x === this.me || this.isMate(x))) s += 1;
if (s > bs) {
bs = s;
best = t;
}
}
return best;
};
const out: Intent[] = [];
const humanMate = this.my.mates.some((m) => !m.startsWith('bot:'));
if (this.h('mchat', this.v.day) < 0.8) {
out.push({
key: key('mchat'),
due: this.inPhase(2, 7, 'mchat', 0.5),
make: () => {
const p = proposal();
if (p) return this.say('mafia', this.line('ok', this.v.day));
const t = own();
if (!t) return null;
const cop = this.r.copClaims().includes(t);
return this.say('mafia', this.line(cop ? 'proposeCop' : 'propose', t, { X: this.name(t) }));
},
});
}
if (n.choice === null) {
out.push({
key: key('kill'),
// With a person on the team, leave them time to choose first.
due: this.inPhase(humanMate ? 10 : 5, humanMate ? 16 : 12, 'kill', 0.75),
make: () => {
const cur = this.my.night?.choice;
if (cur) return null;
const t = proposal() ?? own();
return t ? { type: 'mafiaTarget', target: t } : null;
},
});
}
return out;
}
}
/** Live strategy: at most one action per call; asks again soon so it can answer the chat. */
export function mafiaBot(input: In): LiveBotDecision<MafiaAction> {
const v = input.view;
if (v.phase.kind === 'ended' || !v.my) return { action: null, next: 5000 };
const bot = new MafiaBot(input);
const done = input.memory.done as Done;
const list = bot.intents().sort((a, b) => a.due - b.due);
let soonest = Infinity;
for (const it of list) {
if (done[it.key]) continue;
if (it.due > input.now) {
soonest = Math.min(soonest, it.due);
continue;
}
done[it.key] = true;
const action = it.make();
if (action) return { action, next: Math.round(400 + 600 * input.persona.pace) };
}
const idle = v.my.alive ? 1500 : 4000;
const wait = soonest === Infinity ? idle : soonest - input.now;
return { action: null, next: Math.max(250, Math.min(idle * input.persona.pace, wait)) };
}
export const _internal = { fill, batchim, Reader };