Files
joke-app/apps/server/src/rooms/bots.ts
EJClaw b98775b0a6 사과 게임: 같은 판(17×10) 합 10 만들기 경주, 1~8명·혼자 가능, 레벨별 컴퓨터(라이브 봇)
- 규칙 모듈 packages/games/src/apple: 시드로 만든 한 판(1~9, 합 10의 배수)을 모두 각자 풀고,
  직사각형 합이 딱 10이면 지운 개수만큼 점수. 빈 칸은 합에 영향 없음, 합≠10·빈 직사각형은 거절(벌점 없음).
  3초 카운트다운(판 숨김) → 제한 시간 1/2/3분(기본 2분), 서버 시계 마감(deadline = timeoutNotBefore,
  끊긴 사람 조기 시간 초과 없음), 1초 5번 속도 제한, 더 지울 게 없으면 막힘 → 모두 막히면 조기 종료,
  나가면 맨 아래 순위·혼자 남으면 끝. 동점은 같은 순위, 결과 "사과 N개".
- view는 내 판(170자 문자열)과 모두의 점수만(남의 판 없음). findMoves는 누적합으로 가장 좁은 합 10 직사각형 전부.
- 컴퓨터: 마피아처럼 LIVE_BOT_STRATEGIES.apple. live 전략에 level 전달(서버 bots.ts, live-playout).
  레벨 따라 찾는 시간(6초→2초)·시야·놓침(쉬움 30%)·고르기가 달라짐. 2분 평균 레벨1 약 28개 ~ 레벨60 약 99개.
- 화면 apps/web/src/games/apple: SVG 사과, 포인터 드래그(마우스·터치), 합계 실시간·10이면 초록,
  낙관적 지우기와 튀어 오르는 애니메이션, 휴대폰은 판을 돌려 10열×17줄, 키보드(화살표+스페이스 두 번, Esc),
  다른 사람 점수 칩, 다크 모드, 도움말·30초 요약.
- 등록(GAMES, CATALOG, BOT_GAMES, 화면 레지스트리, 아이콘·파티 탭), 문서 docs/games/apple.md, 09 §9 라이브 봇 줄.
- 테스트: 규칙 15개(무차별 대조, 무작위 대국 1·2·5·8명), 컴퓨터 5개, 도움말 2개, 방 통합 2개(컴퓨터와 끝까지),
  E2E(PC 마우스·키보드, 휴대폰 CDP 터치, 320px, 1분 뒤 결과).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 22:20:49 +09:00

309 lines
14 KiB
TypeScript

