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,67 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { yacht, type YachtOptions, type YachtState } from './index';
const random = () => 0.5;
const isBot = (p: string) => p.startsWith('bot');
/** Bot to move with forced dice after `rollsUsed` rolls. */
function at(dice: number[], rollsUsed: number, opts: Partial<YachtOptions> = {}, scores: YachtState['sheets'][string]['scores'] = {}): YachtState {
const s = yacht.setup({ players: ['bot'], options: yacht.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
s.dice = dice;
s.rollsUsed = rollsUsed;
s.sheets.bot!.scores = scores;
return s;
}
const decide = (s: YachtState) => decideBotAction(yacht, s, 'bot', { now: 1, random });
describe('yacht bot', () => {
test('rolls first, then keeps four sixes and rerolls the odd die', () => {
const s = yacht.setup({ players: ['bot'], options: yacht.defaultOptions, rng: SeededRng.fromSeed(seedN(1)), now: 0 });
expect(decide(s)).toEqual({ type: 'roll' });
expect(decide(at([6, 2, 6, 6, 6], 1))).toEqual({ type: 'hold', held: [true, false, true, true, true] });
});
test('scores a yacht at once and a large straight in its box', () => {
expect(decide(at([4, 4, 4, 4, 4], 1))).toEqual({ type: 'score', category: 'yacht' });
expect(decide(at([2, 3, 4, 5, 6], 3))).toEqual({ type: 'score', category: 'largeStraight' });
});
test('a hopeless last roll sacrifices a weak box, not the yacht', () => {
// Only 'ones' and 'yacht' are open.
const scores = Object.fromEntries(['twos', 'threes', 'fours', 'fives', 'sixes', 'choice', 'fourKind', 'fullHouse', 'smallStraight', 'largeStraight'].map((c) => [c, 10]));
expect(decide(at([2, 3, 4, 6, 6], 3, {}, scores))).toEqual({ type: 'score', category: 'ones' });
});
/** Solo game played by the bot only; returns its final total. */
function solo(options: YachtOptions, seed: number): number {
const rng = SeededRng.fromSeed(seedN(seed));
const chooser = SeededRng.fromSeed(seedN(seed + 1000));
let s = yacht.setup({ players: ['bot'], options, rng, now: 0 });
for (let i = 0; i < 200 && !yacht.result(s); i++) {
const a = decideBotAction(yacht, s, 'bot', { now: 1, random: () => chooser.next() })!;
s = yacht.apply(s, 'bot', a as never, { rng, now: 1 }).state;
}
return yacht.result(s)!.scores!.bot!;
}
test('averages a solid score over solo games', () => {
const scores = Array.from({ length: 10 }, (_, g) => solo(yacht.defaultOptions, g + 1));
// A random player averages well under 100; a careful beginner is comfortably above.
expect(scores.reduce((a, b) => a + b, 0) / scores.length).toBeGreaterThan(150);
});
for (const opts of [{ scoring: 'yahtzee' as const }, { scoring: 'yahtzee' as const, yahtzeeJoker: 'free' as const }, { fullHouseAllowsYacht: false }]) {
test(`option mode ${JSON.stringify(opts)}: games with a timing-out human finish`, () => {
const options = yacht.optionsSchema.parse(opts);
for (let g = 1; g <= 3; g++) {
const r = botPlayout(yacht, { players: ['human', 'bot:1', 'bot:2'], 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,114 @@
/**
* 요트 다이스 computer player. Every final hand is valued as "points minus the par of the category it uses up"
* (so a 0 lands in a weak box, and a high box is not wasted on a poor hand); holds are chosen by the exact
* expected value of that over the remaining rerolls (dice multisets, cached per decision).
*/
import type { BotStrategy } from '../bots/types';
import { answerRequests, best, pick, playable, typeOf } from '../bots/policy';
import { UPPER_BONUS_THRESHOLD, allowedCategories, faceOf, isUpper, scoreFor, type Category, type Sheet } from './scoring';
import type { YachtAction, YachtView } from './index';
/** Roughly what a box is worth on average: the cost of filling it now. */
const PAR: Record<'yacht51' | 'yahtzee', Partial<Record<Category, number>>> = {
yacht51: { choice: 22, fourKind: 12, fullHouse: 14, smallStraight: 10, largeStraight: 16, yacht: 14 },
yahtzee: { choice: 22, threeKind: 17, fourKind: 10, fullHouse: 17, smallStraight: 20, largeStraight: 22, yacht: 14 },
};
// A dice multiset is keyed by its face counts in base 6 (key = Σ count[f] · 6^(f-1)); keys of disjoint parts add up.
const POW = [0, 1, 6, 36, 216, 1296, 7776];
const KEYS = 6 ** 6;
const keyOf = (dice: number[]) => dice.reduce((k, d) => k + POW[d]!, 0);
const diceOf = (key: number) => {
const out: number[] = [];
for (let f = 1; f <= 6; f++) for (let c = Math.floor(key / POW[f]!) % 6; c > 0; c--) out.push(f);
return out;
};
/** All outcomes of rolling k dice as [multiset key, probability]. */
const OUTCOMES: [number, number][][] = [];
for (let k = 0; k <= 5; k++) {
const m = new Map<number, number>();
const rec = (left: number, key: number, p: number) => {
if (left === 0) return void m.set(key, (m.get(key) ?? 0) + p);
for (let f = 1; f <= 6; f++) rec(left - 1, key + POW[f]!, p / 6);
};
rec(k, 0, 1);
OUTCOMES.push([...m]);
}
export const yachtBot: BotStrategy<YachtView, YachtAction> = ({ me, view, legal, random }) => {
const req = answerRequests(legal);
if (req) return req;
const roll = legal.find((a) => a.type === 'roll');
if (!view.dice || view.rollsUsed === 0) return roll ?? pick(playable(legal), random);
const o = view.options;
const rules = { scoring: o.scoring, fullHouseAllowsYacht: o.fullHouseAllowsYacht, yahtzeeJoker: o.yahtzeeJoker };
const mine = view.sheets[me]!;
const sheet: Sheet = { scores: mine.scores, yahtzeeBonus: mine.yahtzeeBonus };
const par = PAR[o.scoring];
const upperNeed = UPPER_BONUS_THRESHOLD - mine.upper;
/** Value of writing `dice` into `c`. */
const catValue = (dice: number[], c: Category): number => {
const out = scoreFor(dice, c, sheet, rules);
let v = out.points + out.yahtzeeBonus;
if (isUpper(c)) {
const f = faceOf(c);
v -= 3 * f; // three of a face keeps the 63 bonus on track
if (upperNeed > 0 && out.points >= 3 * f) v += 6;
} else v -= par[c] ?? 0;
return v;
};
// V: best box value of a final hand; EV1/EV2: expected value with 1/2 rerolls left after holding a multiset.
const V = new Float64Array(KEYS).fill(NaN);
const val = (key: number): number => {
if (Number.isNaN(V[key]!)) {
const dice = diceOf(key);
V[key] = Math.max(...allowedCategories(dice, sheet, rules).map((c) => catValue(dice, c)));
}
return V[key]!;
};
const E1 = new Float64Array(KEYS).fill(NaN);
const ev1 = (held: number, n: number): number => {
if (Number.isNaN(E1[held]!)) E1[held] = OUTCOMES[5 - n]!.reduce((s, [k, p]) => s + p * val(held + k), 0);
return E1[held]!;
};
/** Best expected value reachable from a full hand with one reroll left (holding everything = stop). */
const B1 = new Map<number, number>();
const bestHold1 = (hand: number): number => {
if (!B1.has(hand)) {
const dice = diceOf(hand);
let top = -Infinity;
for (let m = 0; m < 32; m++) {
const kept = dice.filter((_, i) => (m >> i) & 1);
top = Math.max(top, ev1(keyOf(kept), kept.length));
}
B1.set(hand, top);
}
return B1.get(hand)!;
};
const ev2 = (held: number, n: number) => OUTCOMES[5 - n]!.reduce((s, [k, p]) => s + p * bestHold1(held + k), 0);
const dice = view.dice;
if (view.rollsLeft > 0) {
const hold2 = new Map<number, number>();
const expect = (kept: number[]) => {
const key = keyOf(kept);
if (kept.length === 5) return val(key);
if (view.rollsLeft === 1) return ev1(key, kept.length);
if (!hold2.has(key)) hold2.set(key, ev2(key, kept.length));
return hold2.get(key)!;
};
const masks = Array.from({ length: 32 }, (_, m) => [0, 1, 2, 3, 4].map((i) => ((m >> i) & 1) === 1));
const want = best(masks, (h) => expect(dice.filter((_, i) => h[i])) + random() * 1e-6, random);
if (!want.every(Boolean)) {
if (want.some((h, i) => h !== view.held[i])) return { type: 'hold', held: want };
if (roll) return roll;
}
}
const scores = legal.filter((a) => a.type === 'score') as Extract<YachtAction, { type: 'score' }>[];
if (!scores.length) return roll ?? pick(playable(legal), random);
return best(scores, (a) => catValue(dice, a.category), random);
};