M9: 컴퓨터 상대 — 게임 22종 컴퓨터 전략, 서버 구동(BotDriver), 연습 방

- packages/shared/src/bots.ts: 컴퓨터 id(bot:<n>:<ulid>)·프로필(컴퓨터 n)·BOT_GAMES
  (도블·할리갈리·그림 맞히기·마피아 제외)
- packages/games/src/bots: 전략 계약(자기 view + 합법 수만), decideBotAction(validate 재검사),
  게임별 <게임>/bot.ts 22개 + 행동 테스트, 전 게임 판 끝까지 돌리는 공통 테스트
- 서버: Room.addBot/removeBot(방장·대기실만, 방은 친구만), RoomManager.createPractice
  (POST /api/rooms {practice:true}), BotDriver(사람 같은 지연, 사람과 같은 창이면 더 천천히,
  재시작 후 다시 예약), 연습 게임은 전적 제외(result_json.practice), 사람이 모두 나가면 무효
- 프로토콜 addBot/removeBot, 문서 03·06 §12·08·09 §8

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-06 13:32:28 +09:00
parent c27cb0a11a
commit a3f81ded37
67 changed files with 5113 additions and 18 deletions

View File

@@ -0,0 +1,90 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { randomPolicy } from '../bots/policy';
import { yut, type NodeId, type Throw, type YutOptions, type YutState } from './index';
const isBot = (p: string) => p.startsWith('bot');
/** Two-player game, side 0 ('bot') to move with these results. */
function moving(pending: Throw[], opts: Partial<YutOptions> = {}): YutState {
const s = yut.setup({ players: ['bot', 'H'], options: yut.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
Object.assign(s, { turnSide: 0, current: 'bot', phase: 'move', throwsOwed: 0, pending });
return s;
}
function put(s: YutState, side: number, piece: number, node: NodeId, trail: NodeId[] = [node]): void {
Object.assign(s.sides[side]!.pieces[piece]!, { status: 'board', node, trail, lapped: node === 0 });
}
const decide = (s: YutState) => decideBotAction(yut, s, s.current, { now: 1, random: () => 0.5 });
describe('yut bot', () => {
test('throws when it is time to throw', () => {
const s = yut.setup({ players: ['bot', 'H'], options: yut.defaultOptions, rng: SeededRng.fromSeed(seedN(1)), now: 0 });
Object.assign(s, { turnSide: 0, current: 'bot' });
expect(decide(s)).toEqual({ type: 'THROW' });
});
test('catches an enemy piece instead of just running ahead', () => {
const s = moving(['geol']);
put(s, 0, 0, 2);
put(s, 0, 1, 12);
put(s, 1, 0, 5);
expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 0, from: 2 });
});
test('uses 모 on the piece standing on a corner to take the shortcut home', () => {
const s = moving(['mo']);
put(s, 0, 0, 10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
put(s, 0, 1, 3, [1, 2, 3]);
// From 10 the diagonal leads 25 → 26 → 22 → 27 → 28: five steps that nearly finish.
expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 0, from: 10 });
});
test('does not stop right in front of an enemy when an equal move is safe', () => {
const s = moving(['gae']);
for (const side of [0, 1]) for (const p of s.sides[side]!.pieces) Object.assign(p, { status: 'done', node: null, trail: [] });
put(s, 0, 0, 7);
put(s, 0, 1, 14);
put(s, 1, 0, 15);
// 14 → 16 would stand one 도 ahead of the enemy on 15; 7 → 9 is out of its reach.
expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 0, from: 7 });
});
test('beats a random player clearly in 1-on-1', () => {
let wins = 0;
const games = 20;
for (let g = 1; g <= games; g++) {
const rng = SeededRng.fromSeed(seedN(g));
const chooser = SeededRng.fromSeed(seedN(g + 500));
const random = () => chooser.next();
const players = g % 2 ? ['bot', 'rnd'] : ['rnd', 'bot'];
let s = yut.setup({ players, options: yut.defaultOptions, rng, now: 0 });
for (let i = 0; i < 5000 && !yut.result(s); i++) {
const p = s.current;
const a = p === 'bot' ? decideBotAction(yut, s, p, { now: 1, random }) : randomPolicy({ me: p, view: null, legal: yut.legalActions!(s, p), random });
s = yut.apply(s, p, a as never, { rng, now: 1 }).state;
}
if (yut.result(s)!.ranking[0]!.includes('bot')) wins++;
}
expect(wins).toBeGreaterThanOrEqual(14);
});
for (const [opts, n] of [
[{ mode: 'team' as const }, 4],
[{ mode: 'team' as const, pieces: 2 as const }, 6],
[{ finishRule: 'reach' as const, backdoFromDo: 'finish' as const, nakPercent: 10 as const, stickModel: 'fair' as const }, 3],
[{ ranking: 'all' as const, backdo: false }, 4],
] as const) {
test(`option mode ${JSON.stringify(opts)} with ${n} players finishes`, () => {
const options = yut.optionsSchema.parse(opts);
const players = Array.from({ length: n }, (_, i) => (i === 1 ? 'human' : `bot:${i}`));
for (let g = 1; g <= 3; g++) {
const r = botPlayout(yut, { players, options, seed: seedN(g), isBot });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
expect(r.maxBotMs).toBeLessThan(100);
}
});
}
});