/**
* Computer players' driver (docs/06-lobby-rooms.md §12, docs/09-game-engine.md §9).
* After every state change the room calls `schedule()`: if the game waits on a bot, one action is planned after a
* short human-like pause and played through the room's normal action path (validated, logged as `act`).
*/
import { secureRandom, type AnyGameDefinition } from '@bg/engine';
import { isBotId } from '@bg/shared';
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots';
import type { BotBrain } from '../ai/brain';
export { botPace };
export interface BotRoom {
readonly status: string;
readonly game: { state: unknown; players: string[]; finished: boolean } | null;
readonly def: AnyGameDefinition;
now(): number;
/** When the turn timer runs out (room clock), or null without one. */
deadline?(): number | null;
/** Runs the action as `actor` through the room's normal path; returns an error message on rejection. */
run(actor: string, action: unknown): string | null;
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
/** Display name of a player (live bots talk about each other by name). */
nameOf?(id: string): string;
/** A computer's level now and the level it started with (docs/09 §9.1); absent = fixed by the id. */
profile?(bot: string): { level: number; base: number };
/** The computers' talk and visible activity with the local model (docs/06 §12.1). */
brain?: BotBrain;
}
/** What a planned computer move looks like, for its thinking time. */
export interface BotDelayInput {
/** How many moves the bot can choose from. */
choices: number;
/** People may act in the same window (e.g. 원카드 외치기, 마작 울기, simultaneous choices). */
withPeople: boolean;
/** The bot's user id: each computer has its own pace. */
bot: string;
/** The same bot just acted and is still on (e.g. yacht keep → roll): it already knows what it wants. */
followUp: boolean;
}
/**
* Human-like thinking time (ms). A forced move still takes a moment to notice (0.7~1.3 s); a real choice takes longer
* the more moves there are (1.6~3.9 s), and now and then the computer hesitates (+1~3 s). Each bot scales it by its
* own pace, and a follow-up move of the same turn is quicker. When people may act in the same window the computer
* waits 1.5 s more so it never beats a person to a reaction just by being fast.
*/
export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom): number {
const { choices, withPeople, bot, followUp } = input;
let ms = choices <= 1 ? 700 + random() * 600 : 1300 + 300 * Math.min(Math.log2(choices), 4) + random() * 1400;
if (choices > 1 && !followUp && random() < 0.12) ms += 1000 + random() * 2000;
ms *= botPace(bot);
if (followUp) ms *= 0.5;
return Math.round(withPeople ? ms + 1500 : ms);
}
/** Never use more than this share of the time left on the turn timer for thinking. */
export const BOT_DEADLINE_SHARE = 0.5;
/** Bot move budget (ms); slower decisions are logged. */
export const BOT_SLOW_MS = 50;
export class BotDriver {
private timer: ReturnType<typeof setTimeout> | null = null;
/** When the planned action is due (room clock); null when nothing is planned. */
dueAt: number | null = null;
/** Bot the planned action is for. */
private planned: string | null = null;
/** Bot whose action is being played right now: if it is still on afterwards, its next move is a follow-up. */
private acting: string | null = null;
/** Live games (마피아): when each computer looks at the game again, and its notes for the current game. */
private liveDue = new Map<string, number>();
private liveMemory = new Map<string, Record<string, unknown>>();
private liveGame: unknown = null;
/** A computer is typing / about to move with the model (turn games: one at a time; live games: per computer). */
private busy: string | null = null;
private liveBusy = new Set<string>();
constructor(
private room: BotRoom,
private random: () => number = secureRandom,
private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random),
) {}
/** Plans the next bot action if the game is waiting on a bot. Keeps an already planned one (the bot is "thinking"). */
schedule(): void {
if (this.liveStrategy()) return this.scheduleLive();
if (this.dueAt !== null || this.busy) return;
const next = this.next();
if (!next) return;
// People can see it think: "생각 중…" until it moves.
if (this.room.brain?.enabled()) this.room.brain.thinking(next.bot, true);
const now = this.room.now();
let ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting });
const deadline = this.room.deadline?.() ?? null;
if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE));
this.dueAt = now + ms;
this.planned = next.bot;
this.arm();
}
cancel(): void {
if (this.timer) clearTimeout(this.timer);
this.timer = null;
if (this.planned) this.room.brain?.thinking(this.planned, false);
this.dueAt = null;
this.planned = null;
this.liveDue.clear();
}
private liveStrategy(): LiveBotStrategy | null {
return LIVE_BOT_STRATEGIES[this.room.def.id] ?? null;
}
/**
* Live games: every computer has its own timer and is asked again and again (it may also do nothing), so several
* computers talk and vote at the same time, each at its own speed. A planned look stays planned.
*/
private scheduleLive(): void {
const g = this.room.game;
if (!g || g.finished || this.room.status !== 'playing') {
if (this.timer) clearTimeout(this.timer);
this.timer = null;
this.dueAt = null;
return;
}
if (this.liveGame !== g) {
this.liveGame = g;
this.liveMemory.clear();
this.liveDue.clear();
}
const now = this.room.now();
for (const p of g.players) {
if (isBotId(p) && !this.liveDue.has(p)) this.liveDue.set(p, now + Math.round((300 + this.random() * 1200) * botPace(p)));
}
const next = Math.min(...this.liveDue.values());
this.dueAt = Number.isFinite(next) ? next : null;
if (this.dueAt !== null) this.arm();
}
/** Lets every computer whose time has come look at the game once. */
private fireLive(strategy: LiveBotStrategy): void {
const now = this.room.now();
const due = [...this.liveDue.entries()].filter(([, t]) => t <= now).sort((a, b) => a[1] - b[1]);
for (const [bot] of due) {
const g = this.room.game;
if (!g || g.finished || this.room.status !== 'playing') return;
if (this.liveBusy.has(bot)) {
this.liveDue.set(bot, now + 500);
continue;
}
const def = this.room.def;
const memory = this.liveMemory.get(bot) ?? {};
this.liveMemory.set(bot, memory);
const names: Record<string, string> = {};
for (const p of g.players) names[p] = this.room.nameOf?.(p) ?? p;
let decision: { action: unknown; next: number; hint?: string } = { action: null, next: 3000 };
const t0 = performance.now();
try {
const profile = this.room.profile?.(bot);
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, profile?.base), level: profile?.level ?? idLevel(bot), names, memory });
} catch (err) {
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
}
const ms = performance.now() - t0;
if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) });
this.liveDue.set(bot, now + Math.max(100, decision.next));
if (decision.action == null) continue;
if (!def.validate(g.state, bot, decision.action, { now }).ok) continue; // the moment passed (phase changed); look again later
const brain = this.room.brain;
const say = decision.action as { type?: string; channel?: string; text?: string };
if (brain && say.type === 'chat' && brain.enabled()) {
this.typeLive(brain, bot, say as { type: 'chat'; channel: string; text: string }, decision.hint ?? null, names, g);
continue;
}
const err = this.room.run(bot, decision.action);
if (err) this.room.log?.('warn', 'bot action rejected', { game: def.id, action: decision.action, err });
}
this.scheduleLive();
}
/**
* Live chat like a person: the model may say the planned line in the computer's own words, then "입력 중…" for the
* typing time, then it is sent (if it still may be: the phase can end meanwhile).
*/
private typeLive(brain: BotBrain, bot: string, chat: { type: 'chat'; channel: string; text: string }, hint: string | null, names: Record<string, string>, g: unknown): void {
this.liveBusy.add(bot);
const view = this.room.def.view(this.room.game!.state, bot) as { chat?: { channel: string; from: string; text: string }[] };
const recent = (view.chat ?? []).filter((m) => m.channel === chat.channel).slice(-8).map((m) => ({ from: names[m.from] ?? '누군가', text: m.text }));
void (hint ? brain.mafiaLine(bot, hint, chat.text, recent) : Promise.resolve(chat.text))
.catch(() => chat.text)
.then((text) =>
brain.type(bot, text, () => {
const game = this.room.game;
if (!game || game !== g || game.finished) return;
const action = { ...chat, text };
const ok = this.room.def.validate(game.state, bot, action, { now: this.room.now() }).ok;
const err = ok ? this.room.run(bot, action) : this.room.def.validate(game.state, bot, chat, { now: this.room.now() }).ok ? this.room.run(bot, chat) : null;
if (err) this.room.log?.('warn', 'bot chat rejected', { game: this.room.def.id, err });
}),
)
.finally(() => {
this.liveBusy.delete(bot);
});
}
private arm(): void {
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(() => this.fire(), Math.max(0, (this.dueAt ?? 0) - this.room.now()));
}
/** Bot waited on by the game that has something to do, in seat order. */
private next(): { bot: string; choices: number; withPeople: boolean } | null {
const g = this.room.game;
if (!g || g.finished || this.room.status !== 'playing' || !g.players.some(isBotId)) return null;
const def = this.room.def;
const active = def.activePlayers(g.state);
const waiting = new Set([...active, ...(def.timeoutPlayers?.(g.state) ?? [])]);
const withPeople = active.some((p) => !isBotId(p));
for (const p of g.players) {
if (!isBotId(p) || !waiting.has(p)) continue;
const choices = botCandidates(def, g.state, p).length;
if (choices > 0) return { bot: p, choices, withPeople };
}
return null;
}
/** Plays the planned action when due. Public for tests (with a fake clock). */
fire(): void {
if (this.timer) clearTimeout(this.timer);
this.timer = null;
if (this.dueAt === null) return;
if (this.room.now() < this.dueAt) return this.arm();
const live = this.liveStrategy();
if (live) {
this.dueAt = null;
return this.fireLive(live);
}
const planned = this.planned;
this.dueAt = null;
this.planned = null;
const next = this.next();
const g = this.room.game;
if (!next || !g) return;
// Another bot's turn came up meanwhile: give it its own thinking time.
if (next.bot !== planned) return this.schedule();
const def = this.room.def;
const t0 = performance.now();
let action: unknown;
try {
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random, level: this.room.profile?.(next.bot).level ?? idLevel(next.bot) });
} catch (err) {
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
action = null;
}
const ms = performance.now() - t0;
if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) });
const brain = this.room.brain;
if (brain && action != null && brain.enabled()) {
// Like a person: maybe type something first (the model writes it; "입력 중…" while typing), then move.
const bot = next.bot;
this.busy = bot;
void brain
.beforeMove(bot, action, def.view(g.state, bot))
.catch(() => action)
.then((chosen) => {
this.busy = null;
brain.thinking(bot, false);
if (this.room.game !== g || g.finished || this.room.status !== 'playing') return;
const ok = (a: unknown) => def.validate(g.state, bot, a, { now: this.room.now() }).ok;
// The game moved on while it was typing (a timer, someone left): think again.
if (!ok(chosen) && !ok(action)) return this.schedule();
this.acting = bot;
try {
this.playPlanned(bot, ok(chosen) ? chosen : action);
} finally {
this.acting = null;
}
});
return;
}
brain?.thinking(next.bot, false);
this.acting = next.bot;
try {
this.playPlanned(next.bot, action);
} finally {
this.acting = null;
}
}
private playPlanned(bot: string, action: unknown): void {
const def = this.room.def;
let err = action == null ? 'no action' : this.room.run(bot, action);
if (err) {
this.room.log?.('warn', 'bot action rejected', { game: def.id, action, err });
// Last resort before the turn timer: the game's own timeout action.
try {
if (!this.room.game?.finished) err = this.room.run(bot, def.onTimeout(this.room.game!.state, bot));
} catch {
// keep err
}
if (err) return; // give up until the next state change; the room's deadline still applies
}
this.schedule();
}
}