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,62 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { fullDeck, ninetyNine, type NNCard, type NNOptions, type NinetyNineState } from './index';
function make(opts: Partial<NNOptions> = {}): NinetyNineState {
return ninetyNine.setup({ players: ['A', 'B', 'C'], options: ninetyNine.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
}
/** Gives A the cards with these face labels and sets the total; A to move. */
function rig(s: NinetyNineState, labels: string[], total: number): NinetyNineState {
const pool = fullDeck(s);
const take = (label: string): NNCard => pool.splice(pool.findIndex((c) => c.face.label === label), 1)[0]!;
s.hands.A = labels.map(take);
s.hands.B = ['1', '2', '3'].map(take);
s.hands.C = ['1', '2', '3'].map(take);
s.total = total;
s.current = 'A';
s.drawPile = pool;
s.discard = [];
return s;
}
const decide = (s: NinetyNineState) => decideBotAction(ninetyNine, s, 'A', { now: 0, random: () => 0.5 }) as Record<string, unknown>;
const labelOf = (s: NinetyNineState, a: Record<string, unknown>) => s.hands.A!.find((c) => c.id === a.cardId)!.face.label;
describe('ninety-nine bot', () => {
test('plays a big number while there is room and keeps the special cards', () => {
const s = rig(make(), ['2', '8', '조커', '0'], 30);
expect(labelOf(s, decide(s))).toBe('8');
});
test('near 99 it brings the total down with ± instead of spending its 0 card', () => {
const s = rig(make(), ['8', '±10', '0'], 95);
const a = decide(s);
expect(labelOf(s, a)).toBe('±10');
expect(a.sign).toBe('-');
});
test('trump cards: holds with a 9 before spending its K', () => {
const s = rig(make({ mode: 'classic' }), ['K', '9', 'Q'], 92);
// Q (+10) does not fit; 9 keeps the total, K makes it 99: the cheaper 9 goes first.
expect(labelOf(s, decide(s))).toBe('9');
});
const modes: [string, Partial<NNOptions>][] = [
['trump cards with lives', { mode: 'classic', lives: 'auto' }],
['dedicated cards, reset after a loss, 0-99 joker', { afterElimination: 'reset', jokerRange: '0-99', floorAtZero: 'clamp' }],
['no refill, 5 cards, lives on the board', { refill: false, handSize: 5, lives: 2, onTheBoard: true }],
];
for (const [name, opts] of modes) {
test(`bots finish a game: ${name}`, () => {
const options = ninetyNine.optionsSchema.parse(opts);
for (let seed = 1; seed <= 2; seed++) {
const r = botPlayout(ninetyNine as never, { players: ['h', 'bot:1', 'bot:2', 'bot:3'], options, seed: seedN(seed), isBot: (p) => p.startsWith('bot:') });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
}
});
}
});

View File

@@ -0,0 +1,51 @@
/**
* 구십구 computer player: plays plain number cards while they still fit (biggest first, they go dead as the total
* climbs) and saves the "safe" cards — 0/reverse, 9/hold, −10, ±9/±10, K, joker — for when the total is high.
* A forced safe card picks the cheapest one; ± goes down near 99, and K / the joker push the next player to 99 only
* when I still hold another safe card myself.
*/
import type { BotStrategy } from '../bots/types';
import { best, pick, playable } from '../bots/policy';
import type { CardKind, HandCardView, NinetyNineView, NNAction, PlayAction } from './types';
/** How much a card is worth keeping: it can be played on (almost) any total. */
const KEEP: Record<CardKind, number> = { add: 0, ace: 0, reverse: 4, hold: 4, minus: 5, plusMinus: 5, to99: 6, joker: 8 };
const isSafe = (c: HandCardView) => KEEP[c.kind] > 0;
/** Total after `a` (null if it cannot be worked out from the view). */
function totalAfter(a: PlayAction, c: HandCardView): number | null {
if (c.kind === 'joker') return a.jokerValue ?? null;
const ch = c.choices.find((x) => x.legal && x.sign === a.sign && x.aceValue === a.aceValue);
return ch ? ch.total : null;
}
/** Smallest increase a card can make (plain numbers / ace), or null for safe cards. */
function minRaise(c: HandCardView, total: number): number | null {
if (isSafe(c)) return null;
return Math.min(...c.choices.map((x) => x.total - total));
}
export const ninetyNineBot: BotStrategy<NinetyNineView, NNAction> = ({ view, legal, random }) => {
const hand = view.my?.hand ?? [];
const plays = legal.filter((a): a is PlayAction => a.type === 'play');
if (!plays.length || !hand.length) return pick(playable(legal), random);
const byId = new Map(hand.map((c) => [c.id, c]));
const score = (a: PlayAction): number => {
const c = byId.get(a.cardId);
if (!c) return -Infinity;
const after = totalAfter(a, c);
if (after === null) return -Infinity;
const rest = hand.filter((x) => x.id !== c.id);
const keepsSafe = rest.some(isSafe);
let v = -KEEP[c.kind] + random() * 0.2;
if (!isSafe(c)) v += (after - view.total) * 0.3; // dump big numbers while there is room
if (c.kind === 'plusMinus') v += after < view.total ? (view.total >= 80 ? 2 : -1) : view.total >= 80 ? -2 : 1;
if (c.kind === 'joker' || c.kind === 'to99') v += after >= 99 ? (keepsSafe ? 1.5 : -2) : after <= 70 ? 1 : 0;
// Will something in my hand still fit next turn (a safe card, or a number with a little room)?
const room = rest.some((x) => isSafe(x) || (minRaise(x, view.total) ?? 99) + after <= 95);
if (!room) v -= 6;
return v;
};
return best(plays, score, random);
};