Files
joke-app/packages/games/src/bots/playout.ts
EJClaw a3f81ded37 M9: 컴퓨터 상대 — 게임 22종 컴퓨터 전략, 서버 구동(BotDriver), 연습 방
- packages/shared/src/bots.ts: 컴퓨터 id(bot:<n>:<ulid>)·프로필(컴퓨터 n)·BOT_GAMES
  (도블·할리갈리·그림 맞히기·마피아 제외)
- packages/games/src/bots: 전략 계약(자기 view + 합법 수만), decideBotAction(validate 재검사),
  게임별 <게임>/bot.ts 22개 + 행동 테스트, 전 게임 판 끝까지 돌리는 공통 테스트
- 서버: Room.addBot/removeBot(방장·대기실만, 방은 친구만), RoomManager.createPractice
  (POST /api/rooms {practice:true}), BotDriver(사람 같은 지연, 사람과 같은 창이면 더 천천히,
  재시작 후 다시 예약), 연습 게임은 전적 제외(result_json.practice), 사람이 모두 나가면 무효
- 프로토콜 addBot/removeBot, 문서 03·06 §12·08·09 §8

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:32:28 +09:00

73 lines
3.4 KiB
TypeScript

/** Test helper: bots play a whole game the way the room would run it, next to "humans" who only time out. */
import { SeededRng, type AnyGameDefinition, type PlayerId, type RngState } from '@bg/engine';
import { botCandidates, decideBotAction } from './index';
export interface BotPlayoutReport {
steps: number;
finished: boolean;
botMoves: number;
maxBotMs: number;
totalBotMs: number;
/** Timeouts of human seats (expected: they never act otherwise). */
humanTimeouts: number;
/** Timeouts of bots the game was waiting on (a bot stuck until its turn clock ran out: should stay 0). */
botTimeouts: number;
/** Timer-driven steps nobody had to act in (e.g. a minimum claim window or a result pause). */
pauses: number;
}
const waitingOf = (def: AnyGameDefinition, s: unknown): PlayerId[] => [...new Set([...def.activePlayers(s), ...(def.timeoutPlayers?.(s) ?? [])])];
/**
* Bots act as soon as the game waits on them (like `BotDriver`, before any turn clock); when only humans are left,
* the clock runs to the deadline and the game's own timeout action is played for them.
*/
export function botPlayout(
def: AnyGameDefinition,
opts: { players: PlayerId[]; options?: unknown; seed: RngState; maxSteps?: number; isBot: (p: PlayerId) => boolean },
): BotPlayoutReport {
const rng = SeededRng.fromSeed(opts.seed);
const chooser = SeededRng.fromSeed([opts.seed[1], opts.seed[0], opts.seed[3], opts.seed[2] ^ 0x5bd1e995]);
const random = () => chooser.next();
let now = 1_700_000_000_000;
let state = def.setup({ players: opts.players, options: opts.options ?? def.defaultOptions, rng, now, gameNo: 1 });
const rep: BotPlayoutReport = { steps: 0, finished: false, botMoves: 0, maxBotMs: 0, totalBotMs: 0, humanTimeouts: 0, botTimeouts: 0, pauses: 0 };
const maxSteps = opts.maxSteps ?? 20_000;
const apply = (actor: PlayerId, action: unknown, what: string) => {
const v = def.validate(state, actor, action, { now });
if (!v.ok) throw new Error(`${def.id}: ${what} action rejected: ${v.reason} ${JSON.stringify(action)}`);
state = def.apply(state, actor, action, { rng, now }).state;
};
for (; rep.steps < maxSteps; rep.steps++) {
if (def.result(state)) {
rep.finished = true;
return rep;
}
now += 500;
const waiting = waitingOf(def, state);
const bot = waiting.find((p) => opts.isBot(p) && botCandidates(def, state, p).length > 0);
if (bot) {
const t0 = performance.now();
const action = decideBotAction(def, state, bot, { now, random });
const ms = performance.now() - t0;
if (action === null) throw new Error(`${def.id}: bot ${bot} found no valid action`);
rep.botMoves++;
rep.totalBotMs += ms;
rep.maxBotMs = Math.max(rep.maxBotMs, ms);
apply(bot, action, 'bot');
continue;
}
// Nobody else moves: let the clock run to the deadline like the room timer would.
const deadline = def.deadline?.(state) ?? null;
const timed = def.timeoutPlayers ? def.timeoutPlayers(state) : def.activePlayers(state);
const who = timed.find((p) => !opts.isBot(p)) ?? waiting.find((p) => !opts.isBot(p)) ?? timed[0];
if (!who) throw new Error(`${def.id}: stalled (nobody can act, no timeout)`);
if (deadline !== null) now = Math.max(now, deadline);
if (!opts.isBot(who)) rep.humanTimeouts++;
else if (def.activePlayers(state).includes(who)) rep.botTimeouts++;
else rep.pauses++;
apply(who, def.onTimeout(state, who), 'timeout');
}
return rep;
}