- secureRandom(): crypto.getRandomValues 53비트 실수. 서버의 Math.random(컴퓨터 수·생각 시간·AI 말·방 코드·마감 유예)을 모두 교체 - 컴퓨터 id의 ULID를 secureRandom으로 만들고, 그 무작위 부분 30비트로 난이도·말투(smart)를 정함(botDraw) - humanBest: 오목·체스·장기·오델로·바둑에서 난이도별로 비슷한 수(slip)·사고(lapse)·꼭 둬야 할 수 놓침(miss) - 문서 09 §9.1(확률표·게임별 기준·대국 결과), 06 §12; 테스트 bots/level.test.ts, 레벨별 완주 테스트 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
74 lines
3.5 KiB
TypeScript
74 lines
3.5 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';
|
|
import type { BotLevel } from './persona';
|
|
|
|
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; level?: BotLevel },
|
|
): 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, level: opts.level });
|
|
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;
|
|
}
|