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,80 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { classicDeck, oneCard, unoDeck, type Card, type OneCardOptions, type OneCardState } from './index';
const ALL: Card[] = [...classicDeck(2), ...unoDeck()];
const card = (id: string): Card => ALL.find((x) => x.id === id)!;
function make(opts: Partial<OneCardOptions> = {}, players = ['A', 'B', 'C']): OneCardState {
return oneCard.setup({ players, options: oneCard.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
}
function rig(s: OneCardState, hands: Record<string, string[]>, discard: string[], pending = 0): OneCardState {
for (const p of s.seats) s.hands[p] = (hands[p] ?? []).map(card);
s.discard = discard.map(card);
s.current = s.seats[0]!;
s.phase = { kind: 'turn' };
s.pendingAttack = pending;
s.declaredSuit = null;
s.declaredColor = null;
s.oneCardWindow = null;
const used = new Set([...Object.values(hands).flat(), ...discard]);
s.drawPile = (s.mode === 'classic' ? classicDeck(s.decks) : unoDeck()).filter((c) => !used.has(c.id));
return s;
}
const decide = (s: OneCardState, p = 'A') => decideBotAction(oneCard, s, p, { now: 0, random: () => 0.5 }) as Record<string, unknown>;
describe('one-card bot', () => {
test('counters an attack instead of drawing', () => {
const s = rig(make(), { A: ['S2', 'H9', 'D5'], B: ['C4', 'C5'], C: ['D9', 'D10'] }, ['H5', 'H2'], 2);
expect(decide(s)).toEqual({ type: 'play', cardIds: ['S2'] });
});
test('keeps the joker while a plain card fits', () => {
const s = rig(make(), { A: ['H3', 'H9', 'JB'], B: ['C4', 'C5', 'C6', 'C8'], C: ['D9', 'D10'] }, ['H5']);
expect(decide(s)).toEqual({ type: 'play', cardIds: ['H9'] });
});
test('declares one-card, getting rid of a joker that may not be the last card', () => {
const s = rig(make(), { A: ['H9', 'JB'], B: ['C4', 'C5'], C: ['D9', 'D10'] }, ['H5']);
expect(decide(s)).toEqual({ type: 'play', cardIds: ['JB'], declareOneCard: true });
});
test('a 7 changes to the suit it holds most of', () => {
const s = rig(make(), { A: ['H7', 'C3', 'C9', 'S4'], B: ['C4', 'C5'], C: ['D9', 'D10'] }, ['H5']);
// H7 is the only card that fits.
expect(decide(s)).toMatchObject({ type: 'play', cardIds: ['H7'], chooseSuit: 'C' });
});
test("catches another player's missed one-card call", () => {
let s = rig(make(), { A: ['H9', 'C3'], B: ['C4', 'C5', 'S6'], C: ['D9', 'D10'] }, ['H5']);
s = oneCard.apply(s, 'A', { type: 'play', cardIds: ['H9'] }, { rng: SeededRng.fromSeed(seedN(2)), now: 1 }).state;
expect(s.oneCardWindow).toMatchObject({ player: 'A', declared: false });
expect(decide(s, 'C')).toEqual({ type: 'declareOneCard' });
});
test('colour cards: a wild picks the colour it holds most of', () => {
const s = rig(make({ mode: 'uno-style' }), { A: ['W1', 'B3a', 'B5a', 'G1a'], B: ['R1a', 'R2a'], C: ['Y1a', 'Y2a'] }, ['R9a']);
expect(decide(s)).toMatchObject({ type: 'play', cardIds: ['W1'], chooseColor: 'B' });
});
const modes: [string, Partial<OneCardOptions>][] = [
['classic multi-play, special last cards', { multiPlay: true, lastCardRule: 'special', kEffect: 'skip-two', afterJoker: 'any' }],
['colour cards with stacking and +4 challenge', { mode: 'uno-style', unoStacking: true, unoWild4Rule: 'challenge' }],
['colour cards to 200 points', { mode: 'uno-style', unoTargetScore: 200, handSize: 5 }],
['classic until the last player, two decks', { endCondition: 'last-standing', deckCount: 2, playAfterDraw: 'on' }],
];
for (const [name, opts] of modes) {
test(`bots finish a game: ${name}`, () => {
const options = oneCard.optionsSchema.parse(opts);
for (let seed = 1; seed <= 2; seed++) {
const r = botPlayout(oneCard 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,105 @@
/**
* 원카드 / 색깔 카드 computer player: always declare (and catch others' missed) one-card, counter attacks when it
* can, otherwise play a matching card while keeping jokers / 7s / wilds for later; attack when the next player is
* close to going out; a changed suit or colour is the one it holds most of.
*/
import type { BotStrategy } from '../bots/types';
import { best, pick, playable, typeOf } from '../bots/policy';
import { COLORS, SUITS, colorOf, isStd, type Card, type Color, type Suit } from './cards';
import { attackOf, forbiddenAsLast } from './rules';
import type { OneCardAction, OneCardView, PlayAction } from './types';
/** Seat that plays after me (skipping players that are out). */
function nextSeat(view: OneCardView): OneCardView['seats'][number] | undefined {
const n = view.seats.length;
const i = view.seats.findIndex((s) => s.id === view.me);
for (let k = 1; k < n; k++) {
const s = view.seats[(((i + k * view.direction) % n) + n) % n]!;
if (s.status === 'playing') return s;
}
return undefined;
}
/** Most common suit / colour among `cards` (random among ties or when there is none). */
function majority<K extends string>(keys: K[], all: K[], random: () => number): K {
const count = new Map<K, number>();
for (const k of keys) count.set(k, (count.get(k) ?? 0) + 1);
return best(all, (k) => count.get(k) ?? 0, random);
}
export const oneCardBot: BotStrategy<OneCardView, OneCardAction> = ({ view, legal, random }) => {
const types = new Set(legal.map(typeOf));
if (types.has('ready')) return { type: 'ready' };
// My own one-card call, or catching someone who forgot to call it.
if (types.has('declareOneCard')) return { type: 'declareOneCard' };
const hand = view.my?.hand ?? [];
const byId = new Map(hand.map((c) => [c.id, c]));
const plays = (legal.filter((a) => a.type === 'play') as PlayAction[]).filter((a) => a.declareOneCard || hand.length - a.cardIds.length !== 1);
const o = view.options;
const uno = view.mode === 'uno-style';
if (types.has('challengeWild4')) {
// Stack a +4 if allowed; otherwise challenge now and then (it is a guess: costs 2 more cards when wrong).
const stack = plays.find((a) => byId.get(a.cardIds[0]!)?.kind === 'wild4');
if (stack) return withChoice(stack, hand, random);
return { type: random() < 0.25 ? 'challengeWild4' : 'acceptWild4' };
}
if (!plays.length) {
if (types.has('pass')) return { type: 'pass' };
if (types.has('draw')) return { type: 'draw' };
return pick(playable(legal), random);
}
const next = nextSeat(view);
const nextNearOut = !!next && next.cards <= 2;
const score = (a: PlayAction): number => {
const cards = a.cardIds.map((id) => byId.get(id)!);
const first = cards[0]!;
const rest = hand.filter((c) => !a.cardIds.includes(c.id));
let v = cards.length * 2 + random() * 0.5;
if (view.pendingAttack > 0) return v + 10; // countering / blocking beats drawing a pile of cards
if (!uno) {
const atk = cards.reduce((x, c) => x + attackOf(o, c), 0);
if (first.kind === 'joker') v -= nextNearOut ? 0 : 4;
else if (atk > 0) v += nextNearOut ? 3 : -1;
if (isStd(first)) {
if (first.rank === 7) v -= 2; // the suit changer is a lifeline: keep it
if (first.rank === 13 && rest.length > 0) v += 1; // K: play again
if (first.rank === 11 || first.rank === 12) v += nextNearOut ? 2 : 0.5;
v += (first.rank >= 11 ? 10 : first.rank) / 20; // dump points first
}
// Don't leave myself only cards that may not finish the hand.
if (rest.length && rest.every((c) => forbiddenAsLast(o, c))) v -= 6;
} else {
if (first.kind === 'wild') v -= 3;
if (first.kind === 'wild4') {
v -= 4;
// Bluffing a +4 while holding the colour risks a challenge.
if (view.currentColor && rest.some((c) => colorOf(c) === view.currentColor)) v -= 3;
if (nextNearOut) v += 3;
}
if (first.kind === 'skip' || first.kind === 'reverse' || first.kind === 'draw2') v += nextNearOut ? 3 : 0.5;
if (first.kind === 'num') v += first.value / 20;
// Keep my colour going: prefer cards of the colour I hold most of.
const c = colorOf(first);
if (c) v += rest.filter((x) => colorOf(x) === c).length * 0.3;
}
return v;
};
return withChoice(best(plays, score, random), hand, random);
};
/** Fixes the suit / colour of a 7 or a wild to the one the rest of the hand holds most of. */
function withChoice(a: PlayAction, hand: Card[], random: () => number): PlayAction {
const rest = hand.filter((c) => !a.cardIds.includes(c.id));
if (a.chooseSuit) {
const suits = rest.filter(isStd).map((c) => c.suit);
return { ...a, chooseSuit: majority<Suit>(suits, SUITS, random) };
}
if (a.chooseColor) {
const colors = rest.map(colorOf).filter((c): c is Color => !!c);
return { ...a, chooseColor: majority<Color>(colors, COLORS, random) };
}
return a;
}