컴퓨터 난이도(쉬움 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:
@@ -30,6 +30,25 @@ export function createSeed(): ChaChaSeed {
|
||||
return [...buf] as ChaChaSeed;
|
||||
}
|
||||
|
||||
/** Pool of OS random words for `secureRandom` (one `getRandomValues` call per 256 numbers). */
|
||||
const pool = new Uint32Array(512);
|
||||
let poolAt = pool.length;
|
||||
|
||||
/**
|
||||
* Uniform float in [0, 1) with 53 random bits from the operating system's secure source (`crypto.getRandomValues`),
|
||||
* a drop-in for `Math.random` wherever the server picks something nobody should be able to predict: computer moves,
|
||||
* thinking times, room codes, computer ids (2026-10-11). Game dice/cards/tiles use the seeded ChaCha20 below.
|
||||
*/
|
||||
export function secureRandom(): number {
|
||||
if (poolAt + 2 > pool.length) {
|
||||
crypto.getRandomValues(pool);
|
||||
poolAt = 0;
|
||||
}
|
||||
const hi = pool[poolAt++]! >>> 5; // 27 bits
|
||||
const lo = pool[poolAt++]! >>> 6; // 26 bits
|
||||
return (hi * 67108864 + lo) / 9007199254740992;
|
||||
}
|
||||
|
||||
export function seedToHex(seed: RngState): string {
|
||||
return seed.map((n) => (n >>> 0).toString(16).padStart(8, '0')).join('');
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* agrees, after restoring the automatic suggestion if the marks were changed against it.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests, best, pick, playable, typeOf } from '../bots/policy';
|
||||
import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy';
|
||||
import type { BadukView } from './index';
|
||||
import { emptyRegionAt, mapChains, markGroup, neighbours, regionsOf, suggestMarks, type Cell, type Stone } from './board';
|
||||
|
||||
@@ -35,7 +35,7 @@ function scoringAction(view: BadukView): Act {
|
||||
return { type: 'agreeScore' };
|
||||
}
|
||||
|
||||
export const badukBot: BotStrategy<BadukView, Act> = ({ view, legal, random }) => {
|
||||
export const badukBot: BotStrategy<BadukView, Act> = ({ view, legal, random, level }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
if (view.phase === 'scoring') return legal.some((a) => a.type === 'agreeScore') ? scoringAction(view) : pick(playable(legal), random);
|
||||
@@ -131,7 +131,8 @@ export const badukBot: BotStrategy<BadukView, Act> = ({ view, legal, random }) =
|
||||
// Very long game (endless capture fights): wind down so it always ends.
|
||||
if (view.moveCount > 2 * board.length) return pass;
|
||||
const scores = new Map(places.map((p) => [p, score(p)]));
|
||||
const top = places.length ? best(places, (p) => scores.get(p)!, random) : null;
|
||||
// Small = a shape point; capturing or saving three stones or more (≥ 24) is a must-play move.
|
||||
const top = places.length ? humanBest(places, (p) => scores.get(p)!, random, level, { small: 1.5, critical: 24 }) : null;
|
||||
// Nothing useful left (only settled areas, dame on the edge or self-atari): pass so the game can end.
|
||||
return top && scores.get(top)! > 1 ? top : pass;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* (and under-promotes only when queening would stalemate).
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests, best, pick, playable, typeOf } from '../bots/policy';
|
||||
import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy';
|
||||
import type { ChessView } from './index';
|
||||
import { moveInfo, type PieceType } from './movegen';
|
||||
import { PIECE_VALUE, insufficientMaterial, load, pieces } from './rules';
|
||||
@@ -15,7 +15,7 @@ const NEAR_CENTER = new Set(['c3', 'd3', 'e3', 'f3', 'c4', 'f4', 'c5', 'f5', 'c6
|
||||
/** Piece type of a raw generator move field (1..6). */
|
||||
const TYPE = (n: number) => ' pnbrqk'[n] as PieceType;
|
||||
|
||||
export const chessBot: BotStrategy<ChessView> = ({ view, legal, random }) => {
|
||||
export const chessBot: BotStrategy<ChessView> = ({ view, legal, random, level }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
const moves = legal.filter((a) => typeOf(a) === 'move') as Move[];
|
||||
@@ -75,5 +75,6 @@ export const chessBot: BotStrategy<ChessView> = ({ view, legal, random }) => {
|
||||
c.unmake();
|
||||
}
|
||||
};
|
||||
return best(moves, score, random);
|
||||
// 100 = a pawn; mate in one (1e6) is a must-play move.
|
||||
return humanBest(moves, score, random, level, { small: 40, critical: 1e5 });
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* prise > 장군 > activity. Knows 빅장 (judged by score), the 4th-repetition rule and when a 한수쉼 ends the game.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests, best, pick, playable, typeOf } from '../bots/policy';
|
||||
import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy';
|
||||
import type { JanggiView } from './index';
|
||||
import {
|
||||
HAN_BONUS,
|
||||
@@ -77,7 +77,7 @@ function threat(b: Board, me: Side): number {
|
||||
return worst;
|
||||
}
|
||||
|
||||
export const janggiBot: BotStrategy<JanggiView> = ({ view, legal, random }) => {
|
||||
export const janggiBot: BotStrategy<JanggiView> = ({ view, legal, random, level }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
const moves = legal.filter((a) => typeOf(a) === 'move') as Move[];
|
||||
@@ -134,5 +134,6 @@ export const janggiBot: BotStrategy<JanggiView> = ({ view, legal, random }) => {
|
||||
return base;
|
||||
};
|
||||
const options: (Move | Pass)[] = pass ? [...moves, pass] : moves;
|
||||
return best(options, (a) => (typeOf(a) === 'pass' ? passScore() : scoreMove(a as Move)), random);
|
||||
// 100 = one point of material; 외통 (1e7) and a winning judgement (1e5) are must-play moves.
|
||||
return humanBest(options, (a) => (typeOf(a) === 'pass' ? passScore() : scoreMove(a as Move)), random, level, { small: 40, critical: 1e5 });
|
||||
};
|
||||
|
||||
@@ -88,7 +88,7 @@ describe('whole games', () => {
|
||||
players: seats(7, 0),
|
||||
seed: seedN(s),
|
||||
isBot,
|
||||
personaOf: (p, st): BotPersona => ({ smart: roleOf(st, p) === 'mafia' ? mafiaSmart : townSmart, pace: botPace(p), chatty: 0.8 }),
|
||||
personaOf: (p, st): BotPersona => ({ level: 'normal', smart: roleOf(st, p) === 'mafia' ? mafiaSmart : townSmart, pace: botPace(p), chatty: 0.8 }),
|
||||
});
|
||||
if ((r.state as MafiaState).winner === 'town') town++;
|
||||
}
|
||||
@@ -128,8 +128,8 @@ describe('timing and answers', () => {
|
||||
const { st, players } = toPhase('vote');
|
||||
const names = Object.fromEntries(players.map((p, i) => [p, i ? `컴퓨터 ${i + 1}` : '철수']));
|
||||
const bot = players[2]!;
|
||||
const quick = firstAction(st, bot, { smart: true, pace: 0.7, chatty: 0.8 }, names, 'vote')!;
|
||||
const slow = firstAction(st, bot, { smart: true, pace: 1.5, chatty: 0.8 }, names, 'vote')!;
|
||||
const quick = firstAction(st, bot, { level: 'hard', smart: true, pace: 0.7, chatty: 0.8 }, names, 'vote')!;
|
||||
const slow = firstAction(st, bot, { level: 'hard', smart: true, pace: 1.5, chatty: 0.8 }, names, 'vote')!;
|
||||
expect(quick.at).toBeLessThan(slow.at);
|
||||
expect(slow.at).toBeLessThan(st.options.voteSeconds * 1000);
|
||||
});
|
||||
@@ -142,7 +142,7 @@ describe('timing and answers', () => {
|
||||
const memory: Record<string, unknown> = {};
|
||||
let answer: { text: string; at: number } | null = null;
|
||||
for (let t = now + 1000; t < now + 20_000 && !answer; ) {
|
||||
const d = mafiaBot({ me: bot, view: mafia.view(asked, bot), now: t, random: Math.random, persona: { smart: true, pace: 1, chatty: 0.8 }, names, memory });
|
||||
const d = mafiaBot({ me: bot, view: mafia.view(asked, bot), now: t, random: Math.random, persona: { level: 'hard', smart: true, pace: 1, chatty: 0.8 }, names, memory });
|
||||
const a = d.action as { type: string; text?: string } | null;
|
||||
if (a?.type === 'chat' && memory.done && Object.keys(memory.done as object).some((k) => k.includes(':r:'))) answer = { text: a.text!, at: t - now - 1000 };
|
||||
t += Math.max(50, d.next);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** 오목 computer player: win > block a five > open four > block open three > build lines near the stones. */
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests, best, pick, playable, typeOf } from '../bots/policy';
|
||||
import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy';
|
||||
import type { OmokView } from './index';
|
||||
|
||||
type Place = { type: 'place'; x: number; y: number };
|
||||
@@ -40,7 +40,7 @@ function lineValue(board: number[], size: number, x: number, y: number, color: n
|
||||
return total;
|
||||
}
|
||||
|
||||
export const omokBot: BotStrategy<OmokView> = ({ view, legal, random }) => {
|
||||
export const omokBot: BotStrategy<OmokView> = ({ view, legal, random, level }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
const places = legal.filter((a) => typeOf(a) === 'place') as Place[];
|
||||
@@ -62,7 +62,8 @@ export const omokBot: BotStrategy<OmokView> = ({ view, legal, random }) => {
|
||||
// "exact five"; assume the default "five or more").
|
||||
const overline = (c: number) => view.ruleSet === 'free' || (view.ruleSet === 'renju' && c === 2);
|
||||
const center = (size - 1) / 2;
|
||||
return best(
|
||||
// A person now and then plays a slightly different shape or misses a threat (≥ 50,000: win or block a five).
|
||||
return humanBest(
|
||||
close.length ? close : places,
|
||||
(p) =>
|
||||
lineValue(board, size, p.x, p.y, me, overline(me)) * 1.1 +
|
||||
@@ -70,5 +71,7 @@ export const omokBot: BotStrategy<OmokView> = ({ view, legal, random }) => {
|
||||
(Math.abs(p.x - center) + Math.abs(p.y - center)) * 0.1 +
|
||||
random() * 0.5,
|
||||
random,
|
||||
level,
|
||||
{ small: 150, critical: 50_000 },
|
||||
);
|
||||
};
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
* corner, keep the opponent's choices few; flip counts only matter near the end.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests, best, pick, playable, typeOf } from '../bots/policy';
|
||||
import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy';
|
||||
import type { OthelloView } from './index';
|
||||
import { CORNERS, legalMoves, type Cell, type Disc } from './rules';
|
||||
|
||||
type Place = { type: 'place'; x: number; y: number };
|
||||
|
||||
export const othelloBot: BotStrategy<OthelloView> = ({ view, legal, random }) => {
|
||||
export const othelloBot: BotStrategy<OthelloView> = ({ view, legal, random, level }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
const places = legal.filter((a) => typeOf(a) === 'place') as Place[];
|
||||
@@ -44,5 +44,6 @@ export const othelloBot: BotStrategy<OthelloView> = ({ view, legal, random }) =>
|
||||
else if (edgeX || edgeY) v += 10;
|
||||
return v;
|
||||
};
|
||||
return best(places, score, random);
|
||||
// 1.5 = one more reply for the opponent; a free corner (+100) is a must-play move.
|
||||
return humanBest(places, score, random, level, { small: 3, critical: 90 });
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user