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:
69
packages/games/src/baduk/bot.test.ts
Normal file
69
packages/games/src/baduk/bot.test.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
/** 바둑 computer player: captures, saves stones in atari, passes when only territory is left, guards the score marks. */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng } from '@bg/engine';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { baduk, type BadukAction, type BadukOptions, type BadukState } from './index';
|
||||
import { hashBoard } from './board';
|
||||
|
||||
const COLS = 'ABCDEFGHJ';
|
||||
const at = (label: string) => ({ x: COLS.indexOf(label[0]!), y: 9 - Number(label.slice(1)) });
|
||||
const rng = () => SeededRng.fromSeed([1, 2, 3, 4]);
|
||||
|
||||
/** 9×9, A = black (the bot here), B = white. Stones are set directly. */
|
||||
function make(stones: { black?: string[]; white?: string[] } = {}, turn: 'black' | 'white' = 'black', opts: Partial<BadukOptions> = {}): BadukState {
|
||||
const options = baduk.optionsSchema.parse({ colorAssignment: 'hostBlack', boardSize: 9, ...opts });
|
||||
const s = baduk.setup({ players: ['A', 'B'], options, rng: rng(), now: 0 });
|
||||
for (const [color, v] of [['black', 1], ['white', 2]] as const) for (const l of stones[color] ?? []) s.board[at(l).y * 9 + at(l).x] = v;
|
||||
s.turn = turn;
|
||||
s.hash = hashBoard(s.board);
|
||||
s.positionHistory = [s.hash];
|
||||
s.situationCounts = { [s.hash + (turn === 'black' ? 'b' : 'w')]: 1 };
|
||||
return s;
|
||||
}
|
||||
const decide = (s: BadukState, who = 'A', seed = 1) => {
|
||||
const r = SeededRng.fromSeed([seed, 3, 3, 3]);
|
||||
return decideBotAction(baduk, s, who, { now: 1000, random: () => r.next() }) as BadukAction;
|
||||
};
|
||||
const act = (s: BadukState, who: string, a: BadukAction) => {
|
||||
const v = baduk.validate(s, who, a);
|
||||
if (!v.ok) throw new Error(v.reason);
|
||||
return baduk.apply(s, who, a, { rng: rng(), now: 1000 }).state;
|
||||
};
|
||||
|
||||
/** Black owns columns A–D, white F–J; the E/F boundary is closed. */
|
||||
const SPLIT = {
|
||||
black: ['D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7', 'E8', 'E9'],
|
||||
white: ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9'],
|
||||
};
|
||||
|
||||
describe('baduk bot', () => {
|
||||
test('captures a stone in atari', () => {
|
||||
const s = make({ black: ['D5', 'F5', 'E6', 'C3'], white: ['E5', 'G7'] });
|
||||
expect(decide(s)).toEqual({ type: 'place', ...at('E4') });
|
||||
});
|
||||
|
||||
test('saves its own stone in atari instead of playing elsewhere', () => {
|
||||
const s = make({ black: ['E5', 'C7'], white: ['D5', 'F5', 'E6'] });
|
||||
expect(decide(s)).toEqual({ type: 'place', ...at('E4') });
|
||||
});
|
||||
|
||||
test('passes when only settled territory is left, so the game can end', () => {
|
||||
for (let seed = 1; seed <= 3; seed++) expect(decide(make(SPLIT), 'A', seed)).toEqual({ type: 'pass' });
|
||||
});
|
||||
|
||||
test('dead-stone phase: restores a group marked dead against it, then agrees', () => {
|
||||
let s = make(SPLIT);
|
||||
s = act(s, 'A', { type: 'pass' });
|
||||
s = act(s, 'B', { type: 'pass' });
|
||||
expect(s.phase).toBe('scoring');
|
||||
expect(decide(s)).toEqual({ type: 'agreeScore' });
|
||||
// The opponent marks the bot's wall dead.
|
||||
s = act(s, 'B', { type: 'toggleDead', ...at('D5') });
|
||||
expect(s.scoringMarks!.dead.length).toBeGreaterThan(0);
|
||||
const fix = decide(s);
|
||||
expect(fix.type).toBe('toggleDead');
|
||||
s = act(s, 'A', fix);
|
||||
expect(s.scoringMarks!.dead).toEqual([]);
|
||||
expect(decide(s)).toEqual({ type: 'agreeScore' });
|
||||
});
|
||||
});
|
||||
137
packages/games/src/baduk/bot.ts
Normal file
137
packages/games/src/baduk/bot.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* 바둑 computer player: capture > save own stones in atari > put the opponent in atari > play near stones in
|
||||
* contested areas, never self-atari, and pass once only settled territory is left. In the dead-stone phase it
|
||||
* agrees, after restoring the automatic suggestion if the marks were changed against it.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests, best, pick, playable, typeOf } from '../bots/policy';
|
||||
import type { BadukView } from './index';
|
||||
import { emptyRegionAt, mapChains, markGroup, neighbours, regionsOf, suggestMarks, type Cell, type Stone } from './board';
|
||||
|
||||
type Place = { type: 'place'; x: number; y: number };
|
||||
type Act = Place | { type: 'pass' | 'agreeScore' } | { type: 'toggleDead' | 'toggleSeki'; x: number; y: number };
|
||||
|
||||
/** Dead-stone phase: undo a change that disagrees with the automatic suggestion (dead groups, seki), else agree. */
|
||||
function scoringAction(view: BadukView): Act {
|
||||
const { size, board } = view;
|
||||
const sug = suggestMarks(board, size);
|
||||
const want = new Set(sug.dead);
|
||||
const have = new Set(view.scoring!.dead.map((p) => p.y * size + p.x));
|
||||
const at = (i: number) => ({ x: i % size, y: Math.floor(i / size) });
|
||||
// Toggle a group only if that strictly reduces the disagreement (so a bot never toggles back and forth).
|
||||
const differs = (i: number) => want.has(i) !== have.has(i);
|
||||
for (let i = 0; i < board.length; i++) {
|
||||
if (!board[i] || !differs(i)) continue;
|
||||
const group = markGroup(board, size, i, have);
|
||||
if (group.filter(differs).length * 2 > group.length) return { type: 'toggleDead', ...at(i) };
|
||||
}
|
||||
// Seki regions: one toggle per region that is marked but not suggested, or suggested but not marked.
|
||||
const marked = view.scoring!.seki.map((p) => p.y * size + p.x);
|
||||
for (const p of marked) {
|
||||
if (!emptyRegionAt(board, size, p, have).some((q) => sug.seki.includes(q))) return { type: 'toggleSeki', ...at(p) };
|
||||
}
|
||||
const markedSet = new Set(marked);
|
||||
for (const q of sug.seki) if (!markedSet.has(q)) return { type: 'toggleSeki', ...at(q) };
|
||||
return { type: 'agreeScore' };
|
||||
}
|
||||
|
||||
export const badukBot: BotStrategy<BadukView, Act> = ({ view, legal, random }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
if (view.phase === 'scoring') return legal.some((a) => a.type === 'agreeScore') ? scoringAction(view) : pick(playable(legal), random);
|
||||
const places = legal.filter((a) => typeOf(a) === 'place') as Place[];
|
||||
const pass = legal.find((a) => a.type === 'pass');
|
||||
if (!view.myColor || !pass) return pick(playable(legal), random);
|
||||
const { size, board } = view;
|
||||
const me: Stone = view.myColor === 'black' ? 1 : 2;
|
||||
const opp: Stone = me === 1 ? 2 : 1;
|
||||
const nb = neighbours(size);
|
||||
const { id, chains } = mapChains(board, size);
|
||||
// Distance from each colour's stones through empty points (Infinity where it can't reach).
|
||||
const dist = (c: Stone): number[] => {
|
||||
const d = new Array<number>(board.length).fill(Infinity);
|
||||
const queue: number[] = [];
|
||||
for (let i = 0; i < board.length; i++) {
|
||||
if (board[i] !== c) continue;
|
||||
d[i] = 0;
|
||||
queue.push(i);
|
||||
}
|
||||
for (let h = 0; h < queue.length; h++) {
|
||||
const p = queue[h]!;
|
||||
for (let k = 1; k <= nb[p * 5]!; k++) {
|
||||
const q = nb[p * 5 + k]!;
|
||||
if (board[q] !== 0 || d[q] !== Infinity) continue;
|
||||
d[q] = d[p]! + 1;
|
||||
queue.push(q);
|
||||
}
|
||||
}
|
||||
return d;
|
||||
};
|
||||
const dMe = dist(me);
|
||||
const dOpp = dist(opp);
|
||||
// Settled points (ours or theirs): clearly closer to one colour, or in a region only one colour reaches
|
||||
// (unless that region is half the board or more, e.g. right after the first stone).
|
||||
const regions = regionsOf(board, size, (i) => board[i] === 0);
|
||||
const settledMax = Math.floor((size * size) / 2);
|
||||
const settled = (i: number) => {
|
||||
const a = dMe[i]!;
|
||||
const b = dOpp[i]!;
|
||||
if ((a === Infinity) !== (b === Infinity)) return regions.list[regions.id[i]!]!.points.length <= settledMax;
|
||||
return Math.min(a, b) <= 3 && Math.abs(a - b) >= 2;
|
||||
};
|
||||
const line = (v: number) => Math.min(v, size - 1 - v); // 0 = first line
|
||||
|
||||
const score = ({ x, y }: Place): number => {
|
||||
const i = y * size + x;
|
||||
let s = 0;
|
||||
let captured = 0;
|
||||
const libs = new Set<number>();
|
||||
const seen = new Set<number>();
|
||||
let ownSize = 1;
|
||||
let rescue = false;
|
||||
for (let k = 1; k <= nb[i * 5]!; k++) {
|
||||
const q = nb[i * 5 + k]!;
|
||||
const v = board[q] as Cell;
|
||||
if (v === 0) {
|
||||
libs.add(q);
|
||||
continue;
|
||||
}
|
||||
const c = id[q]!;
|
||||
if (seen.has(c)) continue;
|
||||
seen.add(c);
|
||||
const ch = chains[c]!;
|
||||
if (v === opp) {
|
||||
if (ch.libs.length === 1) captured += ch.stones.length;
|
||||
else if (ch.libs.length === 2) s += 2 * ch.stones.length; // atari
|
||||
} else {
|
||||
ownSize += ch.stones.length;
|
||||
for (const l of ch.libs) libs.add(l);
|
||||
if (ch.libs.length === 1) {
|
||||
rescue = true;
|
||||
s += 8 * ch.stones.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
libs.delete(i);
|
||||
const after = libs.size + (captured ? 1 : 0);
|
||||
if (captured) s += 10 * captured;
|
||||
else if (after <= 1) return -10 * ownSize; // self-atari
|
||||
else if (after === 2 && ownSize > 1) s -= 2; // crawling with few liberties
|
||||
if (!captured && !rescue && settled(i)) return -3; // nothing to gain inside settled territory
|
||||
// Shape: stay off the first line, like the 3rd/4th lines, keep in touch with the stones.
|
||||
// (A first-line point touching stones is a boundary to close, not a bad opening move.)
|
||||
const near = Math.min(dMe[i]!, dOpp[i]!);
|
||||
const l = Math.min(line(x), line(y));
|
||||
s += l === 0 ? (near === 1 ? 0 : -1.5) : l === 1 ? 0 : l <= 3 ? 1 : 0.5;
|
||||
if (near <= 2) s += 0.5;
|
||||
else if (near > 3 && view.moveCount > 6) s -= 0.5;
|
||||
return s + 1 + random() * 0.5;
|
||||
};
|
||||
|
||||
// Very long game (endless capture fights): wind down so it always ends.
|
||||
if (view.moveCount > 2 * board.length) return pass;
|
||||
const scores = new Map(places.map((p) => [p, score(p)]));
|
||||
const top = places.length ? best(places, (p) => scores.get(p)!, random) : null;
|
||||
// Nothing useful left (only settled areas, dame on the edge or self-atari): pass so the game can end.
|
||||
return top && scores.get(top)! > 1 ? top : pass;
|
||||
};
|
||||
Reference in New Issue
Block a user