View File

@@ -0,0 +1,61 @@
/**
* 윷놀이 computer player. Each legal move is scored by: catching enemies (worth their progress + the bonus throw),
* steps of progress (shortcuts and finishing come out of the distance table), stacking a little, and the chance an
* enemy lands on the piece with its next throw (estimated from the visible board and the throw odds).
*/
import type { BotStrategy } from '../bots/types';
import { answerRequests, best, pick, playable } from '../bots/policy';
import { FLAT_P, GOAL, THROW_STEPS, advance, defaultPrev, remainingDistance, throwProbabilities, type NodeId, type Throw } from './board';
import type { YutAction, YutLegalMove, YutView } from './index';
const STEP = 3; // points per step of progress per piece
const THROWS: Throw[] = ['backdo', 'do', 'gae', 'geol', 'yut', 'mo'];
export const yutBot: BotStrategy<YutView, YutAction> = ({ view, legal, random }) => {
const req = answerRequests(legal);
if (req) return req;
const moves = legal.filter((a) => a.type === 'MOVE') as Extract<YutAction, { type: 'MOVE' }>[];
if (!moves.length || !view.legalMoves) return pick(playable(legal), random);
const o = view.options;
const me = view.mySide;
const dist = (n: NodeId | 'home' | typeof GOAL) => (n === GOAL ? 0 : remainingDistance(n, o.finishRule));
const home = dist('home');
const odds = throwProbabilities(FLAT_P[o.stickModel], o.backdo);
const live = new Set(view.sides.filter((x) => x.id !== me && !x.out && x.finishedRank === null).map((x) => x.id));
const enemyStacks = view.stacks.filter((st) => live.has(st.side));
const enemyHome = view.sides.some((x) => live.has(x.id) && x.home > 0);
/** Chance that some enemy can land on `node` with its next throw (bonus throws ignored). */
const risk = (node: NodeId): number => {
let p = 0;
for (const t of THROWS) {
const hits =
(t !== 'backdo' && enemyHome && advance('home', THROW_STEPS[t], o.finishRule).to === node) ||
enemyStacks.some((st) => (t === 'backdo' ? defaultPrev(st.node) === node : advance(st.node, THROW_STEPS[t], o.finishRule).to === node));
if (hits) p += odds[t];
}
return Math.min(1, p);
};
const mineAt = (node: NodeId) => view.stacks.find((st) => st.side === me && st.node === node)?.count ?? 0;
/** What losing `n` own pieces standing on `node` would cost. */
const exposure = (node: NodeId, n: number) => STEP * n * (home - dist(node)) + 10;
const score = (m: YutLegalMove): number => {
let v = STEP * m.count * (dist(m.from) - dist(m.to));
if (m.from !== 'home') v += risk(m.from) * exposure(m.from, m.count); // leaving danger
if (m.finishes) return v + 15 * m.count;
const to = m.to as NodeId;
if (m.captures) v += 30 + m.captures * (STEP * (home - dist(to)) + 10);
const group = m.count + (m.stacks ? mineAt(to) : 0);
if (m.stacks) v += 6;
// After a capture we throw again first, so the danger matters less.
v -= (m.captures ? 0.5 : 1) * risk(to) * exposure(to, group);
return v;
};
const byKey = new Map(view.legalMoves.map((m) => [`${m.throwIndex}:${m.from}`, m]));
return best(moves, (a) => {
const m = byKey.get(`${a.throwIndex}:${a.from}`);
return m ? score(m) : -1e9;
}, random);
};