Merge branch 'm9/bots' into codex/owner/grp_discord_joke-app

This commit is contained in:
EJClaw
2026-10-06 13:35:33 +09:00
73 changed files with 5355 additions and 38 deletions

View File

@@ -0,0 +1,50 @@
/** Every bot-enabled game: bots play only accepted actions, react in every window and never stall a game. */
import { describe, expect, test } from 'bun:test';
import { seedN, type AnyGameDefinition } from '@bg/engine';
import { GAMES } from '../index';
import { BOT_STRATEGIES, decideBotAction } from './index';
import { botPlayout } from './playout';
const isBot = (p: string) => p.startsWith('bot:');
const seats = (n: number, humans: number) => Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i}:x`));
function counts(def: AnyGameDefinition): number[] {
const range = def.playersFor?.(def.defaultOptions) ?? { min: def.minPlayers, max: def.maxPlayers };
const out = new Set([Math.max(2, range.min), Math.min(range.max, 4)]);
return [...out].filter((n) => !def.playerCountError?.(def.defaultOptions, n));
}
describe.each(Object.keys(BOT_STRATEGIES))('%s', (id) => {
const def = GAMES[id]!;
test('has a game definition with legalActions', () => {
expect(def).toBeDefined();
expect(typeof def.legalActions).toBe('function');
});
for (const n of counts(def)) {
test(`${n} players: one human who only times out, the rest bots — the game finishes`, () => {
for (let s = 1; s <= 3; s++) {
const r = botPlayout(def, { players: seats(n, 1), seed: seedN(s), isBot, maxSteps: 20_000 });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
expect(r.maxBotMs).toBeLessThan(250);
}
});
}
test('bots only: a whole game finishes without timeouts', () => {
const n = counts(def).at(-1)!;
for (let s = 1; s <= 2; s++) {
const r = botPlayout(def, { players: seats(n, 0), seed: seedN(100 + s), isBot, maxSteps: 30_000 });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
}
});
});
test('decideBotAction returns null when the bot has nothing to do', () => {
const def = GAMES.omok!;
const s = def.setup({ players: ['a', 'bot:1:x'], options: def.defaultOptions, rng: { next: () => 0.5, int: () => 0 } as never, now: 0 });
const waiting = def.activePlayers(s)[0]!;
const other = waiting === 'a' ? 'bot:1:x' : 'a';
expect(decideBotAction(def, s, other, { now: 0 })).toBeNull();
expect(decideBotAction(def, s, waiting, { now: 0 })).not.toBeNull();
});

View File

@@ -0,0 +1,94 @@
/**
* Computer players (docs/09-game-engine.md §9). `decideBotAction` is the only place that touches the game state:
* 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 type { BotStrategy } from './types';
import { pick, playable, randomPolicy } from './policy';
import { omokBot } from '../omok/bot';
import { othelloBot } from '../othello/bot';
import { chessBot } from '../chess/bot';
import { janggiBot } from '../janggi/bot';
import { badukBot } from '../baduk/bot';
import { seotdaBot } from '../seotda/bot';
import { pokerBot } from '../poker/bot';
import { yachtBot } from '../yacht/bot';
import { yutBot } from '../yut/bot';
import { oneCardBot } from '../one-card/bot';
import { rummikubBot } from '../rummikub/bot';
import { gostopBot } from '../gostop/bot';
import { bangBot } from '../bang/bot';
import { davinciBot } from '../davinci-code/bot';
import { mahjongBot } from '../mahjong/bot';
import { marbleBot } from '../marble/bot';
import { dalmutiBot } from '../dalmuti/bot';
import { splendorBot } from '../splendor/bot';
import { quoridorBot } from '../quoridor/bot';
import { lasVegasBot } from '../las-vegas/bot';
import { cockroachPokerBot } from '../cockroach-poker/bot';
import { ninetyNineBot } from '../ninety-nine/bot';
export type { BotInput, BotStrategy } from './types';
/** Strategy per bot-enabled game (must match `BOT_GAMES` in @bg/shared). */
export const BOT_STRATEGIES: Record<string, BotStrategy> = {
omok: omokBot,
othello: othelloBot,
chess: chessBot,
janggi: janggiBot,
baduk: badukBot,
seotda: seotdaBot,
poker: pokerBot,
yacht: yachtBot,
yut: yutBot,
'one-card': oneCardBot,
rummikub: rummikubBot,
gostop: gostopBot,
bang: bangBot,
'davinci-code': davinciBot,
mahjong: mahjongBot,
marble: marbleBot,
dalmuti: dalmutiBot,
splendor: splendorBot,
quoridor: quoridorBot,
'las-vegas': lasVegasBot,
'cockroach-poker': cockroachPokerBot,
'ninety-nine': ninetyNineBot,
};
/** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */
export function botCandidates(def: AnyGameDefinition, state: unknown, me: PlayerId): unknown[] {
return def.legalActions ? def.legalActions(state, me) : [];
}
/**
* Picks the bot's next action, or null when it has nothing to do. The strategy's choice is checked with `validate`
* (with the server clock); a rejected choice is dropped and the strategy asked again, so every returned action is
* one the server accepts. Validating only the chosen action keeps a move fast (chess validates ~0.3ms per move).
*/
export function decideBotAction(
def: AnyGameDefinition,
state: unknown,
me: PlayerId,
ctx: { now: number; random?: () => number },
): unknown | null {
let legal = botCandidates(def, state, me);
if (!legal.length) return null;
const random = ctx.random ?? Math.random;
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 });
} catch {
break;
}
if (action !== undefined && valid(action)) return action;
legal = legal.filter((a) => a !== action);
}
const rest = legal.filter(valid);
return rest.length ? pick(playable(rest), random) : null;
}

View File

@@ -0,0 +1,72 @@
/** 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;
}

View File

@@ -0,0 +1,58 @@
/** Default "random but sensible" bot policy and small helpers shared by per-game strategies. */
import type { BotInput } from './types';
type Act = { type?: string; [k: string]: unknown };
/** Actions a bot never starts on its own: requests to the human, resigning, chatting, editing tricks. */
const META = new Set(['requestUndo', 'offerDraw', 'claimDraw', 'resign', 'concede', 'leave', 'undoDraft', 'report', 'chat', 'reaction', 'emote', 'adjustTime']);
export const pick = <T>(xs: readonly T[], random: () => number): T => xs[Math.floor(random() * xs.length)]!;
export const typeOf = (a: unknown): string => String((a as Act | null)?.type ?? '');
/** Legal actions minus meta ones (kept if nothing else is left). */
export function playable<A>(legal: A[]): A[] {
const out = legal.filter((a) => !META.has(typeOf(a)));
return out.length ? out : legal;
}
/** Highest-scoring action; ties broken at random. */
export function best<A>(xs: readonly A[], score: (a: A) => number, random: () => number): A {
let top: A[] = [];
let topScore = -Infinity;
for (const a of xs) {
const s = score(a);
if (s > topScore) {
topScore = s;
top = [a];
} else if (s === topScore) top.push(a);
}
return pick(top.length ? top : xs, random);
}
/**
* Answers to the human's requests: undo is accepted (it's practice), draw offers are declined.
* Returns null when no request is pending.
*/
export function answerRequests<A>(legal: A[]): A | null {
for (const a of legal) {
const t = typeOf(a);
if (t === 'respondUndo') return { ...(a as object), accept: true } as A;
if (t === 'respondDraw') return { ...(a as object), accept: false } as A;
}
return null;
}
/** Random legal action, preferring to answer requests and skipping meta actions. */
export function randomPolicy<A>({ legal, random }: BotInput<unknown, A>): A {
return answerRequests(legal) ?? pick(playable(legal), random);
}
/** Random action, but "pass"-like actions only when nothing else is possible. */
export function preferPlay<A>(input: BotInput<unknown, A>, passTypes: string[] = ['pass', 'draw']): A {
const req = answerRequests(input.legal);
if (req) return req;
const all = playable(input.legal);
const plays = all.filter((a) => !passTypes.includes(typeOf(a)));
return pick(plays.length ? plays : all, input.random);
}

View File

@@ -0,0 +1,22 @@
/** Computer-player strategy contract (docs/09-game-engine.md §9). */
import type { PlayerId } from '@bg/engine';
/**
* Everything a bot may know when it decides: exactly what its own screen shows (`view` for itself)
* and the actions the server would accept from it right now. Never the game state (other hands, deck order).
*/
export interface BotInput<V = any, A = any> {
me: PlayerId;
/** Deep copy of `def.view(state, me)`; free to mutate. */
view: V;
/** Legal actions (from `legalActions`, each accepted by `validate`). Never empty. */
legal: A[];
/** Uniform [0, 1). */
random: () => number;
}
/**
* Returns the action to play. Usually one of `legal`; it may also build another action
* (e.g. accept an undo request) — the caller validates it and falls back to the default policy.
*/
export type BotStrategy<V = any, A = any> = (input: BotInput<V, A>) => A;