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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 02:54:14 +09:00

155 lines
8.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 마피아 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(/시민/);
});
});