- secureRandom(): crypto.getRandomValues 53비트 실수. 서버의 Math.random(컴퓨터 수·생각 시간·AI 말·방 코드·마감 유예)을 모두 교체 - 컴퓨터 id의 ULID를 secureRandom으로 만들고, 그 무작위 부분 30비트로 난이도·말투(smart)를 정함(botDraw) - humanBest: 오목·체스·장기·오델로·바둑에서 난이도별로 비슷한 수(slip)·사고(lapse)·꼭 둬야 할 수 놓침(miss) - 문서 09 §9.1(확률표·게임별 기준·대국 결과), 06 §12; 테스트 bots/level.test.ts, 레벨별 완주 테스트 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
139 lines
6.3 KiB
TypeScript
139 lines
6.3 KiB
TypeScript
/**
|
|
* 바둑 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, humanBest, 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, level }) => {
|
|
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)]));
|
|
// Small = a shape point; capturing or saving three stones or more (≥ 24) is a must-play move.
|
|
const top = places.length ? humanBest(places, (p) => scores.get(p)!, random, level, { small: 1.5, critical: 24 }) : 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;
|
|
};
|