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:
79
packages/games/src/dalmuti/bot.test.ts
Normal file
79
packages/games/src/dalmuti/bot.test.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN } from '@bg/engine';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { botPlayout } from '../bots/playout';
|
||||
import { FULL_DECK, dalmuti, type DCard, type DalmutiOptions, type DalmutiState } from './index';
|
||||
|
||||
const BY_ID = new Map(FULL_DECK.map((c) => [c.id, c]));
|
||||
const C = (n: number, k = 1) => `c${n}-${k}`;
|
||||
const P = ['A', 'B', 'C', 'D', 'E'];
|
||||
|
||||
function make(opts: Partial<DalmutiOptions> = {}): DalmutiState {
|
||||
return dalmuti.setup({ players: P, options: dalmuti.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
|
||||
}
|
||||
|
||||
/** Seats A..E in order, gives A `hand` (others a few cards) and starts a trick, optionally under B's set. */
|
||||
function rig(hand: string[], top?: string[]): DalmutiState {
|
||||
const s = make();
|
||||
s.order = [...P];
|
||||
const cards = (ids: string[]) => ids.map((id) => BY_ID.get(id)! as DCard);
|
||||
s.hands = { A: cards(hand), B: cards([C(12, 1)]), C: cards([C(12, 2)]), D: cards([C(12, 3)]), E: cards([C(12, 4)]) };
|
||||
s.phase = { kind: 'playing' };
|
||||
s.current = 'A';
|
||||
s.trick = { leader: top ? 'B' : 'A', top: null, passesSinceTop: [], lockedOut: [], pile: [] };
|
||||
if (top) {
|
||||
const n = BY_ID.get(top[0]!)!.n;
|
||||
s.trick.top = { cardIds: top, count: top.length, rank: n, by: 'B' };
|
||||
s.trick.pile = [s.trick.top];
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
const decide = (s: DalmutiState) => decideBotAction(dalmuti, s, 'A', { now: 0, random: () => 0.5 }) as { type: string; cardIds?: string[]; declareRevolution?: boolean };
|
||||
|
||||
describe('dalmuti bot', () => {
|
||||
test('leads its weakest number as a whole set', () => {
|
||||
const s = rig([C(3), C(7, 1), C(7, 2), C(11, 1), C(11, 2), C(11, 3)]);
|
||||
expect(decide(s)).toEqual({ type: 'play', cardIds: [C(11, 1), C(11, 2), C(11, 3)] });
|
||||
});
|
||||
|
||||
test('follows with the weakest pair that beats the table, without jesters', () => {
|
||||
const s = rig([C(4, 1), C(4, 2), C(6, 1), C(6, 2), C(9, 1), C(9, 2), 'j1'], [C(10, 1), C(10, 2)]);
|
||||
expect(decide(s)).toEqual({ type: 'play', cardIds: [C(9, 1), C(9, 2)] });
|
||||
});
|
||||
|
||||
test('passes rather than spend a top card while the hand is big', () => {
|
||||
const s = rig([C(2), C(3), C(8), C(9), C(10), C(11)], [C(5)]);
|
||||
expect(decide(s)).toEqual({ type: 'pass' });
|
||||
});
|
||||
|
||||
test('gives back its two weakest numbers in the tax, never a jester', () => {
|
||||
const s = rig([C(1), C(2), C(11), C(12), 'j1']);
|
||||
s.phase = { kind: 'taxReturn', owed: { A: { to: 'E', count: 2, done: false } } };
|
||||
expect(decide(s).cardIds!.sort()).toEqual([C(11), C(12)].sort());
|
||||
});
|
||||
|
||||
test('declares a revolution only from the lower half', () => {
|
||||
for (const [order, declare] of [[['B', 'C', 'D', 'E', 'A'], true], [['A', 'B', 'C', 'D', 'E'], false]] as const) {
|
||||
const s = rig([C(5), 'j1', 'j2']);
|
||||
s.order = [...order];
|
||||
s.phase = { kind: 'revolutionCheck', confirmed: Object.fromEntries(P.map((p) => [p, false])) };
|
||||
expect(!!decide(s).declareRevolution).toBe(declare);
|
||||
}
|
||||
});
|
||||
|
||||
const modes: [string, Partial<DalmutiOptions>][] = [
|
||||
['pass locks out, 38 cards', { passLocksOut: true, removeHighCards: true }],
|
||||
['no revolution, taxable jesters, 5 rounds by last round', { revolution: false, jesterTaxable: true, rounds: 5, scoring: 'last-round' }],
|
||||
];
|
||||
for (const [name, opts] of modes) {
|
||||
test(`bots finish a game: ${name}`, () => {
|
||||
const options = dalmuti.optionsSchema.parse(opts);
|
||||
for (let seed = 1; seed <= 2; seed++) {
|
||||
const r = botPlayout(dalmuti as never, { players: ['h', 'bot:1', 'bot:2', 'bot:3', 'bot:4'], options, seed: seedN(seed), isBot: (p) => p.startsWith('bot:') });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
58
packages/games/src/dalmuti/bot.ts
Normal file
58
packages/games/src/dalmuti/bot.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* 달무티 computer player (1 = strongest, 13 = jester/wild): leads its weakest number as a whole set, follows with
|
||||
* the weakest set that still beats the table, keeps jesters and the top numbers for later (passing instead while
|
||||
* the hand is big), gives its worst cards back in the tax and declares a revolution only from the lower half.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { best, pick, playable } from '../bots/policy';
|
||||
import { JESTER, type DalmutiAction, type DalmutiView, type DCard, type PlayAction } from './types';
|
||||
|
||||
type ReturnTax = Extract<DalmutiAction, { type: 'returnTax' }>;
|
||||
|
||||
export const dalmutiBot: BotStrategy<DalmutiView, DalmutiAction> = ({ me, view, legal, random }) => {
|
||||
const hand = view.my?.hand ?? [];
|
||||
const byId = new Map(hand.map((c) => [c.id, c]));
|
||||
const cardsOf = (ids: string[]) => ids.map((id) => byId.get(id)).filter((c): c is DCard => !!c);
|
||||
|
||||
// Revolution check: cancelling the tax only pays off for the lower half (and the last seat's great revolution).
|
||||
const confirms = legal.filter((a) => a.type === 'confirmHand');
|
||||
if (confirms.length) {
|
||||
const seat = view.seats.find((s) => s.id === me);
|
||||
const lowerHalf = !!seat && seat.rank >= view.seats.length / 2;
|
||||
return confirms.find((a) => a.type === 'confirmHand' && !!a.declareRevolution === lowerHalf) ?? confirms[0]!;
|
||||
}
|
||||
|
||||
// Tax: give back the weakest numbers (highest), never a jester.
|
||||
const returns = legal.filter((a): a is ReturnTax => a.type === 'returnTax');
|
||||
if (returns.length) return best(returns, (a) => cardsOf(a.cardIds).reduce((x, c) => x + (c.n === JESTER ? -20 : c.n), 0), random);
|
||||
|
||||
const plays = legal.filter((a): a is PlayAction => a.type === 'play');
|
||||
const canPass = legal.some((a) => a.type === 'pass');
|
||||
if (!plays.length) return pick(playable(legal), random);
|
||||
|
||||
const count = (n: number) => hand.filter((c) => c.n === n).length;
|
||||
const score = (a: PlayAction): number => {
|
||||
const cards = cardsOf(a.cardIds);
|
||||
if (cards.length === hand.length) return 1000; // goes out
|
||||
const jesters = cards.filter((c) => c.n === JESTER).length;
|
||||
const nums = cards.filter((c) => c.n !== JESTER);
|
||||
const rank = nums.length ? nums[0]!.n : JESTER;
|
||||
let v = rank * 2 - jesters * 6 + random() * 0.5;
|
||||
if (nums.length) {
|
||||
v -= (count(rank) - nums.length) * 1.5; // splitting a set leaves stragglers
|
||||
if (!canPass) v += nums.length; // leading: shed as many as possible
|
||||
} else v -= 10; // jesters alone: last resort
|
||||
return v;
|
||||
};
|
||||
const choice = best(plays, score, random);
|
||||
if (canPass && score(choice) < 1000) {
|
||||
// Following: hold back strong cards / jesters while the hand is still big, otherwise play.
|
||||
const cards = cardsOf(choice.cardIds);
|
||||
const rank = Math.min(...cards.map((c) => c.n));
|
||||
const usesJester = cards.some((c) => c.n === JESTER);
|
||||
const big = hand.length > 5;
|
||||
if (big && (rank <= 3 || usesJester)) return { type: 'pass' };
|
||||
if (random() < 0.1) return { type: 'pass' };
|
||||
}
|
||||
return choice;
|
||||
};
|
||||
Reference in New Issue
Block a user