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:
72
packages/games/src/janggi/bot.test.ts
Normal file
72
packages/games/src/janggi/bot.test.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
/** 장기 computer player: 외통, free material, no losing trades, and a 한수쉼 that wins on score. */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng } from '@bg/engine';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { janggi, type JanggiAction, type JanggiOptions, type JanggiState } from './index';
|
||||
import { idx, inCheck, positionKey, type Board, type PieceKind, type Side } from './rules';
|
||||
|
||||
type P = [Side, PieceKind, number, number];
|
||||
const rng = () => SeededRng.fromSeed([1, 2, 3, 4]);
|
||||
|
||||
/** Game in play with a custom board; A = 초 (the bot here), B = 한. */
|
||||
function custom(pieces: P[], o: Partial<JanggiOptions> = {}, turn: Side = 'cho'): JanggiState {
|
||||
const s = janggi.setup({ players: ['A', 'B'], options: janggi.optionsSchema.parse({ sideAssignment: 'hostCho', ...o }), rng: rng(), now: 0 });
|
||||
const b: Board = new Array(90).fill(null);
|
||||
for (const [side, kind, f, r] of pieces) b[idx(f, r)] = { side, kind };
|
||||
s.board = b;
|
||||
s.startBoard = b.slice();
|
||||
s.phase = 'playing';
|
||||
s.turn = turn;
|
||||
s.inCheck = inCheck(b, turn) ? turn : null;
|
||||
s.positionCounts = { [positionKey(b, turn)]: 1 };
|
||||
return s;
|
||||
}
|
||||
const decide = (s: JanggiState, seed = 1) => {
|
||||
const r = SeededRng.fromSeed([seed, 5, 5, 5]);
|
||||
return decideBotAction(janggi, s, 'A', { now: 1000, random: () => r.next() }) as JanggiAction;
|
||||
};
|
||||
const kings: P[] = [
|
||||
['cho', 'king', 4, 1],
|
||||
['han', 'king', 3, 8],
|
||||
];
|
||||
|
||||
describe('janggi bot', () => {
|
||||
test('captures a hanging 차', () => {
|
||||
const s = custom([...kings, ['cho', 'cha', 0, 0], ['han', 'cha', 0, 5]]);
|
||||
for (let seed = 1; seed <= 3; seed++) expect(decide(s, seed)).toEqual({ type: 'move', from: { f: 0, r: 0 }, to: { f: 0, r: 5 } });
|
||||
});
|
||||
|
||||
test('does not trade its 차 for a defended 졸', () => {
|
||||
// 한 병 on (0,5) is covered by the 한 차 on (0,9): taking it loses the 차.
|
||||
const s = custom([...kings, ['cho', 'cha', 0, 0], ['han', 'jol', 0, 5], ['han', 'cha', 0, 9]]);
|
||||
for (let seed = 1; seed <= 3; seed++) {
|
||||
const a = decide(s, seed);
|
||||
expect(a.type === 'move' && a.to.f === 0 && a.to.r === 5).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('finds 외통 in one', () => {
|
||||
// 한 궁 (4,9) is boxed in by its own 병; the 차 on (0,8) guards rank 8, the other 차 checks down file 4.
|
||||
const s = custom([
|
||||
['cho', 'king', 3, 1],
|
||||
['cho', 'cha', 0, 8],
|
||||
['cho', 'cha', 8, 5],
|
||||
['han', 'king', 4, 9],
|
||||
['han', 'jol', 3, 9],
|
||||
['han', 'jol', 5, 9],
|
||||
]);
|
||||
const a = decide(s);
|
||||
const after = janggi.apply(s, 'A', a, { rng: rng(), now: 1000 }).state;
|
||||
expect(after.result?.reason).toBe('checkmate');
|
||||
expect(after.result?.winner).toBe('cho');
|
||||
});
|
||||
|
||||
test('answers a pass with a pass when that wins on score', () => {
|
||||
const s = custom([...kings, ['cho', 'cha', 0, 0], ['cho', 'po', 1, 2], ['han', 'sa', 3, 9]]);
|
||||
s.moves = [{ kind: 'pass', side: 'han' }];
|
||||
s.consecutivePasses = 1;
|
||||
expect(decide(s)).toEqual({ type: 'pass' });
|
||||
const after = janggi.apply(s, 'A', { type: 'pass' }, { rng: rng(), now: 1000 }).state;
|
||||
expect(after.result?.winner).toBe('cho');
|
||||
});
|
||||
});
|
||||
138
packages/games/src/janggi/bot.ts
Normal file
138
packages/games/src/janggi/bot.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* 장기 computer player (1-ply with a cheap look at the reply): 외통 > win material without leaving pieces en
|
||||
* prise > 장군 > activity. Knows 빅장 (judged by score), the 4th-repetition rule and when a 한수쉼 ends the game.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests, best, pick, playable, typeOf } from '../bots/policy';
|
||||
import type { JanggiView } from './index';
|
||||
import {
|
||||
HAN_BONUS,
|
||||
PIECE_VALUE,
|
||||
attacks,
|
||||
findKing,
|
||||
hasLegalMove,
|
||||
idx,
|
||||
inCheck,
|
||||
kingsFacing,
|
||||
makeMove,
|
||||
material,
|
||||
other,
|
||||
positionKey,
|
||||
pseudoMoves,
|
||||
sqOf,
|
||||
type Board,
|
||||
type Side,
|
||||
type Sq,
|
||||
} from './rules';
|
||||
|
||||
type Move = { type: 'move'; from: Sq; to: Sq };
|
||||
type Pass = { type: 'pass' };
|
||||
/** After this many plies, bots stop dragging out a game a 한수쉼 can end (score judgement). */
|
||||
const LONG_GAME = 300;
|
||||
|
||||
/** Positions seen so far (board + side to move), rebuilt backwards from the public move list. */
|
||||
function seenPositions(view: JanggiView): Map<string, number> {
|
||||
const seen = new Map<string, number>();
|
||||
const b = view.board.slice() as Board;
|
||||
let turn = view.turn;
|
||||
const add = () => seen.set(positionKey(b, turn), (seen.get(positionKey(b, turn)) ?? 0) + 1);
|
||||
add();
|
||||
for (let i = view.moves.length - 1; i >= 0; i--) {
|
||||
const m = view.moves[i]!;
|
||||
if (m.kind === 'move') {
|
||||
b[idx(m.from.f, m.from.r)] = b[idx(m.to.f, m.to.r)]!;
|
||||
b[idx(m.to.f, m.to.r)] = m.captured ? { side: other(m.side), kind: m.captured } : null;
|
||||
}
|
||||
turn = m.side;
|
||||
add();
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
/** Worst material the opponent can win at once on `b` (a defended victim only costs the difference; 외통 = 1000). */
|
||||
function threat(b: Board, me: Side): number {
|
||||
const opp = other(me);
|
||||
const king = sqOf(findKing(b, me));
|
||||
// Only moves touching the king's file/rank or its surroundings can give 장군 (lines, 멱, palace diagonals).
|
||||
const nearKing = (i: number) => {
|
||||
const q = sqOf(i);
|
||||
return q.f === king.f || q.r === king.r || Math.max(Math.abs(q.f - king.f), Math.abs(q.r - king.r)) <= 3;
|
||||
};
|
||||
let worst = 0;
|
||||
for (let i = 0; i < b.length; i++) {
|
||||
if (b[i]?.side !== opp) continue;
|
||||
const fromNear = nearKing(i);
|
||||
for (const m of pseudoMoves(b, i)) {
|
||||
const victim = b[m.to];
|
||||
if (victim?.side === me && victim.kind === 'king') continue;
|
||||
const after = makeMove(b, i, m.to);
|
||||
if (inCheck(after, opp)) continue; // illegal for them
|
||||
if ((fromNear || nearKing(m.to)) && inCheck(after, me) && !hasLegalMove(after, me)) return 1000; // 외통 next move
|
||||
if (!victim || victim.side !== me) continue;
|
||||
const v = PIECE_VALUE[victim.kind];
|
||||
const loss = attacks(after, me, m.to) ? Math.max(0, v - PIECE_VALUE[b[i]!.kind]) : v;
|
||||
worst = Math.max(worst, loss);
|
||||
}
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
|
||||
export const janggiBot: BotStrategy<JanggiView> = ({ view, legal, random }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
const moves = legal.filter((a) => typeOf(a) === 'move') as Move[];
|
||||
const pass = legal.find((a) => typeOf(a) === 'pass') as Pass | undefined;
|
||||
const me = view.mySide;
|
||||
if ((!moves.length && !pass) || !me) return pick(playable(legal), random); // 상차림: any arrangement
|
||||
const opp = other(me);
|
||||
const board = view.board as Board;
|
||||
const score = (b: Board) => material(b, me) + (me === 'han' ? HAN_BONUS : 0) - material(b, opp) - (opp === 'han' ? HAN_BONUS : 0);
|
||||
/** Value of a game ended by score judgement right now (a draw when scoring is off). */
|
||||
const judged = (b: Board) => (!view.rules.scoring ? 0 : score(b) > 0 ? 1e5 : -1e5);
|
||||
const seen = view.repeatWarning ? seenPositions(view) : null;
|
||||
const long = view.moveCount >= LONG_GAME;
|
||||
const capturedYet = view.moves.some((m) => m.kind === 'move' && m.captured);
|
||||
const bikjangArmed = (b: Board) =>
|
||||
view.rules.bikjang === 'kjf' ? capturedYet : view.rules.bikjang === 'kja30' && material(b, 'cho') < 30 && material(b, 'han') < 30;
|
||||
const lastOpp = view.moves.at(-1);
|
||||
|
||||
const evaluate = (b: Board, gain: number): number => {
|
||||
// The opponent leaving a 빅장 standing → score judgement.
|
||||
if (view.bikjang && view.bikjang.calledBy === opp && kingsFacing(b)) return judged(b);
|
||||
if (seen && (seen.get(positionKey(b, opp)) ?? 0) >= 3) return view.rules.repetition === 'lose' ? -1e6 : judged(b);
|
||||
let s = (gain - threat(b, me)) * 100;
|
||||
// Calling 빅장 hands the opponent the choice of a score judgement: only when ahead.
|
||||
if (kingsFacing(b) && !kingsFacing(board) && bikjangArmed(b)) s += score(b) > 0 ? 30 : -300;
|
||||
return s;
|
||||
};
|
||||
|
||||
const scoreMove = (m: Move): number => {
|
||||
const from = idx(m.from.f, m.from.r);
|
||||
const to = idx(m.to.f, m.to.r);
|
||||
const piece = board[from]!;
|
||||
const b = makeMove(board, from, to);
|
||||
const check = inCheck(b, opp);
|
||||
if (check && !hasLegalMove(b, opp)) return 1e7;
|
||||
let s = evaluate(b, board[to] ? PIECE_VALUE[board[to]!.kind] : 0);
|
||||
if (Math.abs(s) >= 1e5) return s;
|
||||
if (check) s += 25;
|
||||
if (piece.kind === 'king') s -= 15;
|
||||
// Activity: 졸 step forward, 차·포·마 leave the back ranks.
|
||||
const ahead = (r: number) => (me === 'cho' ? r : 9 - r);
|
||||
if (piece.kind === 'jol' && ahead(m.to.r) > ahead(m.from.r)) s += 4;
|
||||
if ((piece.kind === 'cha' || piece.kind === 'po' || piece.kind === 'ma') && ahead(m.from.r) <= 2 && ahead(m.to.r) > 2) s += 6;
|
||||
return s + random() * 5;
|
||||
};
|
||||
|
||||
/** 한수쉼: only to dodge a threat, or when two passes in a row end the game in our favour. */
|
||||
const passScore = (): number => {
|
||||
const oppPassed = lastOpp?.kind === 'pass' && lastOpp.side === opp;
|
||||
const base = evaluate(board, 0) - 50;
|
||||
if (oppPassed && view.rules.scoring && score(board) > 0) return judged(board);
|
||||
// Long game: wind it down (the side ahead offers, the other answers) so bot games always finish.
|
||||
if (long && (oppPassed || score(board) > 0)) return Math.max(base, 200);
|
||||
return base;
|
||||
};
|
||||
const options: (Move | Pass)[] = pass ? [...moves, pass] : moves;
|
||||
return best(options, (a) => (typeOf(a) === 'pass' ? passScore() : scoreMove(a as Move)), random);
|
||||
};
|
||||
Reference in New Issue
Block a user