Files
joke-app/packages/games/src/bots/index.ts
EJClaw c9f4b782e8 새 게임 버건디의 성: 주사위 두 개로 육각 타일을 가져와 1번 공국을 채우는 2~4명 개인전 + 혼자 하기(2019년판 규칙), 시작 성 고르기·2011 수도원·추가 타일·여관·방패를 방 설정으로
- 데이터 packages/games/src/castles-of-burgundy/data.ts: 1번 공국 37칸(구역 13개 계산), 인원별 보급소 칸 색(3인 6번 보급소 B·D 광산), 타일 164장 + 추가 4장 + 여관 5장, 수도원 26+2종, 방패 18종, 점수표. 확인 안 된 데이터(가축 분포·검은 뒷면 수도원·장인 번호·2/3인 칸)는 UNCONFIRMED 주석으로 한 곳에
- 엔진(engine·moves·index): 페이즈 5 × 라운드 5, 일꾼 눈 바꾸기(6↔1, 수도원 8·9~12·방패 16), 가져오기·놓기·팔기·일꾼, 구역 완성·색 보너스·가축·건물 8종·배·성 연쇄를 pending 스택으로, 검은 보급소 구매(수도원 6번 2019/2011), 페이즈 끝 광산·방패 유지비·방패 14/15, 게임 끝 점수와 동점(빈칸 많은 사람 → 차례 트랙 뒤), 혼자 하기(강으로만 넓히기·목표 표시기·상품 5장 바꾸기·색 완성 보상), 시간 초과 자동 진행·자리 비움·기권
- 합법성은 actionError 하나, 합법 수는 후보를 그것으로 거름. view는 더미·다음 페이즈 상품·남의 판 상품 종류를 숨김
- 컴퓨터(bot.ts): 뷰를 상태로 되돌려 자기 차례를 미리 두고 주사위 A → B 묶음을 평가(1~20 한 수+잡음, 21~40 상위 3개, 41~60 상위 6개), 묶음은 차례 끝까지 기억. 한 수 평균 2~18ms
- 화면 apps/web/src/games/castles-of-burgundy/: PC는 가운데 판(보급소 1~6·검은 보급소·여관·남은 상품·색 보너스) + 내 공국 SVG + 오른쪽에 다른 사람 요약·작은 공국, 휴대폰은 [내 공국]/[보급소]/[다른 사람] 탭 + 아래 고정 주사위 줄. 주사위를 고르면 가져올 타일·놓을 칸·팔 상품이 빛나고 "일꾼 n" 배지, 버릴 칸·확인·내는 방법 시트, 성 보너스·배·건물·방패 등 대기 효과는 배너와 버튼. 소리·배너(구역 완성·색 완성·페이즈), 도움말·30초 요약·타일 효과 표
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·판·주사위 탭, docs/games/README.md, docs/games/castles-of-burgundy.md(§2 나중에 표시, §13 구현 결정)
- 나중에(데이터 필요): 팀전, 공국 2~10번(duchy), 흰 성, 무역로, 국경 초소
- 테스트: 규칙 48개(문서 §10), 무작위 대국 4가지 옵션(타일·상품 수 보존, JSON 왕복, 결정성) + 깊게 두기, 컴퓨터 3개(1단계 < 60단계), 방 통합 1개(연습 + 시간 넘김), e2e games.e2e.ts castles-of-burgundy(PC + 휴대폰 실제 행동 70번, 320px 넘침 없음, 기권으로 결과)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 00:06:00 +09:00

138 lines
5.4 KiB
TypeScript

