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,98 @@
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 { allTileIds, davinci, tileOf, type DavinciOptions, type DavinciState } from './index';
/** A game in the guess phase: rows as written (`!` = revealed), A to move, pool = every other tile. */
function rigged(rows: Record<string, string[]>, opts: Partial<DavinciOptions> = {}): DavinciState {
const players = Object.keys(rows);
const s = davinci.setup({ players, options: davinci.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
const used = new Set<string>();
for (const p of players) {
s.rows[p] = rows[p]!.map((x) => {
const id = x.replace('!', '');
used.add(id);
return { id, revealed: x.endsWith('!'), wrong: [] };
});
}
const rest = allTileIds(s.options.jokers).filter((id) => !used.has(id));
s.pool = { black: rest.filter((id) => tileOf(id).color === 'black'), white: rest.filter((id) => tileOf(id).color === 'white') };
s.jokerReserve = [];
s.phase = { kind: 'guess' };
s.current = players[0]!;
return s;
}
const decide = (s: DavinciState, p: string, seed = 1) => {
const r = SeededRng.fromSeed(seedN(seed));
return decideBotAction(davinci, s, p, { now: 1, random: () => r.next() });
};
describe('davinci-code bot', () => {
test('guesses a tile pinned by the row order (w? < b? < b2 → w0, b1)', () => {
const s = rigged({ A: ['b5', 'w6', 'b8', 'w10'], B: ['w0', 'b1', 'b2!', 'w9'] });
for (let seed = 1; seed <= 5; seed++) {
const a = decide(s, 'A', seed) as { type: string; target: string; index: number; value: number };
expect(a.type).toBe('guess');
expect(a.target).toBe('B');
expect(['0:0', '1:1']).toContain(`${a.index}:${a.value}`);
}
});
test('keeps guessing after a hit only when the next tile is certain', () => {
const sure = rigged({ A: ['b5', 'w6', 'b8', 'w10'], B: ['w0', 'b1', 'b2!', 'w9'] });
sure.phase = { kind: 'afterCorrect' };
expect(decide(sure, 'A')).toEqual({ type: 'continue' });
const vague = rigged({ A: ['b5', 'w6', 'b8', 'w10'], B: ['w1', 'b3', 'b7', 'w9'] });
vague.phase = { kind: 'afterCorrect' };
vague.pending = 'b11';
expect(decide(vague, 'A')).toEqual({ type: 'stop' });
});
test('splits the start tiles evenly; reveals its most exposed own tile', () => {
const s = davinci.setup({ players: ['A', 'B'], options: davinci.defaultOptions, rng: SeededRng.fromSeed(seedN(3)), now: 0 });
expect(decide(s, 'A')).toEqual({ type: 'chooseStart', black: 2, white: 2 });
// b3 sits between the revealed b2 and b4: everybody can already name it.
const r = rigged({ A: ['b0!', 'b1!', 'b2!', 'b3', 'b4!', 'w9', 'w10'], B: ['w0', 'w5'] });
r.phase = { kind: 'revealOwn' };
r.pool = { black: [], white: [] };
expect(decide(r, 'A')).toEqual({ type: 'revealOwn', index: 3 });
});
test('option modes: games with jokers / random colours / no penalty finish without bot timeouts', () => {
const modes: Partial<DavinciOptions>[] = [{ jokers: true }, { chooseColors: false, emptyPoolPenalty: 'none' }, { jokers: true, tieOrder: 'white-left', startTiles: 5 }];
for (const [i, m] of modes.entries()) {
for (const n of [2, 4]) {
const r = botPlayout(davinci as never, {
players: Array.from({ length: n }, (_, k) => `bot:${k}`),
options: davinci.optionsSchema.parse(m),
seed: seedN(10 + i * 7 + n),
isBot: () => true,
});
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
}
}
});
test('beats a random player clearly', () => {
let wins = 0;
for (let g = 0; g < 20; g++) {
const rng = SeededRng.fromSeed(seedN(200 + g));
const ch = SeededRng.fromSeed(seedN(900 + g));
const random = () => ch.next();
let s = davinci.setup({ players: ['bot', 'rnd'], options: davinci.defaultOptions, rng, now: 0 });
for (let step = 0; step < 2000 && !davinci.result(s); step++) {
const p = davinci.activePlayers(s)[0]!;
const a =
p === 'bot'
? decideBotAction(davinci, s, p, { now: 0, random })
: randomPolicy({ me: p, view: davinci.view(s, p), legal: davinci.legalActions!(s, p), random });
s = davinci.apply(s, p, a as never, { rng, now: 0 }).state;
}
if (davinci.result(s)?.ranking[0]?.[0] === 'bot') wins++;
}
expect(wins).toBeGreaterThanOrEqual(17);
});
});

View File

@@ -0,0 +1,106 @@
/**
* 다빈치 코드 computer player: deduces candidate values for every hidden opponent tile from its own view
* (own tiles, revealed tiles, colours, wrong guesses and the sorted order of each row), guesses the most
* certain tile and keeps guessing after a hit only while it is confident.
*/
import type { PlayerId } from '@bg/engine';
import type { BotStrategy } from '../bots/types';
import { best, pick, randomPolicy } from '../bots/policy';
import { candidatesFor, sortKey, type DavinciAction, type DavinciView, type TileValue } from './index';
type Cands = Record<PlayerId, (TileValue[] | null)[]>;
/** Candidates per hidden tile of `players` (null for known tiles), refined by row order and uniqueness. */
export function deduce(v: DavinciView, players: PlayerId[]): Cands {
const out: Cands = {};
for (const p of players) out[p] = v.rows[p]!.map((t, i) => (t.n !== undefined ? null : candidatesFor(v.rows, v.pending, p, i, v.options)));
for (let round = 0; round < 3; round++) {
// Numbered tiles of a row are strictly increasing. A hidden tile that may be a joker breaks that chain,
// so only rows without such a tile are tightened (keeps the deduction sound).
for (const p of players) {
const row = v.rows[p]!;
const c = out[p]!;
if (c.some((x) => x?.includes('joker'))) continue;
const keys = row.map((t, i) => (t.n === 'joker' ? null : (c[i] ?? [t.n!]).map((n) => sortKey(t.color, n as number, v.options.tieOrder))));
let prev = -Infinity;
for (let i = 0; i < row.length; i++) {
const k = keys[i];
if (!k) continue;
keys[i] = k.filter((x) => x > prev);
prev = Math.min(...keys[i]!);
}
let next = Infinity;
for (let i = row.length - 1; i >= 0; i--) {
const k = keys[i];
if (!k) continue;
keys[i] = k.filter((x) => x < next);
next = Math.max(...keys[i]!);
}
row.forEach((t, i) => {
if (c[i]) c[i] = c[i]!.filter((n) => keys[i]!.includes(sortKey(t.color, n as number, v.options.tieOrder)));
});
}
// A tile pinned to one value can't be that value anywhere else.
const pinned = new Set<string>();
for (const p of players) out[p]!.forEach((c, i) => c?.length === 1 && pinned.add(`${v.rows[p]![i]!.color}${c[0]}`));
for (const p of players) {
out[p]!.forEach((c, i) => {
if (c && c.length > 1) out[p]![i] = c.filter((n) => !pinned.has(`${v.rows[p]![i]!.color}${n}`));
});
}
}
return out;
}
/** Jokers are rare: count only numbers unless a joker is the sole option. */
const spread = (c: TileValue[]) => c.filter((n) => n !== 'joker').length || c.length;
/** The most certain hidden tile of a living opponent (fewest candidates; ties: opponent closest to elimination). */
function bestGuess(v: DavinciView, me: PlayerId, random: () => number): { target: PlayerId; index: number; cands: TileValue[] } | null {
const opps = v.seats.filter((p) => p !== me && v.alive[p]);
const all = deduce(v, opps);
const spots: { target: PlayerId; index: number; cands: TileValue[]; hidden: number }[] = [];
for (const p of opps) {
const hidden = v.rows[p]!.filter((t) => !t.revealed).length;
all[p]!.forEach((c, index) => c && c.length && !v.rows[p]![index]!.revealed && spots.push({ target: p, index, cands: c, hidden }));
}
if (!spots.length) return null;
return best(spots, (s) => -spread(s.cands) * 100 - s.hidden, random);
}
export const davinciBot: BotStrategy<DavinciView, DavinciAction> = (input) => {
const { me, view: v, legal, random } = input;
switch (v.phase) {
case 'chooseStart': {
// Split the start tiles as evenly as allowed.
const opts = legal.filter((a): a is Extract<DavinciAction, { type: 'chooseStart' }> => a.type === 'chooseStart');
return best(opts, (a) => -Math.abs(a.black - a.white), random);
}
case 'guess': {
const g = bestGuess(v, me, random);
if (!g) break;
const nums = g.cands.filter((n) => n !== 'joker');
return { type: 'guess', target: g.target, index: g.index, value: pick(nums.length ? nums : g.cands, random) };
}
case 'afterCorrect': {
const g = bestGuess(v, me, random);
if (!g) return { type: 'stop' };
// A miss costs the drawn tile (or one of mine); free when neither applies.
const free = !v.pending && v.options.emptyPoolPenalty === 'none';
const n = spread(g.cands);
const go = free || n === 1 || (n === 2 && random() < 0.4);
return { type: go ? 'continue' : 'stop' };
}
case 'revealOwn': {
// Give away the tile the others could already pin down best from public information.
const masked = structuredClone(v.rows);
for (const t of masked[me]!) if (!t.revealed) delete t.n;
const opts = legal.filter((a): a is Extract<DavinciAction, { type: 'revealOwn' }> => a.type === 'revealOwn');
return best(opts, (a) => -candidatesFor(masked, null, me, a.index, v.options).length, random);
}
default:
// draw (colour choice barely matters) and placeJoker (anywhere keeps the others guessing).
break;
}
return randomPolicy(input);
};