마피아 컴퓨터 플레이어: 각자 타이머로 말하고 투표하는 라이브 봇, 똑똑한 편/허술한 편, 반응 속도 차이
- 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:
@@ -4,7 +4,7 @@
|
||||
* information (other hands, deck order).
|
||||
*/
|
||||
import type { AnyGameDefinition, PlayerId } from '@bg/engine';
|
||||
import type { BotStrategy } from './types';
|
||||
import type { BotStrategy, LiveBotStrategy } from './types';
|
||||
import { pick, playable, randomPolicy } from './policy';
|
||||
import { omokBot } from '../omok/bot';
|
||||
import { othelloBot } from '../othello/bot';
|
||||
@@ -28,8 +28,10 @@ import { quoridorBot } from '../quoridor/bot';
|
||||
import { lasVegasBot } from '../las-vegas/bot';
|
||||
import { cockroachPokerBot } from '../cockroach-poker/bot';
|
||||
import { ninetyNineBot } from '../ninety-nine/bot';
|
||||
import { mafiaBot } from '../mafia/bot';
|
||||
|
||||
export type { BotInput, BotStrategy } from './types';
|
||||
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { botPace, botPersona, hash01, type BotPersona } from './persona';
|
||||
|
||||
/** Strategy per bot-enabled game (must match `BOT_GAMES` in @bg/shared). */
|
||||
export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
@@ -92,3 +94,8 @@ export function decideBotAction(
|
||||
const rest = legal.filter(valid);
|
||||
return rest.length ? pick(playable(rest), random) : null;
|
||||
}
|
||||
|
||||
/** Live strategies (games where everybody acts at once and talks); also in `BOT_GAMES`. */
|
||||
export const LIVE_BOT_STRATEGIES: Record<string, LiveBotStrategy> = {
|
||||
mafia: mafiaBot,
|
||||
};
|
||||
|
||||
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.
|
||||
*/
|
||||
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>;
|
||||
|
||||
Reference in New Issue
Block a user