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,65 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { KINDS, cockroachPoker as game, kindOf, type CockroachAction, type CockroachOptions, type CockroachState, type Kind } from './index';
/** Hands / fronts as kinds (ids assigned in order); `starter` offers. Same shape as the game's own tests. */
function rigged(hands: Record<string, Kind[]>, fronts: Record<string, Kind[]> = {}, starter?: string): CockroachState {
const players = Object.keys(hands);
const s = game.setup({ players, options: game.defaultOptions, rng: SeededRng.fromSeed(seedN(1)), now: 0 });
const next = Object.fromEntries(KINDS.map((k) => [k, 0])) as Record<Kind, number>;
const take = (k: Kind) => `${k}-${next[k]++}`;
for (const p of players) {
s.hands[p] = hands[p]!.map(take);
s.fronts[p] = (fronts[p] ?? []).map(take);
}
s.removed = [];
s.round = { no: 1, starter: starter ?? players[0]!, card: null, holder: null, lastPasser: null, claim: null, seen: [], peeked: false, claims: [] };
return s;
}
const act = (s: CockroachState, p: string, a: CockroachAction) => game.apply(s, p, a, { rng: SeededRng.fromSeed([7, 7, 7, 7]), now: 1 }).state;
const decide = (s: CockroachState, p: string) => decideBotAction(game, s, p, { now: 0, random: () => 0.3 }) as Record<string, unknown>;
describe('cockroach-poker bot', () => {
test('offers a kind to the player who already shows the most of it', () => {
const s = rigged({ A: ['rat', 'rat', 'fly'], B: ['bat'], C: ['toad'] }, { B: ['fly'], C: ['rat', 'rat'] });
const a = decide(s, 'A');
expect(a.type).toBe('offer');
expect(kindOf(a.cardId as string)).toBe('rat');
expect(a.to).toBe('C');
});
test('calls "false" when every copy of the claimed kind is accounted for', () => {
// 3 bats in my hand + 5 face-up: the passed card cannot be a bat.
let s = rigged({ A: ['fly', 'toad'], B: ['bat', 'bat', 'bat'], C: ['rat'] }, { A: ['bat', 'bat'], C: ['bat', 'bat', 'bat'] });
s = act(s, 'A', { type: 'offer', cardId: s.hands.A![0]!, to: 'B', claim: 'bat' });
expect(decide(s, 'B')).toEqual({ type: 'call', call: 'false' });
});
test('peeks and passes on when a wrong "false" would be deadly', () => {
let s = rigged({ A: ['fly', 'toad'], B: ['rat'], C: ['rat'], D: ['bat'] }, { B: ['spider', 'spider', 'spider'], C: ['fly', 'fly'] });
s = act(s, 'A', { type: 'offer', cardId: s.hands.A![0]!, to: 'B', claim: 'spider' });
expect(decide(s, 'B')).toEqual({ type: 'peek' });
s = act(s, 'B', { type: 'peek' });
// It saw a fly: C already shows two of them.
expect(decide(s, 'B')).toMatchObject({ type: 'pass', to: 'C' });
});
const modes: [string, number, Partial<CockroachOptions>][] = [
['2 players with the pass-back house rule', 2, { twoPlayerPass: true }],
['6 players, 3 of a kind, 8-kinds rule', 6, { loseCount: 3, eightKindsRule: true }],
];
for (const [name, n, opts] of modes) {
test(`bots finish a game: ${name}`, () => {
const options = game.optionsSchema.parse(opts);
const players = ['h', ...Array.from({ length: n - 1 }, (_, i) => `bot:${i + 1}`)];
for (let seed = 1; seed <= 3; seed++) {
const r = botPlayout(game as never, { players, options, seed: seedN(seed), isBot: (p) => p.startsWith('bot:') });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
}
});
}
});

View File

