마피아 컴퓨터 플레이어: 각자 타이머로 말하고 투표하는 라이브 봇, 똑똑한 편/허술한 편, 반응 속도 차이
- 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. */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
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 { openDb } from '../db';
|
||||
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);
|
||||
|
||||
describe('bot list', () => {
|
||||
test('BOT_GAMES matches the strategies and leaves out real-time / talk games', () => {
|
||||
expect([...BOT_GAMES].sort()).toEqual(Object.keys(BOT_STRATEGIES).sort());
|
||||
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), ...Object.keys(LIVE_BOT_STRATEGIES)].sort());
|
||||
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', () => {
|
||||
@@ -205,7 +206,7 @@ describe('addBot / removeBot', () => {
|
||||
describe('createPractice', () => {
|
||||
test('a private room with just enough computers to start; never offered by quick play', () => {
|
||||
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)) {
|
||||
const room = manager.createPractice(`host-${gameId}`, gameId);
|
||||
if (typeof room === 'string') throw new Error(room);
|
||||
@@ -216,7 +217,7 @@ describe('createPractice', () => {
|
||||
expect(room.start(`host-${gameId}`)).toBeNull();
|
||||
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.
|
||||
const qp = manager.quickPlay('Q', 'omok');
|
||||
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', () => {
|
||||
function omokVsBot() {
|
||||
const h = harness();
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
*/
|
||||
import type { AnyGameDefinition } from '@bg/engine';
|
||||
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 {
|
||||
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. */
|
||||
run(actor: string, action: unknown): string | null;
|
||||
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. */
|
||||
@@ -31,16 +35,6 @@ export interface BotDelayInput {
|
||||
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
|
||||
* 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;
|
||||
/** 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;
|
||||
/** 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(
|
||||
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"). */
|
||||
schedule(): void {
|
||||
if (this.liveStrategy()) return this.scheduleLive();
|
||||
if (this.dueAt !== null) return;
|
||||
const next = this.next();
|
||||
if (!next) return;
|
||||
@@ -96,6 +95,67 @@ export class BotDriver {
|
||||
this.timer = null;
|
||||
this.dueAt = 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 {
|
||||
@@ -125,6 +185,11 @@ export class BotDriver {
|
||||
this.timer = null;
|
||||
if (this.dueAt === null) return;
|
||||
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;
|
||||
this.dueAt = null;
|
||||
this.planned = null;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Creates, finds, restores and garbage-collects rooms (docs/06 §11, docs/04 §3). */
|
||||
import { ulid } from 'ulid';
|
||||
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 type { RoomStore } from './store';
|
||||
import type { SettingsStore } from '../admin/settings';
|
||||
@@ -136,7 +136,7 @@ export class RoomManager {
|
||||
if (typeof room === 'string') return room;
|
||||
const def = this.deps.games[gameId]!;
|
||||
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++;
|
||||
// Seat 0 stays free for the host.
|
||||
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) : '잘못된 요청이에요.';
|
||||
},
|
||||
log: deps.log,
|
||||
nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가',
|
||||
},
|
||||
Math.random,
|
||||
deps.botDelay,
|
||||
|
||||
Reference in New Issue
Block a user