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:
58
packages/games/src/chess/bot.test.ts
Normal file
58
packages/games/src/chess/bot.test.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
/** 체스 computer player: mates, wins material without hanging it, promotes to a queen. */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng } from '@bg/engine';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { chess, type ChessAction, type ChessState } from './index';
|
||||
import { fullFen, keyOf, load } from './rules';
|
||||
|
||||
/** White = 'A' (the bot in these tests), black = 'B'; both clocks running. */
|
||||
function make(fen: string): ChessState {
|
||||
const options = chess.optionsSchema.parse({ colorAssignment: 'hostWhite' });
|
||||
const s = chess.setup({ players: ['A', 'B'], options, rng: SeededRng.fromSeed([1, 2, 3, 4]), now: 0 });
|
||||
s.startFen = fullFen(load(fen));
|
||||
s.fen = s.startFen;
|
||||
s.repetition = { [keyOf(load(fen))]: 1 };
|
||||
s.clock.started = { white: true, black: true };
|
||||
return s;
|
||||
}
|
||||
const decide = (s: ChessState, seed = 1) => {
|
||||
const r = SeededRng.fromSeed([seed, 7, 7, 7]);
|
||||
return decideBotAction(chess, s, 'A', { now: 1000, random: () => r.next() }) as ChessAction;
|
||||
};
|
||||
const uci = (a: ChessAction) => (a.type === 'move' ? `${a.from}${a.to}${a.promotion ?? ''}` : a.type);
|
||||
|
||||
describe('chess bot', () => {
|
||||
test('plays mate in one', () => {
|
||||
for (let seed = 1; seed <= 5; seed++) expect(uci(decide(make('6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1'), seed))).toBe('a1a8');
|
||||
});
|
||||
|
||||
test('takes a hanging queen', () => {
|
||||
expect(uci(decide(make('4k3/8/8/3q4/8/8/8/3RK3 w - - 0 1')))).toBe('d1d5');
|
||||
});
|
||||
|
||||
test('does not grab a defended pawn with the queen, and moves an attacked queen away', () => {
|
||||
// Qxd5 would lose the queen to cxd5.
|
||||
for (let seed = 1; seed <= 5; seed++) expect(uci(decide(make('4k3/8/2p5/3p4/8/8/8/3QK3 w - - 0 1'), seed))).not.toBe('d1d5');
|
||||
// The queen on d5 is attacked by the c6 pawn: it must leave, to a square nothing black attacks.
|
||||
for (let seed = 1; seed <= 5; seed++) {
|
||||
const fen = '4k3/8/2p5/3Q4/8/8/8/4K3 w - - 0 1';
|
||||
const a = decide(make(fen), seed) as Extract<ChessAction, { type: 'move' }>;
|
||||
expect(a.from).toBe('d5');
|
||||
const c = load(fen);
|
||||
c.move({ from: a.from, to: a.to });
|
||||
expect(c.isAttacked(a.to as 'a1', 'b')).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('promotes to a queen', () => {
|
||||
expect(uci(decide(make('8/P7/8/8/8/8/k7/4K3 w - - 0 1')))).toBe('a7a8q');
|
||||
});
|
||||
|
||||
test("accepts the opponent's undo request", () => {
|
||||
let s = make('4k3/8/8/8/8/8/4P3/4K3 w - - 0 1');
|
||||
s = chess.apply(s, 'A', { type: 'move', from: 'e2', to: 'e4' }, { rng: SeededRng.fromSeed([1, 1, 1, 1]), now: 500 }).state;
|
||||
s = chess.apply(s, 'B', { type: 'move', from: 'e8', to: 'd7' }, { rng: SeededRng.fromSeed([1, 1, 1, 1]), now: 600 }).state;
|
||||
s = chess.apply(s, 'B', { type: 'requestUndo' }, { rng: SeededRng.fromSeed([1, 1, 1, 1]), now: 700 }).state;
|
||||
expect(decide(s)).toEqual({ type: 'respondUndo', accept: true });
|
||||
});
|
||||
});
|
||||
74
packages/games/src/chess/bot.ts
Normal file
74
packages/games/src/chess/bot.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* 체스 computer player (1-ply with a cheap look at the reply): mate > win material without hanging it >
|
||||
* checks > development / centre / pawn pushes. Promotions are scored by the new piece, so it queens
|
||||
* (and under-promotes only when queening would stalemate).
|
||||
*/
|
||||
import type { PieceSymbol, Square } from 'chess.js';
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests, best, pick, playable, typeOf } from '../bots/policy';
|
||||
import type { ChessView } from './index';
|
||||
import { PIECE_VALUE, insufficientMaterial, load, pieces } from './rules';
|
||||
|
||||
type Move = { type: 'move'; from: Square; to: Square; promotion?: 'q' | 'r' | 'b' | 'n' };
|
||||
const CENTER = new Set(['d4', 'e4', 'd5', 'e5']);
|
||||
const NEAR_CENTER = new Set(['c3', 'd3', 'e3', 'f3', 'c4', 'f4', 'c5', 'f5', 'c6', 'd6', 'e6', 'f6']);
|
||||
const SAN_PIECE: Record<string, PieceSymbol> = { N: 'n', B: 'b', R: 'r', Q: 'q', K: 'k' };
|
||||
|
||||
export const chessBot: BotStrategy<ChessView> = ({ view, legal, random }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
const moves = legal.filter((a) => typeOf(a) === 'move') as Move[];
|
||||
if (!moves.length) return pick(playable(legal), random);
|
||||
const c = load(view.fen);
|
||||
const us = c.turn();
|
||||
const them = us === 'w' ? 'b' : 'w';
|
||||
let balance = 0;
|
||||
for (const p of pieces(c)) balance += (p.color === us ? 1 : -1) * PIECE_VALUE[p.type];
|
||||
const opening = view.moves.length < 20;
|
||||
const theirPieces = pieces(c).filter((p) => p.color === them && p.type !== 'k').length;
|
||||
|
||||
/** Worst material loss the opponent can inflict right away (mate counts as everything). */
|
||||
const threat = (): number => {
|
||||
let worst = 0;
|
||||
for (const san of c.moves()) {
|
||||
if (san.endsWith('#')) return 1000;
|
||||
if (!san.includes('x')) continue;
|
||||
const to = san.match(/[a-h][1-8]/g)!.at(-1)! as Square;
|
||||
const victim = c.get(to)?.type ?? 'p'; // empty target = en passant
|
||||
const attacker = SAN_PIECE[san[0]!] ?? 'p';
|
||||
// A defended victim only costs the difference (they lose the attacker to our recapture).
|
||||
const defended = c.attackers(to, us).length > 0;
|
||||
const loss = defended ? Math.max(0, PIECE_VALUE[victim] - PIECE_VALUE[attacker]) : PIECE_VALUE[victim];
|
||||
worst = Math.max(worst, loss);
|
||||
}
|
||||
return worst;
|
||||
};
|
||||
|
||||
const score = (m: Move): number => {
|
||||
const piece = c.get(m.from)!;
|
||||
const done = c.move({ from: m.from, to: m.to, promotion: m.promotion });
|
||||
try {
|
||||
if (c.isCheckmate()) return 1e6;
|
||||
const gain = (done.captured ? PIECE_VALUE[done.captured] : 0) + (done.promotion ? PIECE_VALUE[done.promotion] - 1 : 0);
|
||||
// A draw is bad when ahead, welcome when clearly behind.
|
||||
if (c.isStalemate() || insufficientMaterial(c)) return (balance + gain > 0 ? -5000 : balance + gain < -2 ? 5000 : 0) + random();
|
||||
let s = (gain - threat()) * 100;
|
||||
if (c.inCheck()) s += 25;
|
||||
// Squeeze a lone king (helps finish won endgames): fewer replies is better.
|
||||
if (theirPieces === 0) s -= c.moves().length * 3;
|
||||
if (done.isKingsideCastle() || done.isQueensideCastle()) s += 40;
|
||||
else if (piece.type === 'k' && opening) s -= 30;
|
||||
if (CENTER.has(m.to)) s += piece.type === 'p' ? 12 : 6;
|
||||
else if (NEAR_CENTER.has(m.to)) s += 4;
|
||||
const backRank = us === 'w' ? '1' : '8';
|
||||
if (opening && (piece.type === 'n' || piece.type === 'b') && m.from[1] === backRank) s += 15;
|
||||
if (opening && piece.type === 'q') s -= 10;
|
||||
// Late in the game, push pawns towards promotion.
|
||||
if (piece.type === 'p' && !opening) s += (us === 'w' ? Number(m.to[1]) : 9 - Number(m.to[1])) * 2;
|
||||
return s + random() * 5;
|
||||
} finally {
|
||||
c.undo();
|
||||
}
|
||||
};
|
||||
return best(moves, score, random);
|
||||
};
|
||||
Reference in New Issue
Block a user