@@ -0,0 +1,69 @@
/**
* 바퀴벌레 포커 computer player. Offering: a kind I hold many of, to the player who already has the most of that
* kind face-up (and that I am not close to losing with myself), telling the truth about half the time. Receiving:
* estimates how likely the claim is from the copies still unaccounted for (8 per kind minus my hand and every
* face-up card); unsure or the claim would be deadly → peeks and passes on when allowed, otherwise calls.
* Uses only the view: own hand, public fronts, the claim, and the card itself once the bot has seen it.
*/
import type { BotStrategy } from '../bots/types';
import { best, pick, playable } from '../bots/policy';
import { KINDS, PER_KIND, type CockroachAction, type CockroachView, type Kind } from './index';
type Offer = Extract<CockroachAction, { type: 'offer' }>;
type Pass = Extract<CockroachAction, { type: 'pass' }>;
/** A claim for a card of `kind`: the truth about half the time, else a random other kind. */
function claimFor(kind: Kind, random: () => number): Kind {
if (random() < 0.5) return kind;
const others = KINDS.filter((k) => k !== kind);
return pick(others, random);
}
export const cockroachPokerBot: BotStrategy<CockroachView, CockroachAction> = ({ me, view, legal, random }) => {
const front = (p: string, k: Kind) => view.fronts[p]?.counts[k] ?? 0;
const myCount = (k: Kind) => view.myHand?.find((g) => g.kind === k)?.ids.length ?? 0;
const lose = view.loseCount;
// Hand a card to someone: kind × target, then pick a claim among the legal ones.
const offers = legal.filter((a): a is Offer => a.type === 'offer');
if (offers.length) {
const kindOfId = new Map((view.myHand ?? []).flatMap((g) => g.ids.map((id) => [id, g.kind] as const)));
const score = (a: Offer) => {
const k = kindOfId.get(a.cardId)!;
return front(a.to, k) * 2 - front(me, k) * (front(me, k) >= lose - 1 ? 10 : 2) + myCount(k) * 0.5 + random();
};
const top = best(offers, score, random);
const claim = claimFor(kindOfId.get(top.cardId)!, random);
return offers.find((a) => a.cardId === top.cardId && a.to === top.to && a.claim === claim) ?? top;
}
// Peeked: pass it on to whoever is most at risk with that kind.
const passes = legal.filter((a): a is Pass => a.type === 'pass');
if (passes.length) {
const kind = view.card && view.card.known ? view.card.kind : null;
if (!kind) return pick(passes, random);
const to = best([...new Set(passes.map((a) => a.to))], (p) => front(p, kind) + random() * 0.5, random);
const claim = claimFor(kind, random);
return passes.find((a) => a.to === to && a.claim === claim) ?? passes.find((a) => a.to === to)!;
}
const calls = legal.filter((a) => a.type === 'call');
const claim = view.round.claim;
if (!calls.length || !claim) return pick(playable(legal), random);
const call = (c: 'true' | 'false'): CockroachAction => ({ type: 'call', call: c });
// Already know the card (it came back to me): answer right.
if (view.card?.known) return call(view.card.kind === claim ? 'true' : 'false');
// Copies of the claimed kind not in my hand and not face-up anywhere.
const faceUp = (k: Kind) => view.order.reduce((x, p) => x + front(p, k), 0);
const left = PER_KIND - myCount(claim) - faceUp(claim);
if (left <= 0) return call('false');
const unknown = KINDS.length * PER_KIND - (view.myHand ?? []).reduce((x, g) => x + g.ids.length, 0) - view.order.reduce((x, p) => x + (view.fronts[p]?.total ?? 0), 0);
const pTrue = Math.min(0.9, Math.max(0.1, (0.5 * left) / Math.max(1, unknown / KINDS.length)));
// Calling "false" on a true claim gives me the claimed kind: deadly when I already have lose-1 of it.
const deadly = front(me, claim) >= lose - 1;
const canPeek = legal.some((a) => a.type === 'peek');
if (canPeek && (deadly || (Math.abs(pTrue - 0.5) < 0.15 && random() < 0.5))) return { type: 'peek' };
if (deadly) return call('true');
return call(pTrue + (random() - 0.5) * 0.3 > 0.5 ? 'true' : 'false');
};