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:
83
packages/games/src/rummikub/bot.test.ts
Normal file
83
packages/games/src/rummikub/bot.test.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN, type PlayerId } from '@bg/engine';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { botPlayout } from '../bots/playout';
|
||||
import { ALL_TILE_IDS, normalizeSet, rummikub, type RummikubAction, type RummikubOptions, type RummikubState } from './index';
|
||||
|
||||
const ME = 'bot:1:x';
|
||||
const OTHER = 'human0';
|
||||
|
||||
function rig(o: { rack: string[]; table?: string[][]; melded?: boolean; opts?: Partial<RummikubOptions> }): RummikubState {
|
||||
const options = rummikub.optionsSchema.parse(o.opts ?? {});
|
||||
const s = rummikub.setup({ players: [ME, OTHER], options, rng: SeededRng.fromSeed(seedN(1)), now: 0 });
|
||||
const table = o.table ?? [];
|
||||
const otherRack = ALL_TILE_IDS.filter((id) => !o.rack.includes(id) && !table.flat().includes(id)).slice(-14);
|
||||
const used = new Set([...o.rack, ...table.flat(), ...otherRack]);
|
||||
s.racks = { [ME]: [...o.rack], [OTHER]: otherRack };
|
||||
s.table = table.map((ids, i) => {
|
||||
const n = normalizeSet({ tileIds: ids })!;
|
||||
return { id: `s${i + 1}`, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs };
|
||||
});
|
||||
s.pool = ALL_TILE_IDS.filter((id) => !used.has(id));
|
||||
s.current = ME;
|
||||
s.hasMelded = { [ME]: !!o.melded, [OTHER]: true };
|
||||
s.draft = { sets: s.table.map((t) => ({ tileIds: [...t.tileIds], as: t.kind })), history: [], edits: 0 };
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Lets the bot finish its turn (draft, then commit); returns the actions it took. */
|
||||
function botTurn(s: RummikubState): { state: RummikubState; acts: RummikubAction[] } {
|
||||
const acts: RummikubAction[] = [];
|
||||
let now = 1000;
|
||||
while (s.current === ME && s.phase === 'playing' && acts.length < 5) {
|
||||
const a = decideBotAction(rummikub, s, ME, { now, random: () => 0.5 }) as RummikubAction;
|
||||
acts.push(a);
|
||||
s = rummikub.apply(s, ME, a, { rng: SeededRng.fromSeed(seedN(2)), now: (now += 1000) }).state;
|
||||
}
|
||||
return { state: s, acts };
|
||||
}
|
||||
|
||||
describe('rummikub bot', () => {
|
||||
test('makes the 30-point first meld from its rack and commits it in the same turn', () => {
|
||||
const s = rig({ rack: ['R10a', 'R11a', 'R12a', 'K3a', 'B3a', 'O3a', 'B7a', 'K9b'] });
|
||||
const { state, acts } = botTurn(s);
|
||||
expect(acts.map((a) => a.type)).toEqual(['setDraft', 'commit']);
|
||||
expect(state.hasMelded[ME]).toBe(true);
|
||||
expect(state.racks[ME]!.sort()).toEqual(['B7a', 'K9b']);
|
||||
});
|
||||
|
||||
test('draws when the first meld would be under 30 points', () => {
|
||||
const s = rig({ rack: ['R1a', 'R2a', 'R3a', 'K2a', 'B2a', 'O2a', 'B9a'] });
|
||||
const { state, acts } = botTurn(s);
|
||||
expect(acts.map((a) => a.type)).toEqual(['draw']);
|
||||
expect(state.racks[ME]).toHaveLength(8);
|
||||
expect(state.table).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('after melding it lays tiles off on table sets (extending runs repeatedly)', () => {
|
||||
const s = rig({ rack: ['B8a', 'B9a', 'O5a', 'K1a'], table: [['B5a', 'B6a', 'B7a'], ['R5a', 'K5a', 'B5b']], melded: true });
|
||||
const { state, acts } = botTurn(s);
|
||||
expect(acts.map((a) => a.type)).toEqual(['setDraft', 'commit']);
|
||||
expect(state.racks[ME]).toEqual(['K1a']);
|
||||
expect(state.table.map((t) => t.tileIds.length).sort()).toEqual([4, 5]);
|
||||
});
|
||||
|
||||
test('a half-built draft (left from a timeout race) is dropped by drawing, never committed', () => {
|
||||
let s = rig({ rack: ['R1a', 'B9a', 'K4a'], melded: true });
|
||||
s = rummikub.apply(s, ME, { type: 'setDraft', sets: [{ tileIds: ['R1a'] }] }, { rng: SeededRng.fromSeed(seedN(2)), now: 500 }).state;
|
||||
const { state, acts } = botTurn(s);
|
||||
expect(acts.map((a) => a.type)).toEqual(['draw']);
|
||||
expect(state.racks[ME]).toHaveLength(4);
|
||||
});
|
||||
|
||||
test('bot-only games finish under several option sets', () => {
|
||||
const isBot = (p: PlayerId) => p.startsWith('bot:');
|
||||
const optionSets: Partial<RummikubOptions>[] = [{}, { initialMeldPoints: 0 }, { initialMeldPoints: 50, invalidCommitPenalty: 'penalty3' }, { gamesPerMatch: '2' }];
|
||||
for (const [i, o] of optionSets.entries()) {
|
||||
const options = rummikub.optionsSchema.parse(o);
|
||||
const r = botPlayout(rummikub, { players: ['bot:0:x', 'bot:1:x', 'bot:2:x'], options, seed: seedN(30 + i), isBot, maxSteps: 30_000 });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
62
packages/games/src/rummikub/bot.ts
Normal file
62
packages/games/src/rummikub/bot.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 숫자 타일 computer player. A turn is two decisions: first one `setDraft` with the whole plan (rack-only sets, then
|
||||
* single tiles laid off on table / new sets), then `commit` once the view says the draft is valid. If the draft is
|
||||
* not valid (should not happen) it draws, which also throws the draft away — it never leaves a half-built draft.
|
||||
* Table sets are never rearranged beyond adding tiles to their ends.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests } from '../bots/policy';
|
||||
import { extendSet, isJoker, pickDisjoint, type JokerAs } from './rules';
|
||||
import type { RummikubAction, RummikubView } from './index';
|
||||
|
||||
type Plan = { tileIds: string[]; kind: 'run' | 'group'; jokerAs: Record<string, JokerAs> };
|
||||
|
||||
/** Lays rack tiles off on the given sets in place (repeating, so 5-6-7 + 8 + 9 works). */
|
||||
function layOff(sets: Plan[], rack: string[], keepJokers: boolean): void {
|
||||
const used = new Set<string>();
|
||||
for (let changed = true; changed; ) {
|
||||
changed = false;
|
||||
for (const id of rack) {
|
||||
if (used.has(id) || (keepJokers && isJoker(id))) continue;
|
||||
for (let i = 0; i < sets.length; i++) {
|
||||
const ext = extendSet(sets[i]!, id);
|
||||
if (!ext) continue;
|
||||
sets[i] = ext;
|
||||
used.add(id);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const rummikubBot: BotStrategy<RummikubView, RummikubAction> = ({ view, legal }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
if (legal.some((a) => a.type === 'ready')) return { type: 'ready' };
|
||||
const my = view.my!;
|
||||
const endTurn: RummikubAction = legal.find((a) => a.type === 'pass') ?? { type: 'draw' };
|
||||
// Second step of a turn: the plan is on the table — commit it, or give up cleanly (draw resets the draft).
|
||||
if (my.changed) return my.check?.ok ? { type: 'commit', turn: view.turnNo } : endTurn;
|
||||
|
||||
const rack = my.rack;
|
||||
const table: Plan[] = view.table.map((t) => ({ tileIds: [...t.tileIds], kind: t.kind, jokerAs: t.jokerAs }));
|
||||
const disjoint = pickDisjoint(rack);
|
||||
const fresh = disjoint.sets.map((n): Plan => ({ tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs }));
|
||||
const rest = rack.filter((id) => !fresh.some((s) => s.tileIds.includes(id)));
|
||||
// A lone joker is only laid off near the end (it's the most flexible tile, but costs 30 if still on the rack).
|
||||
const keepJokers = rack.length > 4;
|
||||
let sets: Plan[];
|
||||
if (!my.melded) {
|
||||
// First meld: every disjoint rack set at once, if together they reach the minimum. Table sets stay untouched.
|
||||
if (!fresh.length || disjoint.points < view.options.initialMeldPoints) return endTurn;
|
||||
layOff(fresh, rest, keepJokers);
|
||||
sets = [...table, ...fresh];
|
||||
} else {
|
||||
sets = [...table, ...fresh];
|
||||
layOff(sets, rest, keepJokers);
|
||||
}
|
||||
const before = new Set(view.table.flatMap((t) => t.tileIds));
|
||||
if (!sets.some((s) => s.tileIds.some((id) => !before.has(id)))) return endTurn;
|
||||
return { type: 'setDraft', sets: sets.map((s) => ({ tileIds: s.tileIds, as: s.kind })), turn: view.turnNo };
|
||||
};
|
||||
Reference in New Issue
Block a user