마피아 컴퓨터 플레이어: 각자 타이머로 말하고 투표하는 라이브 봇, 똑똑한 편/허술한 편, 반응 속도 차이
- 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:
@@ -1,7 +1,7 @@
|
|||||||
/** Computer players in rooms (docs/06-lobby-rooms.md §12): seating rules, practice rooms, driving, records, restore. */
|
/** Computer players in rooms (docs/06-lobby-rooms.md §12): seating rules, practice rooms, driving, records, restore. */
|
||||||
import { afterEach, describe, expect, test } from 'bun:test';
|
import { afterEach, describe, expect, test } from 'bun:test';
|
||||||
import { GAMES } from '@bg/games';
|
import { GAMES } from '@bg/games';
|
||||||
import { BOT_STRATEGIES } from '@bg/games/bots';
|
import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES } from '@bg/games/bots';
|
||||||
import { BOT_GAMES, ClientMessage, botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
import { BOT_GAMES, ClientMessage, botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||||
import { openDb } from '../db';
|
import { openDb } from '../db';
|
||||||
import { botPace, defaultBotDelay, type BotDelayInput } from './bots';
|
import { botPace, defaultBotDelay, type BotDelayInput } from './bots';
|
||||||
@@ -48,10 +48,11 @@ function drive(room: Room, max = 500): number {
|
|||||||
const bots = (room: Room) => room.seatedIds().filter(isBotId);
|
const bots = (room: Room) => room.seatedIds().filter(isBotId);
|
||||||
|
|
||||||
describe('bot list', () => {
|
describe('bot list', () => {
|
||||||
test('BOT_GAMES matches the strategies and leaves out real-time / talk games', () => {
|
test('BOT_GAMES matches the strategies (turn-based + live) and leaves out real-time / drawing games', () => {
|
||||||
expect([...BOT_GAMES].sort()).toEqual(Object.keys(BOT_STRATEGIES).sort());
|
expect([...BOT_GAMES].sort()).toEqual([...Object.keys(BOT_STRATEGIES), ...Object.keys(LIVE_BOT_STRATEGIES)].sort());
|
||||||
for (const id of BOT_GAMES) expect(GAMES[id]).toBeDefined();
|
for (const id of BOT_GAMES) expect(GAMES[id]).toBeDefined();
|
||||||
for (const id of ['dobble', 'halli-galli', 'catchmind', 'mafia']) expect(BOT_GAMES).not.toContain(id);
|
for (const id of ['dobble', 'halli-galli', 'catchmind']) expect(BOT_GAMES).not.toContain(id);
|
||||||
|
expect(BOT_GAMES).toContain('mafia');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('each computer has its own fixed pace between quick and careful', () => {
|
test('each computer has its own fixed pace between quick and careful', () => {
|
||||||
@@ -205,7 +206,7 @@ describe('addBot / removeBot', () => {
|
|||||||
describe('createPractice', () => {
|
describe('createPractice', () => {
|
||||||
test('a private room with just enough computers to start; never offered by quick play', () => {
|
test('a private room with just enough computers to start; never offered by quick play', () => {
|
||||||
const { manager, conn } = harness();
|
const { manager, conn } = harness();
|
||||||
const expected: Record<string, number> = { omok: 1, mahjong: 2, bang: 3, dalmuti: 3, quoridor: 1, yacht: 1 };
|
const expected: Record<string, number> = { omok: 1, mahjong: 2, bang: 3, dalmuti: 3, quoridor: 1, yacht: 1, mafia: 5 };
|
||||||
for (const [gameId, n] of Object.entries(expected)) {
|
for (const [gameId, n] of Object.entries(expected)) {
|
||||||
const room = manager.createPractice(`host-${gameId}`, gameId);
|
const room = manager.createPractice(`host-${gameId}`, gameId);
|
||||||
if (typeof room === 'string') throw new Error(room);
|
if (typeof room === 'string') throw new Error(room);
|
||||||
@@ -216,7 +217,7 @@ describe('createPractice', () => {
|
|||||||
expect(room.start(`host-${gameId}`)).toBeNull();
|
expect(room.start(`host-${gameId}`)).toBeNull();
|
||||||
expect(room.game!.players).toContain(`host-${gameId}`);
|
expect(room.game!.players).toContain(`host-${gameId}`);
|
||||||
}
|
}
|
||||||
expect(manager.createPractice('X', 'mafia')).toBe('이 게임은 컴퓨터와 할 수 없어요.');
|
expect(manager.createPractice('X', 'dobble')).toBe('이 게임은 컴퓨터와 할 수 없어요.');
|
||||||
// Quick play never lands in a practice room.
|
// Quick play never lands in a practice room.
|
||||||
const qp = manager.quickPlay('Q', 'omok');
|
const qp = manager.quickPlay('Q', 'omok');
|
||||||
if (typeof qp === 'string') throw new Error(qp);
|
if (typeof qp === 'string') throw new Error(qp);
|
||||||
@@ -225,6 +226,36 @@ describe('createPractice', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('마피아: talking computers (live bots)', () => {
|
||||||
|
test('each computer looks at the game on its own clock: they greet, talk, vote at different moments and the game goes on', () => {
|
||||||
|
const h = harness();
|
||||||
|
const room = h.manager.createPractice('A', 'mafia') as Room;
|
||||||
|
rooms.push(room);
|
||||||
|
room.join(h.conn('A'), 'player');
|
||||||
|
expect(room.start('A')).toBeNull();
|
||||||
|
const ids = room.game!.players.filter(isBotId);
|
||||||
|
expect(room.bots.dueAt).not.toBeNull(); // computers are watching from the start
|
||||||
|
const voteTimes = new Map<string, number>();
|
||||||
|
for (let i = 0; i < 10 * 60 * 4 && !room.game!.finished; i++) {
|
||||||
|
h.clock.advance(250);
|
||||||
|
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||||
|
const ph = (room.game!.state as { phase: { kind: string; votes?: Record<string, string> } }).phase;
|
||||||
|
if (ph.kind === 'vote') for (const v of Object.keys(ph.votes ?? {})) if (!voteTimes.has(v)) voteTimes.set(v, h.clock.now());
|
||||||
|
const d = room.effectiveDeadline();
|
||||||
|
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||||
|
}
|
||||||
|
const s = room.game!.state as { chat: { from: string; channel: string; text: string }[]; events: { t: string }[] };
|
||||||
|
const talkers = new Set(s.chat.filter((m) => m.channel === 'day' && isBotId(m.from)).map((m) => m.from));
|
||||||
|
expect(talkers.size).toBeGreaterThanOrEqual(3);
|
||||||
|
expect(s.events.some((e) => e.t === 'vote')).toBe(true);
|
||||||
|
// Votes came in one by one, not all at the same instant.
|
||||||
|
expect(new Set(voteTimes.values()).size).toBeGreaterThan(1);
|
||||||
|
expect(ids.length).toBe(5);
|
||||||
|
// Names in chat are the players' display names ("컴퓨터 n" / "n번"), never raw ids.
|
||||||
|
expect(s.chat.some((m) => m.text.includes('bot:'))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('playing with bots', () => {
|
describe('playing with bots', () => {
|
||||||
function omokVsBot() {
|
function omokVsBot() {
|
||||||
const h = harness();
|
const h = harness();
|
||||||
|
|||||||
@@ -5,7 +5,9 @@
|
|||||||
*/
|
*/
|
||||||
import type { AnyGameDefinition } from '@bg/engine';
|
import type { AnyGameDefinition } from '@bg/engine';
|
||||||
import { isBotId } from '@bg/shared';
|
import { isBotId } from '@bg/shared';
|
||||||
import { botCandidates, decideBotAction } from '@bg/games/bots';
|
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, type LiveBotStrategy } from '@bg/games/bots';
|
||||||
|
|
||||||
|
export { botPace };
|
||||||
|
|
||||||
export interface BotRoom {
|
export interface BotRoom {
|
||||||
readonly status: string;
|
readonly status: string;
|
||||||
@@ -17,6 +19,8 @@ export interface BotRoom {
|
|||||||
/** Runs the action as `actor` through the room's normal path; returns an error message on rejection. */
|
/** Runs the action as `actor` through the room's normal path; returns an error message on rejection. */
|
||||||
run(actor: string, action: unknown): string | null;
|
run(actor: string, action: unknown): string | null;
|
||||||
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
|
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
|
||||||
|
/** Display name of a player (live bots talk about each other by name). */
|
||||||
|
nameOf?(id: string): string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What a planned computer move looks like, for its thinking time. */
|
/** What a planned computer move looks like, for its thinking time. */
|
||||||
@@ -31,16 +35,6 @@ export interface BotDelayInput {
|
|||||||
followUp: boolean;
|
followUp: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Human-like thinking time (ms). A forced move still takes a moment to notice (0.7~1.3 s); a real choice takes longer
|
* Human-like thinking time (ms). A forced move still takes a moment to notice (0.7~1.3 s); a real choice takes longer
|
||||||
* the more moves there are (1.6~3.9 s), and now and then the computer hesitates (+1~3 s). Each bot scales it by its
|
* the more moves there are (1.6~3.9 s), and now and then the computer hesitates (+1~3 s). Each bot scales it by its
|
||||||
@@ -70,6 +64,10 @@ export class BotDriver {
|
|||||||
private planned: string | null = null;
|
private planned: string | null = null;
|
||||||
/** Bot whose action is being played right now: if it is still on afterwards, its next move is a follow-up. */
|
/** Bot whose action is being played right now: if it is still on afterwards, its next move is a follow-up. */
|
||||||
private acting: string | null = null;
|
private acting: string | null = null;
|
||||||
|
/** Live games (마피아): when each computer looks at the game again, and its notes for the current game. */
|
||||||
|
private liveDue = new Map<string, number>();
|
||||||
|
private liveMemory = new Map<string, Record<string, unknown>>();
|
||||||
|
private liveGame: unknown = null;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private room: BotRoom,
|
private room: BotRoom,
|
||||||
@@ -79,6 +77,7 @@ export class BotDriver {
|
|||||||
|
|
||||||
/** Plans the next bot action if the game is waiting on a bot. Keeps an already planned one (the bot is "thinking"). */
|
/** Plans the next bot action if the game is waiting on a bot. Keeps an already planned one (the bot is "thinking"). */
|
||||||
schedule(): void {
|
schedule(): void {
|
||||||
|
if (this.liveStrategy()) return this.scheduleLive();
|
||||||
if (this.dueAt !== null) return;
|
if (this.dueAt !== null) return;
|
||||||
const next = this.next();
|
const next = this.next();
|
||||||
if (!next) return;
|
if (!next) return;
|
||||||
@@ -96,6 +95,67 @@ export class BotDriver {
|
|||||||
this.timer = null;
|
this.timer = null;
|
||||||
this.dueAt = null;
|
this.dueAt = null;
|
||||||
this.planned = null;
|
this.planned = null;
|
||||||
|
this.liveDue.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private liveStrategy(): LiveBotStrategy | null {
|
||||||
|
return LIVE_BOT_STRATEGIES[this.room.def.id] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Live games: every computer has its own timer and is asked again and again (it may also do nothing), so several
|
||||||
|
* computers talk and vote at the same time, each at its own speed. A planned look stays planned.
|
||||||
|
*/
|
||||||
|
private scheduleLive(): void {
|
||||||
|
const g = this.room.game;
|
||||||
|
if (!g || g.finished || this.room.status !== 'playing') {
|
||||||
|
if (this.timer) clearTimeout(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
this.dueAt = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.liveGame !== g) {
|
||||||
|
this.liveGame = g;
|
||||||
|
this.liveMemory.clear();
|
||||||
|
this.liveDue.clear();
|
||||||
|
}
|
||||||
|
const now = this.room.now();
|
||||||
|
for (const p of g.players) {
|
||||||
|
if (isBotId(p) && !this.liveDue.has(p)) this.liveDue.set(p, now + Math.round((300 + this.random() * 1200) * botPace(p)));
|
||||||
|
}
|
||||||
|
const next = Math.min(...this.liveDue.values());
|
||||||
|
this.dueAt = Number.isFinite(next) ? next : null;
|
||||||
|
if (this.dueAt !== null) this.arm();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lets every computer whose time has come look at the game once. */
|
||||||
|
private fireLive(strategy: LiveBotStrategy): void {
|
||||||
|
const now = this.room.now();
|
||||||
|
const due = [...this.liveDue.entries()].filter(([, t]) => t <= now).sort((a, b) => a[1] - b[1]);
|
||||||
|
for (const [bot] of due) {
|
||||||
|
const g = this.room.game;
|
||||||
|
if (!g || g.finished || this.room.status !== 'playing') return;
|
||||||
|
const def = this.room.def;
|
||||||
|
const memory = this.liveMemory.get(bot) ?? {};
|
||||||
|
this.liveMemory.set(bot, memory);
|
||||||
|
const names: Record<string, string> = {};
|
||||||
|
for (const p of g.players) names[p] = this.room.nameOf?.(p) ?? p;
|
||||||
|
let decision: { action: unknown; next: number } = { action: null, next: 3000 };
|
||||||
|
const t0 = performance.now();
|
||||||
|
try {
|
||||||
|
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot), names, memory });
|
||||||
|
} catch (err) {
|
||||||
|
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
|
||||||
|
}
|
||||||
|
const ms = performance.now() - t0;
|
||||||
|
if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) });
|
||||||
|
this.liveDue.set(bot, now + Math.max(100, decision.next));
|
||||||
|
if (decision.action == null) continue;
|
||||||
|
if (!def.validate(g.state, bot, decision.action, { now }).ok) continue; // the moment passed (phase changed); look again later
|
||||||
|
const err = this.room.run(bot, decision.action);
|
||||||
|
if (err) this.room.log?.('warn', 'bot action rejected', { game: def.id, action: decision.action, err });
|
||||||
|
}
|
||||||
|
this.scheduleLive();
|
||||||
}
|
}
|
||||||
|
|
||||||
private arm(): void {
|
private arm(): void {
|
||||||
@@ -125,6 +185,11 @@ export class BotDriver {
|
|||||||
this.timer = null;
|
this.timer = null;
|
||||||
if (this.dueAt === null) return;
|
if (this.dueAt === null) return;
|
||||||
if (this.room.now() < this.dueAt) return this.arm();
|
if (this.room.now() < this.dueAt) return this.arm();
|
||||||
|
const live = this.liveStrategy();
|
||||||
|
if (live) {
|
||||||
|
this.dueAt = null;
|
||||||
|
return this.fireLive(live);
|
||||||
|
}
|
||||||
const planned = this.planned;
|
const planned = this.planned;
|
||||||
this.dueAt = null;
|
this.dueAt = null;
|
||||||
this.planned = null;
|
this.planned = null;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/** Creates, finds, restores and garbage-collects rooms (docs/06 §11, docs/04 §3). */
|
/** Creates, finds, restores and garbage-collects rooms (docs/06 §11, docs/04 §3). */
|
||||||
import { ulid } from 'ulid';
|
import { ulid } from 'ulid';
|
||||||
import type { AnyGameDefinition } from '@bg/engine';
|
import type { AnyGameDefinition } from '@bg/engine';
|
||||||
import { botsAllowed, isAllowedRoomCode, isBotId, type PublicUser } from '@bg/shared';
|
import { PRACTICE_PLAYERS, botsAllowed, isAllowedRoomCode, isBotId, type PublicUser } from '@bg/shared';
|
||||||
import { Room, type RoomConfig, type RoomDeps, type RoomSnapshot } from './room';
|
import { Room, type RoomConfig, type RoomDeps, type RoomSnapshot } from './room';
|
||||||
import type { RoomStore } from './store';
|
import type { RoomStore } from './store';
|
||||||
import type { SettingsStore } from '../admin/settings';
|
import type { SettingsStore } from '../admin/settings';
|
||||||
@@ -136,7 +136,7 @@ export class RoomManager {
|
|||||||
if (typeof room === 'string') return room;
|
if (typeof room === 'string') return room;
|
||||||
const def = this.deps.games[gameId]!;
|
const def = this.deps.games[gameId]!;
|
||||||
const { min, max } = room.playerRange();
|
const { min, max } = room.playerRange();
|
||||||
let bots = Math.max(1, min - 1);
|
let bots = Math.max(1, Math.min(max, PRACTICE_PLAYERS[gameId] ?? min) - 1);
|
||||||
while (bots + 1 < max && def.playerCountError?.(room.config.options, bots + 1)) bots++;
|
while (bots + 1 < max && def.playerCountError?.(room.config.options, bots + 1)) bots++;
|
||||||
// Seat 0 stays free for the host.
|
// Seat 0 stays free for the host.
|
||||||
for (let i = 1; i <= Math.min(bots, room.config.maxPlayers - 1); i++) room.addBot(hostId, i);
|
for (let i = 1; i <= Math.min(bots, room.config.maxPlayers - 1); i++) room.addBot(hostId, i);
|
||||||
|
|||||||
@@ -155,6 +155,7 @@ export class Room {
|
|||||||
return parsed.success ? this.runAction(bot, parsed.data, undefined, false) : '잘못된 요청이에요.';
|
return parsed.success ? this.runAction(bot, parsed.data, undefined, false) : '잘못된 요청이에요.';
|
||||||
},
|
},
|
||||||
log: deps.log,
|
log: deps.log,
|
||||||
|
nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가',
|
||||||
},
|
},
|
||||||
Math.random,
|
Math.random,
|
||||||
deps.botDelay,
|
deps.botDelay,
|
||||||
|
|||||||
@@ -108,7 +108,7 @@ interface Room {
|
|||||||
- 들어가는 곳: 게임 상세와 홈의 [🤖 컴퓨터와 연습하기]. 친구만 방이 열리고, 바로 시작할 수 있을 만큼 컴퓨터가 앉아 있다(예: 오목 1명, 마작 2명, 뱅 3명).
|
- 들어가는 곳: 게임 상세와 홈의 [🤖 컴퓨터와 연습하기]. 친구만 방이 열리고, 바로 시작할 수 있을 만큼 컴퓨터가 앉아 있다(예: 오목 1명, 마작 2명, 뱅 3명).
|
||||||
- 대기실: 방장은 첫 빈자리의 [🤖 컴퓨터 넣기]로 넣고, 컴퓨터 자리의 [✕]로 뺀다(대기실에서만). 컴퓨터 이름은 "컴퓨터 1", "컴퓨터 2"…, 아바타는 🤖. 늘 준비 완료이고, 방장은 컴퓨터에게 넘어가지 않는다. 사람이 한 명은 앉아야 시작된다.
|
- 대기실: 방장은 첫 빈자리의 [🤖 컴퓨터 넣기]로 넣고, 컴퓨터 자리의 [✕]로 뺀다(대기실에서만). 컴퓨터 이름은 "컴퓨터 1", "컴퓨터 2"…, 아바타는 🤖. 늘 준비 완료이고, 방장은 컴퓨터에게 넘어가지 않는다. 사람이 한 명은 앉아야 시작된다.
|
||||||
- 컴퓨터가 앉은 방은 연습 방이다: 공개로 바꿀 수 없고, 공개 방 목록·빠른 시작에 나오지 않는다. 결과는 남지만 전적(`user_stats`)에는 넣지 않는다. 화면에 "연습 게임이에요. 기록에는 남지 않아요." 표시.
|
- 컴퓨터가 앉은 방은 연습 방이다: 공개로 바꿀 수 없고, 공개 방 목록·빠른 시작에 나오지 않는다. 결과는 남지만 전적(`user_stats`)에는 넣지 않는다. 화면에 "연습 게임이에요. 기록에는 남지 않아요." 표시.
|
||||||
- 컴퓨터가 할 수 있는 게임: 실시간·대화 게임(도블, 할리갈리, 그림 맞히기, 마피아)을 뺀 전부(`packages/shared/src/bots.ts`의 `BOT_GAMES`).
|
- 컴퓨터가 할 수 있는 게임: 실시간·그림 게임(도블, 할리갈리, 그림 맞히기)을 뺀 전부(`packages/shared/src/bots.ts`의 `BOT_GAMES`). 마피아는 말하는 컴퓨터(2026-10-11, games/mafia.md §13), 연습 방은 6명으로 시작.
|
||||||
- 움직임: 서버의 `BotDriver`(`apps/server/src/rooms/bots.ts`)가 게임이 컴퓨터를 기다릴 때(차례, 반응 창, 동시 선택, 다음 판 준비) 사람처럼 생각할 시간을 두고 한 수를 둔다(2026-10-11). 할 게 하나뿐이면 0.7~1.3초, 고를 게 있으면 1.6~3.9초(고를 수가 많을수록 길게), 가끔(12%) 1~3초 더 멈칫한다. 컴퓨터마다 빠르기가 달라서(`botPace`: 0.7배 빠른 편~1.5배 신중한 편, 컴퓨터 id로 고정) 같은 판에서도 반응 속도가 다르다. 같은 컴퓨터가 이어서 두는 동작(요트 굴리기 → 고르기 등)은 절반 시간, 사람도 함께 반응할 수 있는 창(원카드 외치기 등)은 1.5초 더. 차례 시간이 있으면 남은 시간의 절반을 넘기지 않는다. 사람과 같은 행동 경로(검사·기록)를 거치고, 서버가 다시 켜져도 이어서 둔다.
|
- 움직임: 서버의 `BotDriver`(`apps/server/src/rooms/bots.ts`)가 게임이 컴퓨터를 기다릴 때(차례, 반응 창, 동시 선택, 다음 판 준비) 사람처럼 생각할 시간을 두고 한 수를 둔다(2026-10-11). 할 게 하나뿐이면 0.7~1.3초, 고를 게 있으면 1.6~3.9초(고를 수가 많을수록 길게), 가끔(12%) 1~3초 더 멈칫한다. 컴퓨터마다 빠르기가 달라서(`botPace`: 0.7배 빠른 편~1.5배 신중한 편, 컴퓨터 id로 고정) 같은 판에서도 반응 속도가 다르다. 같은 컴퓨터가 이어서 두는 동작(요트 굴리기 → 고르기 등)은 절반 시간, 사람도 함께 반응할 수 있는 창(원카드 외치기 등)은 1.5초 더. 차례 시간이 있으면 남은 시간의 절반을 넘기지 않는다. 사람과 같은 행동 경로(검사·기록)를 거치고, 서버가 다시 켜져도 이어서 둔다.
|
||||||
- 수 고르기: `packages/games/src/<게임>/bot.ts`. 자기 화면(`view(state, 나)`)과 둘 수 있는 수만 보고 고르므로 남의 패를 볼 수 없다. 강하지 않지만 엉뚱하지 않게(오목은 4를 막고, 오셀로는 귀를 잡고, 카드 게임은 패 세기에 맞게).
|
- 수 고르기: `packages/games/src/<게임>/bot.ts`. 자기 화면(`view(state, 나)`)과 둘 수 있는 수만 보고 고르므로 남의 패를 볼 수 없다. 강하지 않지만 엉뚱하지 않게(오목은 4를 막고, 오셀로는 귀를 잡고, 카드 게임은 패 세기에 맞게).
|
||||||
- 사람이 모두 나가면 게임은 무효로 끝난다.
|
- 사람이 모두 나가면 게임은 무효로 끝난다.
|
||||||
|
|||||||
@@ -134,4 +134,5 @@ export interface GameUI<V> {
|
|||||||
## 9. 컴퓨터 상대 (`packages/games/src/bots/`, 06 §12)
|
## 9. 컴퓨터 상대 (`packages/games/src/bots/`, 06 §12)
|
||||||
- 게임마다 `<게임>/bot.ts`의 전략 하나: `(입력: { me, view, legal, random }) => 행동`. `view`는 `view(state, me)`, `legal`은 `legalActions(state, me)`. 게임 상태는 넘기지 않는다(비공개 정보 차단).
|
- 게임마다 `<게임>/bot.ts`의 전략 하나: `(입력: { me, view, legal, random }) => 행동`. `view`는 `view(state, me)`, `legal`은 `legalActions(state, me)`. 게임 상태는 넘기지 않는다(비공개 정보 차단).
|
||||||
- `decideBotAction`이 고른 수를 `validate`로 다시 검사하고, 틀리면 다른 합법 수로 바꾼다. 서버는 그래도 실패하면 게임의 `onTimeout` 행동을 쓴다.
|
- `decideBotAction`이 고른 수를 `validate`로 다시 검사하고, 틀리면 다른 합법 수로 바꾼다. 서버는 그래도 실패하면 게임의 `onTimeout` 행동을 쓴다.
|
||||||
|
- 라이브 봇(`LIVE_BOT_STRATEGIES`, 마피아): 모두가 동시에 시계에 맞춰 움직이고 말하는 게임. 전략은 `({ me, view, now, persona, names, memory }) => { action | null, next }`로, 서버가 컴퓨터마다 따로 `next` ms 뒤에 다시 묻는다. `persona`(`bots/persona.ts`)는 똑똑한 편/허술한 편과 빠르기, `memory`는 이번 판에 이미 한 일(서버가 다시 켜지면 비워짐). 테스트 도우미 `bots/live-playout.ts`.
|
||||||
- 테스트(`bots/bots.test.ts`): 게임마다 "사람 1명은 시간 초과만, 나머지는 컴퓨터"와 "컴퓨터끼리" 판을 끝까지 돌려, 모든 수가 합법이고 컴퓨터 때문에 멈추지 않으며 한 수가 충분히 빠른지 본다.
|
- 테스트(`bots/bots.test.ts`): 게임마다 "사람 1명은 시간 초과만, 나머지는 컴퓨터"와 "컴퓨터끼리" 판을 끝까지 돌려, 모든 수가 합법이고 컴퓨터 때문에 멈추지 않으며 한 수가 충분히 빠른지 본다.
|
||||||
|
|||||||
@@ -252,3 +252,11 @@ interface MafiaResult {
|
|||||||
- 아동 이용자: "처치/처형" 표현을 "탈락/퇴장"으로 바꾸는 어린이 표현 모드 검토. 채팅이 핵심이므로 신고 버튼, 방장 강퇴, 비속어 필터, 개인정보(전화번호 등) 패턴 차단을 기본 제공.
|
- 아동 이용자: "처치/처형" 표현을 "탈락/퇴장"으로 바꾸는 어린이 표현 모드 검토. 채팅이 핵심이므로 신고 버튼, 방장 강퇴, 비속어 필터, 개인정보(전화번호 등) 패턴 차단을 기본 제공.
|
||||||
- 채팅 로그 보관: 신고 처리용으로 짧게(예: 7일) 보관하고 이후 삭제. 개인정보 처리방침에 명시.
|
- 채팅 로그 보관: 신고 처리용으로 짧게(예: 7일) 보관하고 이후 삭제. 개인정보 처리방침에 명시.
|
||||||
- 도박 요소 없음.
|
- 도박 요소 없음.
|
||||||
|
|
||||||
|
## 13. 컴퓨터 플레이어 (2026-10-11)
|
||||||
|
- 연습 방([🤖 컴퓨터와 연습하기])은 사람 1 + 컴퓨터 5명(6명, 마피아 2)으로 시작한다(`PRACTICE_PLAYERS`). 대기실에서 컴퓨터를 더 넣거나 뺄 수 있다.
|
||||||
|
- 움직임: "라이브 봇"(`packages/games/src/mafia/bot.ts`, 서버 `BotDriver`의 live 모드). 차례를 기다리는 게 아니라 컴퓨터마다 자기 타이머로 0.3~2초마다 화면(`view`)과 채팅을 다시 보고, 할 일이 있으면 하나(말하기·투표·찬반·밤 행동·토론 끝내기)를 한다. 그래서 여러 컴퓨터가 동시에, 각자 다른 때에 말하고 투표한다.
|
||||||
|
- 성격(컴퓨터 id로 고정, 대략 반반): **똑똑한 편**은 경찰 결과, 경찰이라고 나선 사람의 말, 투표 기록(시민을 처형한 표), 나를 몰아가는 사람, 말 없는 사람을 근거로 의심하고 존댓말로 이유를 말한다. 경찰이면 마피아를 찾았을 때 밝히고, 의사는 경찰이라고 나선 사람을 지키고, 마피아는 경찰이라고 나선 사람부터 노리며 가짜 경찰로 맞서기도 한다. **허술한 편**은 느낌으로 의심하고 남이 몰아가면 따라가며, 반말·ㅋㅋ·"3번" 같은 짧은 말을 쓰고 아무 결과나 불쑥 말한다. 7명 컴퓨터끼리 40판: 똑똑한 시민 대 허술한 마피아는 시민 승률이 허술한 시민 대 똑똑한 마피아보다 20%p 넘게 높다(테스트).
|
||||||
|
- 반응 속도: 컴퓨터마다 빠르기(`botPace` 0.7~1.5배)가 달라 대답·투표·밤 행동 시점이 다르다. 시간은 늘 그 페이즈 안(투표는 남은 시간의 75% 안).
|
||||||
|
- 채팅: 인사, 아침 소식 반응(두 명이 이미 말했으면 조용히), 의심 지목, 남의 지목에 동의·반박, 이름이 불리면 대답(질문·의심에는 꼭), 최후의 반론, 투표·찬반 한마디, 마피아 채팅으로 상의(사람 마피아가 고르면 따른다), 연인 채팅, 탈락 뒤 한마디. 자기나 남이 방금 한 말은 되풀이하지 않는다. 이름은 "컴퓨터 3", "컴퓨터3", "컴3", "3번"을 모두 알아듣는다.
|
||||||
|
- 비공개 정보: 컴퓨터는 자기 화면만 본다(남의 직업은 모름). 마피아 컴퓨터는 낮 채팅에서 자기 팀을 지목하지 않는다(테스트).
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ try {
|
|||||||
const pc = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
|
const pc = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
|
||||||
const phone = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'ko-KR' });
|
const phone = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'ko-KR' });
|
||||||
// The first-game "30초 규칙 요약" cards are tested in e2e/tutorial.e2e.ts; mark them seen here.
|
// The first-game "30초 규칙 요약" cards are tested in e2e/tutorial.e2e.ts; mark them seen here.
|
||||||
for (const ctx of [pc, phone]) await ctx.addInitScript(() => { for (const g of ['omok', 'one-card', 'yacht']) localStorage.setItem(`bg:qs:${g}`, '1'); });
|
for (const ctx of [pc, phone]) await ctx.addInitScript(() => { for (const g of ['omok', 'one-card', 'yacht', 'mafia']) localStorage.setItem(`bg:qs:${g}`, '1'); });
|
||||||
const a = await pc.newPage();
|
const a = await pc.newPage();
|
||||||
const b = await phone.newPage();
|
const b = await phone.newPage();
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
@@ -266,6 +266,30 @@ try {
|
|||||||
await b.waitForURL(`${ORIGIN}/`);
|
await b.waitForURL(`${ORIGIN}/`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
await step('마피아(연습, PC): 컴퓨터 5명 → 인사 채팅 → 이름을 부르면 대답', async () => {
|
||||||
|
await a.goto(`${ORIGIN}/g/mafia`);
|
||||||
|
await a.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click();
|
||||||
|
await a.waitForURL(/\/r\/\d{6}$/);
|
||||||
|
await a.getByLabel('자리').getByText('컴퓨터 5').waitFor();
|
||||||
|
await a.getByRole('button', { name: '▶ 게임 시작' }).click();
|
||||||
|
// Role card (8 s), then the greeting: computers say hello at their own pace.
|
||||||
|
const fromBots = a.locator('.mf-msgs .mf-msg:not(.sys)', { has: a.locator('strong', { hasText: /^컴퓨터 \d$/ }) });
|
||||||
|
await a.waitForFunction(() => document.querySelectorAll('.mf-msgs .mf-msg:not(.sys)').length >= 2, null, { timeout: 40_000 });
|
||||||
|
const hello = await fromBots.allInnerTexts();
|
||||||
|
if (hello.length < 2) throw new Error(`computers said ${hello.length} lines`);
|
||||||
|
await a.getByRole('tab', { name: /^전체 채팅/ }).click();
|
||||||
|
await a.getByLabel('전체 채팅 메시지').fill('컴퓨터 2 직업 뭐야?');
|
||||||
|
await a.getByLabel('전체 채팅 메시지').press('Enter');
|
||||||
|
// The answer to the question (one of the "what's your job" lines), not just any line of 컴퓨터 2.
|
||||||
|
const answer = a.locator('.mf-msgs .mf-msg', { has: a.locator('strong', { hasText: /^컴퓨터 2$/ }), hasText: /저 시민이에요|저는 시민이에요|나 시민ㅋㅋ|비밀ㅋㅋ|시민이지/ });
|
||||||
|
await answer.first().waitFor({ timeout: 20_000 });
|
||||||
|
console.log(` mafia: ${hello.slice(0, 3).join(' | ')} → ${await answer.first().innerText()}`);
|
||||||
|
await a.screenshot({ path: join(SHOTS, 'bots-6-mafia-pc.png') });
|
||||||
|
await a.getByRole('button', { name: '방 나가고 홈으로' }).click();
|
||||||
|
await a.getByRole('button', { name: '나가기', exact: true }).click();
|
||||||
|
await a.waitForURL(`${ORIGIN}/`);
|
||||||
|
});
|
||||||
|
|
||||||
await step('게스트 로그아웃 → 계정 삭제', async () => {
|
await step('게스트 로그아웃 → 계정 삭제', async () => {
|
||||||
const id = userId('호랑이')!;
|
const id = userId('호랑이')!;
|
||||||
await a.getByRole('button', { name: '내 계정: 호랑이' }).click();
|
await a.getByRole('button', { name: '내 계정: 호랑이' }).click();
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
* information (other hands, deck order).
|
* information (other hands, deck order).
|
||||||
*/
|
*/
|
||||||
import type { AnyGameDefinition, PlayerId } from '@bg/engine';
|
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 { pick, playable, randomPolicy } from './policy';
|
||||||
import { omokBot } from '../omok/bot';
|
import { omokBot } from '../omok/bot';
|
||||||
import { othelloBot } from '../othello/bot';
|
import { othelloBot } from '../othello/bot';
|
||||||
@@ -28,8 +28,10 @@ import { quoridorBot } from '../quoridor/bot';
|
|||||||
import { lasVegasBot } from '../las-vegas/bot';
|
import { lasVegasBot } from '../las-vegas/bot';
|
||||||
import { cockroachPokerBot } from '../cockroach-poker/bot';
|
import { cockroachPokerBot } from '../cockroach-poker/bot';
|
||||||
import { ninetyNineBot } from '../ninety-nine/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). */
|
/** Strategy per bot-enabled game (must match `BOT_GAMES` in @bg/shared). */
|
||||||
export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||||
@@ -92,3 +94,8 @@ export function decideBotAction(
|
|||||||
const rest = legal.filter(valid);
|
const rest = legal.filter(valid);
|
||||||
return rest.length ? pick(playable(rest), random) : null;
|
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,
|
||||||
|
};
|
||||||
|
|||||||
87
packages/games/src/bots/live-playout.ts
Normal file
87
packages/games/src/bots/live-playout.ts
Normal 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;
|
||||||
|
}
|
||||||
32
packages/games/src/bots/persona.ts
Normal file
32
packages/games/src/bots/persona.ts
Normal 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 };
|
||||||
|
}
|
||||||
@@ -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.
|
* (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;
|
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>;
|
||||||
|
|||||||
154
packages/games/src/mafia/bot.test.ts
Normal file
154
packages/games/src/mafia/bot.test.ts
Normal 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(/시민/);
|
||||||
|
});
|
||||||
|
});
|
||||||
736
packages/games/src/mafia/bot.ts
Normal file
736
packages/games/src/mafia/bot.ts
Normal 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 };
|
||||||
@@ -22,8 +22,8 @@ export function botProfile(id: string): PublicUser | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Games that offer computer players. Real-time and talk-based games (도블, 할리갈리, 그림 맞히기, 마피아)
|
* Games that offer computer players. Real-time and drawing games (도블, 할리갈리, 그림 맞히기) don't: a bot there is
|
||||||
* don't: a bot there is either unbeatable or meaningless.
|
* either unbeatable or meaningless. 마피아 has talking computers (2026-10-11).
|
||||||
*/
|
*/
|
||||||
export const BOT_GAMES: readonly string[] = [
|
export const BOT_GAMES: readonly string[] = [
|
||||||
'omok',
|
'omok',
|
||||||
@@ -48,6 +48,10 @@ export const BOT_GAMES: readonly string[] = [
|
|||||||
'las-vegas',
|
'las-vegas',
|
||||||
'cockroach-poker',
|
'cockroach-poker',
|
||||||
'ninety-nine',
|
'ninety-nine',
|
||||||
|
'mafia',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1). */
|
||||||
|
export const PRACTICE_PLAYERS: Readonly<Record<string, number>> = { mafia: 6 };
|
||||||
|
|
||||||
export const botsAllowed = (gameId: string): boolean => BOT_GAMES.includes(gameId);
|
export const botsAllowed = (gameId: string): boolean => BOT_GAMES.includes(gameId);
|
||||||
|
|||||||
Reference in New Issue
Block a user