/**
* Computer players (docs/09-game-engine.md §9). `decideBotAction` is the only place that touches the game state:
* it hands the strategy the bot's own view and its legal actions — nothing else — so a bot can't peek at hidden
* information (other hands, deck order).
*/
import { secureRandom, type AnyGameDefinition, type PlayerId } from '@bg/engine';
import type { BotLevel } from './persona';
import type { BotReaction, BotStrategy, LiveBotStrategy } from './types';
import { pick, playable, randomPolicy } from './policy';
import { omokBot } from '../omok/bot';
import { othelloBot } from '../othello/bot';
import { chessBot } from '../chess/bot';
import { janggiBot } from '../janggi/bot';
import { badukBot } from '../baduk/bot';
import { seotdaBot } from '../seotda/bot';
import { pokerBot } from '../poker/bot';
import { yachtBot } from '../yacht/bot';
import { yutBot } from '../yut/bot';
import { oneCardBot, oneCardReaction } from '../one-card/bot';
import { rummikubBot } from '../rummikub/bot';
import { gostopBot } from '../gostop/bot';
import { bangBot } from '../bang/bot';
import { davinciBot } from '../davinci-code/bot';
import { mahjongBot } from '../mahjong/bot';
import { marbleBot } from '../marble/bot';
import { dalmutiBot } from '../dalmuti/bot';
import { splendorBot } from '../splendor/bot';
import { quoridorBot } from '../quoridor/bot';
import { lasVegasBot } from '../las-vegas/bot';
import { cockroachPokerBot } from '../cockroach-poker/bot';
import { ninetyNineBot } from '../ninety-nine/bot';
import { oldMaidBot } from '../old-maid/bot';
import { mafiaBot } from '../mafia/bot';
import { appleBot } from '../apple/bot';
import { clueBot } from '../clue/bot';
import { connectFourBot } from '../connect-four/bot';
import { unoBot } from '../uno/bot';
import { liarBot } from '../liar/bot';
import { magicalAthleteBot } from '../magical-athlete/bot';
import { blackjackBot } from '../blackjack/bot';
import { cobBot } from '../castles-of-burgundy/bot';
export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
export { botPlay } from './policy';
/** Strategy per bot-enabled game (must match `BOT_GAMES` in @bg/shared). */
export const BOT_STRATEGIES: Record<string, BotStrategy> = {
omok: omokBot,
othello: othelloBot,
chess: chessBot,
janggi: janggiBot,
baduk: badukBot,
seotda: seotdaBot,
poker: pokerBot,
yacht: yachtBot,
yut: yutBot,
'one-card': oneCardBot,
rummikub: rummikubBot,
gostop: gostopBot,
bang: bangBot,
'davinci-code': davinciBot,
mahjong: mahjongBot,
marble: marbleBot,
dalmuti: dalmutiBot,
splendor: splendorBot,
quoridor: quoridorBot,
'las-vegas': lasVegasBot,
'cockroach-poker': cockroachPokerBot,
'ninety-nine': ninetyNineBot,
clue: clueBot,
'connect-four': connectFourBot,
'old-maid': oldMaidBot,
uno: unoBot,
'magical-athlete': magicalAthleteBot,
blackjack: blackjackBot,
'castles-of-burgundy': cobBot,
};
/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */
export const BOT_REACTIONS: Record<string, BotReaction> = {
'one-card': oneCardReaction,
};
/** When `me` reacts out of turn (server time), 'ignore', or null (nothing to react to / the game has no reactions). */
export function botReactionAt(def: AnyGameDefinition, state: unknown, me: PlayerId, level?: BotLevel): number | 'ignore' | null {
const react = BOT_REACTIONS[def.id];
if (!react) return null;
try {
return react({ me, view: def.view(state, me), level });
} catch {
return null;
}
}
/** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */
export function botCandidates(def: AnyGameDefinition, state: unknown, me: PlayerId): unknown[] {
return def.legalActions ? def.legalActions(state, me) : [];
}
/**
* Picks the bot's next action, or null when it has nothing to do. The strategy's choice is checked with `validate`
* (with the server clock); a rejected choice is dropped and the strategy asked again, so every returned action is
* one the server accepts. Validating only the chosen action keeps a move fast (chess validates ~0.3ms per move).
*/
export function decideBotAction(
def: AnyGameDefinition,
state: unknown,
me: PlayerId,
ctx: { now: number; random?: () => number; level?: BotLevel },
): unknown | null {
let legal = botCandidates(def, state, me);
if (!legal.length) return null;
const random = ctx.random ?? secureRandom;
const valid = (a: unknown) => def.validate(state, me, a, { now: ctx.now }).ok;
const view = def.view(state, me);
const strategy = BOT_STRATEGIES[def.id] ?? randomPolicy;
for (let attempt = 0; attempt < 3 && legal.length; attempt++) {
let action: unknown;
try {
action = strategy({ me, view: structuredClone(view), legal, random, level: ctx.level });
} catch {
break;
}
if (action !== undefined && valid(action)) return action;
legal = legal.filter((a) => a !== action);
}
const rest = legal.filter(valid);
return rest.length ? pick(playable(rest), random) : null;
}
/** Live strategies (games where everybody acts at once: 마피아·라이어 게임 talk, 사과 게임 races on its own board); also in `BOT_GAMES`. */
export const LIVE_BOT_STRATEGIES: Record<string, LiveBotStrategy> = {
mafia: mafiaBot,
apple: appleBot,
liar: liarBot,
};