컴퓨터 난이도(쉬움 35%·보통 40%·어려움 25%)와 사람 같은 수, 서버 난수를 OS 보안 난수로
- 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>
This commit is contained in:
@@ -48,3 +48,15 @@ test('decideBotAction returns null when the bot has nothing to do', () => {
|
||||
expect(decideBotAction(def, s, other, { now: 0 })).toBeNull();
|
||||
expect(decideBotAction(def, s, waiting, { now: 0 })).not.toBeNull();
|
||||
});
|
||||
|
||||
describe('levels (docs/09 §9.1)', () => {
|
||||
const BOARD = ['omok', 'chess', 'janggi', 'othello', 'baduk'];
|
||||
test.each(BOARD)('%s: easy and hard computers still finish a game against each other', (id) => {
|
||||
const def = GAMES[id]!;
|
||||
for (const level of ['easy', 'hard'] as const) {
|
||||
const r = botPlayout(def, { players: seats(2, 0), seed: seedN(7), isBot, maxSteps: 30_000, level });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
* it hands the strategy the bot's own view and its legal actions — nothing else — so a bot can't peek at hidden
|
||||
* information (other hands, deck order).
|
||||
*/
|
||||
import type { AnyGameDefinition, PlayerId } from '@bg/engine';
|
||||
import { secureRandom, type AnyGameDefinition, type PlayerId } from '@bg/engine';
|
||||
import type { BotLevel } from './persona';
|
||||
import type { BotStrategy, LiveBotStrategy } from './types';
|
||||
import { pick, playable, randomPolicy } from './policy';
|
||||
import { omokBot } from '../omok/bot';
|
||||
@@ -31,7 +32,7 @@ import { ninetyNineBot } from '../ninety-nine/bot';
|
||||
import { mafiaBot } from '../mafia/bot';
|
||||
|
||||
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { botPace, botPersona, hash01, type BotPersona } from './persona';
|
||||
export { BOT_LEVEL_ODDS, botDraw, botPace, botPersona, hash01, levelOf, type BotLevel, type BotPersona } from './persona';
|
||||
|
||||
/** Strategy per bot-enabled game (must match `BOT_GAMES` in @bg/shared). */
|
||||
export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
@@ -73,18 +74,18 @@ export function decideBotAction(
|
||||
def: AnyGameDefinition,
|
||||
state: unknown,
|
||||
me: PlayerId,
|
||||
ctx: { now: number; random?: () => number },
|
||||
ctx: { now: number; random?: () => number; level?: BotLevel },
|
||||
): unknown | null {
|
||||
let legal = botCandidates(def, state, me);
|
||||
if (!legal.length) return null;
|
||||
const random = ctx.random ?? Math.random;
|
||||
const random = ctx.random ?? secureRandom;
|
||||
const valid = (a: unknown) => def.validate(state, me, a, { now: ctx.now }).ok;
|
||||
const view = def.view(state, me);
|
||||
const strategy = BOT_STRATEGIES[def.id] ?? randomPolicy;
|
||||
for (let attempt = 0; attempt < 3 && legal.length; attempt++) {
|
||||
let action: unknown;
|
||||
try {
|
||||
action = strategy({ me, view: structuredClone(view), legal, random });
|
||||
action = strategy({ me, view: structuredClone(view), legal, random, level: ctx.level });
|
||||
} catch {
|
||||
break;
|
||||
}
|
||||
|
||||
93
packages/games/src/bots/level.test.ts
Normal file
93
packages/games/src/bots/level.test.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
/** Computer levels and human-like choices (docs/09-game-engine.md §9.1). */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, secureRandom, seedN } from '@bg/engine';
|
||||
import { BOT_PLAY, humanBest } from './policy';
|
||||
import { BOT_LEVEL_ODDS, botDraw, botPersona, levelOf, type BotLevel } from './persona';
|
||||
|
||||
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
||||
const fakeUlid = (r: () => number) => '01J' + Array.from({ length: 23 }, () => CROCKFORD[Math.floor(r() * 32)]).join('');
|
||||
|
||||
describe('secureRandom', () => {
|
||||
test('uniform floats in [0, 1)', () => {
|
||||
const n = 100_000;
|
||||
const bins = new Array(10).fill(0);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const x = secureRandom();
|
||||
expect(x >= 0 && x < 1).toBe(true);
|
||||
bins[Math.floor(x * 10)]++;
|
||||
}
|
||||
for (const b of bins) expect(Math.abs(b - n / 10)).toBeLessThan(n / 10 * 0.05);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bot level', () => {
|
||||
test('the roll comes from the id’s random characters and keeps the level for the same id', () => {
|
||||
const id = `bot:2:${fakeUlid(secureRandom)}`;
|
||||
expect(botPersona(id)).toEqual(botPersona(id));
|
||||
expect(botDraw('bot:1:01J0000000000000000000000Z')).toBe(0);
|
||||
expect(botDraw('bot:1:01J0000000ZZZZZZ0000000000')).toBeCloseTo(1, 6);
|
||||
});
|
||||
|
||||
test('levels come out at the documented odds; 똑똑한 편 is half, every 쉬움 허술, every 어려움 똑똑', () => {
|
||||
const rng = SeededRng.fromSeed(seedN(3));
|
||||
const n = 40_000;
|
||||
const count: Record<BotLevel, number> = { easy: 0, normal: 0, hard: 0 };
|
||||
let smart = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const p = botPersona(`bot:${(i % 7) + 1}:${fakeUlid(() => rng.next())}`);
|
||||
count[p.level]++;
|
||||
if (p.smart) smart++;
|
||||
if (p.level === 'easy') expect(p.smart).toBe(false);
|
||||
if (p.level === 'hard') expect(p.smart).toBe(true);
|
||||
}
|
||||
for (const level of ['easy', 'normal', 'hard'] as const) expect(Math.abs(count[level] / n - BOT_LEVEL_ODDS[level])).toBeLessThan(0.015);
|
||||
expect(Math.abs(smart / n - 0.5)).toBeLessThan(0.015);
|
||||
expect(levelOf(0.3499)).toBe('easy');
|
||||
expect(levelOf(0.35)).toBe('normal');
|
||||
expect(levelOf(0.75)).toBe('hard');
|
||||
});
|
||||
});
|
||||
|
||||
describe('humanBest', () => {
|
||||
// Scores: 100 best, 95 close, 60 a slip away for easy, 0 a blunder.
|
||||
const moves = ['best', 'close', 'meh', 'blunder'];
|
||||
const value: Record<string, number> = { best: 100, close: 95, meh: 70, blunder: 0 };
|
||||
const scale = { small: 10, critical: 1000 };
|
||||
const share = (level: BotLevel | undefined, xs = moves, v = value) => {
|
||||
const rng = SeededRng.fromSeed(seedN(11));
|
||||
const n = 20_000;
|
||||
const out: Record<string, number> = {};
|
||||
for (let i = 0; i < n; i++) {
|
||||
const m = humanBest(xs, (a) => v[a]!, () => rng.next(), level, scale);
|
||||
out[m] = (out[m] ?? 0) + 1;
|
||||
}
|
||||
for (const k in out) out[k]! /= n;
|
||||
return out;
|
||||
};
|
||||
|
||||
test('without a level it is the plain best move', () => {
|
||||
expect(share(undefined)).toEqual({ best: 1 });
|
||||
});
|
||||
|
||||
test('stronger levels play the best move more often and never pick a move far worse than a lapse allows', () => {
|
||||
const easy = share('easy');
|
||||
const normal = share('normal');
|
||||
const hard = share('hard');
|
||||
expect(easy.best!).toBeLessThan(normal.best!);
|
||||
expect(normal.best!).toBeLessThan(hard.best!);
|
||||
expect(hard.best!).toBeGreaterThan(0.9);
|
||||
// "meh" (30 worse = 3 × small) is past every slip window (≤ 2 × small): only a lapse (8 × small) plays it.
|
||||
expect(hard.meh ?? 0).toBeLessThan(0.01);
|
||||
// 100 worse is beyond every window: never played.
|
||||
for (const s of [easy, normal, hard]) expect(s.blunder ?? 0).toBe(0);
|
||||
// Close alternative: roughly slip share of the time.
|
||||
expect(Math.abs((normal.close ?? 0) - (BOT_PLAY.normal.slip + BOT_PLAY.normal.lapse / 2))).toBeLessThan(0.03);
|
||||
});
|
||||
|
||||
test('a must-play move (≥ critical) is missed only at the documented rate', () => {
|
||||
const v = { ...value, best: 5000 };
|
||||
expect(share('hard', moves, v).best).toBe(1);
|
||||
expect(Math.abs(1 - share('normal', moves, v).best! - BOT_PLAY.normal.miss)).toBeLessThan(0.01);
|
||||
expect(Math.abs(1 - share('easy', moves, v).best! - BOT_PLAY.easy.miss)).toBeLessThan(0.015);
|
||||
});
|
||||
});
|
||||
@@ -18,8 +18,39 @@ export function botPace(bot: string): number {
|
||||
return 0.7 + ((h >>> 0) / 2 ** 32) * 0.8;
|
||||
}
|
||||
|
||||
/** How well a computer plays (docs/09-game-engine.md §9.1). */
|
||||
export type BotLevel = 'easy' | 'normal' | 'hard';
|
||||
|
||||
/** Share of computers at each level: 쉬움 35%, 보통 40%, 어려움 25%. */
|
||||
export const BOT_LEVEL_ODDS: Readonly<Record<BotLevel, number>> = { easy: 0.35, normal: 0.4, hard: 0.25 };
|
||||
|
||||
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
||||
|
||||
/**
|
||||
* The computer's own die roll in [0, 1), read straight from the random part of its id: the server makes bot ids as
|
||||
* `bot:<n>:<ULID>` with OS secure randomness (`secureRandom`), so the first 6 random characters are 30 uniform bits.
|
||||
* Other ids (tests, hand-made) fall back to a hash. Fixed for the id, so the computer keeps its level after a restart.
|
||||
*/
|
||||
export function botDraw(bot: string): number {
|
||||
const u = bot.split(':')[2] ?? '';
|
||||
if (!/^[0-9A-HJKMNP-TV-Z]{26}$/.test(u)) return hash01(bot, 'level');
|
||||
let v = 0;
|
||||
for (const ch of u.slice(10, 16)) v = v * 32 + CROCKFORD.indexOf(ch);
|
||||
return v / 32 ** 6;
|
||||
}
|
||||
|
||||
export function levelOf(draw: number): BotLevel {
|
||||
if (draw < BOT_LEVEL_ODDS.easy) return 'easy';
|
||||
return draw < BOT_LEVEL_ODDS.easy + BOT_LEVEL_ODDS.normal ? 'normal' : 'hard';
|
||||
}
|
||||
|
||||
export interface BotPersona {
|
||||
/** 똑똑한 편(근거를 보고 추리) / 허술한 편(느낌과 분위기를 따름). About half of the computers each. */
|
||||
/** 쉬움 / 보통 / 어려움: how often it slips in board games (`humanBest`). */
|
||||
level: BotLevel;
|
||||
/**
|
||||
* 똑똑한 편(근거를 보고 추리, 존댓말) / 허술한 편(느낌과 분위기를 따름, 반말): half of the computers each, by the
|
||||
* same roll as the level — every 쉬움 is 허술, every 어려움 똑똑, 보통 split in two.
|
||||
*/
|
||||
smart: boolean;
|
||||
/** Reaction speed multiplier (`botPace`): 0.7 quick … 1.5 slow. */
|
||||
pace: number;
|
||||
@@ -28,5 +59,6 @@ export interface BotPersona {
|
||||
}
|
||||
|
||||
export function botPersona(bot: string): BotPersona {
|
||||
return { smart: hash01(bot, 'smart') < 0.5, pace: botPace(bot), chatty: 0.5 + hash01(bot, 'chatty') * 0.5 };
|
||||
const draw = botDraw(bot);
|
||||
return { level: levelOf(draw), smart: draw >= 0.5, pace: botPace(bot), chatty: 0.5 + hash01(bot, 'chatty') * 0.5 };
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** 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;
|
||||
@@ -24,7 +25,7 @@ const waitingOf = (def: AnyGameDefinition, s: unknown): PlayerId[] => [...new Se
|
||||
*/
|
||||
export function botPlayout(
|
||||
def: AnyGameDefinition,
|
||||
opts: { players: PlayerId[]; options?: unknown; seed: RngState; maxSteps?: number; isBot: (p: PlayerId) => boolean },
|
||||
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]);
|
||||
@@ -48,7 +49,7 @@ export function botPlayout(
|
||||
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 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++;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/** Default "random but sensible" bot policy and small helpers shared by per-game strategies. */
|
||||
import type { BotInput } from './types';
|
||||
import type { BotLevel } from './persona';
|
||||
|
||||
type Act = { type?: string; [k: string]: unknown };
|
||||
|
||||
@@ -30,6 +31,60 @@ export function best<A>(xs: readonly A[], score: (a: A) => number, random: () =>
|
||||
return pick(top.length ? top : xs, random);
|
||||
}
|
||||
|
||||
/** How each level slips (docs/09-game-engine.md §9.1). */
|
||||
export interface BotPlay {
|
||||
/** Chance per move of a small inaccuracy: a move almost as good (within `window` × the game's `small`). */
|
||||
slip: number;
|
||||
window: number;
|
||||
/** Chance per move of a real blunder (사고): one of the next best few, up to `LAPSE_WINDOW` × `small` worse. */
|
||||
lapse: number;
|
||||
/** Chance of overlooking a must-play move (a win, mate, blocking a five, a free corner). */
|
||||
miss: number;
|
||||
}
|
||||
|
||||
export const BOT_PLAY: Readonly<Record<BotLevel, BotPlay>> = {
|
||||
easy: { slip: 0.35, window: 2, lapse: 0.06, miss: 0.12 },
|
||||
normal: { slip: 0.2, window: 1, lapse: 0.02, miss: 0.03 },
|
||||
hard: { slip: 0.08, window: 0.5, lapse: 0.005, miss: 0 },
|
||||
};
|
||||
|
||||
export const LAPSE_WINDOW = 8;
|
||||
|
||||
/**
|
||||
* Like `best`, but played by a person of `level`: usually the best move, now and then one that looked almost as good,
|
||||
* rarely a real mistake, and once in a while it doesn't see the winning / saving move. `small` is what a small
|
||||
* inaccuracy is worth in the game's score units; scores ≥ `critical` mark must-play moves. Without a level (tests,
|
||||
* `best` callers) it is exactly `best`.
|
||||
*/
|
||||
export function humanBest<A>(
|
||||
xs: readonly A[],
|
||||
score: (a: A) => number,
|
||||
random: () => number,
|
||||
level: BotLevel | undefined,
|
||||
scale: { small: number; critical: number },
|
||||
): A {
|
||||
if (!level || xs.length < 2) return best(xs, score, random);
|
||||
const scored = xs.map((a) => ({ a, s: score(a) }));
|
||||
const topScore = Math.max(...scored.map((x) => x.s));
|
||||
const top = pick(scored.filter((x) => x.s === topScore), random).a;
|
||||
const rest = scored.filter((x) => x.a !== top).sort((x, y) => y.s - x.s);
|
||||
const play = BOT_PLAY[level];
|
||||
const r = random();
|
||||
if (topScore >= scale.critical) {
|
||||
if (r >= play.miss) return top;
|
||||
// Didn't see it: plays one of the next moves that looked fine.
|
||||
return pick(rest.slice(0, 3), random).a;
|
||||
}
|
||||
if (r < play.lapse) {
|
||||
const near = rest.filter((x) => x.s >= topScore - LAPSE_WINDOW * scale.small).slice(0, 8);
|
||||
if (near.length) return pick(near, random).a;
|
||||
} else if (r < play.lapse + play.slip) {
|
||||
const near = rest.filter((x) => x.s >= topScore - play.window * scale.small).slice(0, 5);
|
||||
if (near.length) return pick(near, random).a;
|
||||
}
|
||||
return top;
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers to the human's requests: undo is accepted (it's practice), draw offers are declined.
|
||||
* Returns null when no request is pending.
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface BotInput<V = any, A = any> {
|
||||
legal: A[];
|
||||
/** Uniform [0, 1). */
|
||||
random: () => number;
|
||||
/** The computer's level (`humanBest`); absent in tests that want the plain best move. */
|
||||
level?: import('./persona').BotLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user