fertig-classic-games/tools/genGoPuzzles.js

249 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
// genGoPuzzles.js: builds Hōun's life-and-death problems for Go
// (src/games/go/GoPuzzleData.js).
//
// Each problem starts from a classic eye-space shape in the top-left
// corner or along the top edge (straight three, bent four, bulky five,
// rabbity six, …). The defender's wall is every point touching that space
// (diagonals too, so walls are solid); the attacker's wall wraps that,
// reaching into open board so it can never be captured. Then the shape is
// roughed up at random: wall stones knocked out, attacker stones dropped
// inside, a defender stone added. The solver (GoTsumego.js) keeps a
// problem only when
// • Black, to play, has exactly one move that works (to kill, or to live),
// • passing would not do (the problem is real),
// • the answer is the same whoever is given the kos (no ko problems),
// • the search finished inside its budget.
// Ratings come from how deep the answer goes, how many first moves look
// plausible, and whether the key move is a sacrifice. Duplicates (same
// stones) are dropped.
//
// Usage: node tools/genGoPuzzles.js [--target 200] [--seed 7]
import { writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import * as L from '../src/games/go/GoLogic.js';
import * as T from '../src/games/go/GoTsumego.js';
const args = process.argv.slice(2);
const arg = (k, d) => { const i = args.indexOf(k); return i >= 0 ? Number(args[i + 1]) : d; };
const TARGET = arg('--target', 200);
const SEED = arg('--seed', 7);
const SIZE = 9;
const BUDGET = 60000;
function mulberry32(seed) {
let a = (seed >>> 0) || 1;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const rnd = mulberry32(SEED);
const pick = (a) => a[Math.floor(rnd() * a.length)];
// ── shapes: [name, cells (row, col) from the corner, 'corner' | 'side'] ──────
const rect = (h, w, r0 = 0, c0 = 0) => { const o = []; for (let r = 0; r < h; r++) for (let c = 0; c < w; c++) o.push([r0 + r, c0 + c]); return o; };
const SHAPES = [
['a straight three', [[0, 0], [0, 1], [0, 2]], 'corner'],
['a bent three', [[0, 0], [0, 1], [1, 0]], 'corner'],
['a square four', rect(2, 2), 'corner'],
['a straight four', [[0, 0], [0, 1], [0, 2], [0, 3]], 'corner'],
['a bent four', [[0, 0], [0, 1], [0, 2], [1, 0]], 'corner'],
['a pyramid four', [[0, 0], [0, 1], [0, 2], [1, 1]], 'corner'],
['a bulky five', [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]], 'corner'],
['a bulky five', [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0]], 'corner'],
['a straight five', [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]], 'corner'],
['an L-shaped five', [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0]], 'corner'],
['a crossed five', [[0, 1], [1, 0], [1, 1], [1, 2], [2, 1]], 'corner'],
['a rabbity six', rect(2, 3), 'corner'],
['a long six', [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1]], 'corner'],
['a corner seven', [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0]], 'corner'],
['a two-by-four', rect(2, 4), 'corner'],
['a carpenter\'s square', [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [2, 0]], 'corner'],
['a straight three', [[0, 0], [0, 1], [0, 2]], 'side'],
['a straight four', [[0, 0], [0, 1], [0, 2], [0, 3]], 'side'],
['a straight five', [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]], 'side'],
['a bulky five', [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]], 'side'],
['a pyramid four', [[0, 0], [0, 1], [0, 2], [1, 1]], 'side'],
['a rabbity six', rect(2, 3), 'side'],
['a straight six', [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5]], 'side'],
['a two-by-four', rect(2, 4), 'side'],
];
const inB = (r, c) => r >= 0 && c >= 0 && r < SIZE && c < SIZE;
const sq = (r, c) => r * SIZE + c;
function ring(set) {
// every point (8-neighbourhood) touching the set, not in it
const out = new Set();
for (const p of set) {
const r = Math.floor(p / SIZE), c = p % SIZE;
for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
const rr = r + dr, cc = c + dc;
if (!inB(rr, cc)) continue;
const q = sq(rr, cc);
if (!set.has(q)) out.add(q);
}
}
return out;
}
function build(cells, kind, def, perturb) {
const att = L.other(def);
const c0 = kind === 'side' ? 2 : 0;
const E = new Set(cells.map(([r, c]) => sq(r, c + c0)));
const Dw = ring(E);
const both = new Set([...E, ...Dw]);
const Aw = [...ring(both)];
const board = Array(SIZE * SIZE).fill(null);
for (const p of Dw) board[p] = def;
for (const p of Aw) board[p] = att;
const region = [...both];
// rough it up
const dw = [...Dw];
const eArr = [...E];
for (let i = 0; i < perturb.cutWall; i++) { const p = pick(dw); board[p] = null; }
for (let i = 0; i < perturb.inside; i++) { const p = pick(eArr); board[p] = att; }
for (let i = 0; i < perturb.helper; i++) { const p = pick(eArr); if (!board[p]) board[p] = def; }
return { size: SIZE, board, region, attacker: att };
}
function legalPosition(prob) {
const inR = new Set(prob.region);
for (const g of L.allGroups(prob.board, SIZE)) {
if (!g.libs.length) return false;
// attacker chains that reach outside must keep a liberty out there
if (g.color === prob.attacker && g.stones.some((s) => !inR.has(s)) && !g.libs.some((l) => !inR.has(l))) return false;
// defender stones only inside
if (g.color !== prob.attacker && g.stones.some((s) => !inR.has(s))) return false;
}
const defN = prob.board.filter((v, i) => v && v !== prob.attacker && inR.has(i)).length;
return defN >= 3;
}
const coord = (s) => String.fromCharCode(97 + (s % SIZE)) + String.fromCharCode(97 + Math.floor(s / SIZE));
function selfAtari(prob, s) {
const t = L.tryMove({ ...L.createGame({ size: SIZE }), board: prob.board, turn: prob.toMove, seen: [] }, s, prob.toMove);
return t.ok && t.own.libs.length === 1 && t.captured.length === 0;
}
function theme(prob, s) {
const r = Math.floor(s / SIZE), c = s % SIZE;
const t = L.tryMove({ ...L.createGame({ size: SIZE }), board: prob.board, turn: prob.toMove, seen: [] }, s, prob.toMove);
if (t.captured?.length) return 'capture';
if (selfAtari(prob, s)) return 'sacrifice';
const N = L.nbrs(SIZE)[s];
const touchOwn = N.some((q) => prob.board[q] === prob.toMove);
if (!touchOwn) return 'placement';
if (r === 0 || c === 0) return 'edge';
return 'vital point';
}
/** Play out the main line: the human's first winning move, the computer's stubbornest reply. */
function mainLine(prob, first) {
let p = T.play(prob, first);
const line = [first];
for (let i = 0; i < 14 && p; i++) {
if (T.settled(p, 'black', { maxNodes: BUDGET })) break;
const rep = T.reply(p, { maxNodes: BUDGET });
if (rep.sq === T.PASS || rep.refutes) break;
p = T.play(p, rep.sq);
line.push(rep.sq);
if (!p) break;
const w = T.winningMoves(p, { maxNodes: BUDGET }).moves.filter((m) => m !== T.PASS);
if (!w.length) break;
p = T.play(p, w[0]);
line.push(w[0]);
}
return line;
}
const out = [];
const seenKeys = new Set();
const t0 = Date.now();
let tried = 0;
const perShape = new Map();
const maxPerShape = Math.ceil(TARGET / SHAPES.length) + 6;
while (out.length < TARGET && tried < TARGET * 120) {
tried++;
const [name, cells, kind] = pick(SHAPES);
const goal = rnd() < 0.55 ? 'kill' : 'live';
const def = goal === 'kill' ? L.WHITE : L.BLACK;
const perturb = {
cutWall: Math.floor(rnd() * 3),
inside: Math.floor(rnd() * (cells.length >= 5 ? 3 : 2)),
helper: rnd() < 0.25 ? 1 : 0,
};
const shapeKey = `${name}|${kind}|${goal}`;
if ((perShape.get(shapeKey) ?? 0) >= maxPerShape) continue;
const base = build(cells, kind, def, perturb);
const prob = { ...base, toMove: L.BLACK, ko: -1 };
if (!legalPosition(prob)) continue;
const key = prob.board.map((v) => (v ? v[0] : '.')).join('') + goal;
if (seenKeys.has(key)) continue;
seenKeys.add(key);
const a = T.winningMoves(prob, { maxNodes: BUDGET, koWinner: 'attacker' });
if (a.aborted || a.limit || a.passWins || a.moves.length !== 1) continue;
const d = T.winningMoves(prob, { maxNodes: BUDGET, koWinner: 'defender' });
if (d.aborted || d.limit || d.passWins || d.moves.length !== 1 || d.moves[0] !== a.moves[0]) continue;
const first = a.moves[0];
const line = mainLine(prob, first);
const th = theme(prob, first);
const plausible = a.tried.length;
let rating = 520 + line.length * 75 + plausible * 14 + (th === 'sacrifice' ? 260 : th === 'placement' ? 150 : th === 'capture' ? -80 : 0)
+ (kind === 'side' ? 40 : 0) + perturb.inside * 40;
rating = Math.max(450, Math.min(2300, Math.round(rating / 10) * 10));
const black = [], white = [];
prob.board.forEach((v, s) => { if (v === L.BLACK) black.push(coord(s)); else if (v === L.WHITE) white.push(coord(s)); });
out.push({
goal, shape: name, kind, theme: th, rating,
b: black.join(''), w: white.join(''),
region: prob.region.map(coord).join(''),
attacker: prob.attacker,
first: coord(first),
line: line.map(coord).join(''),
});
perShape.set(shapeKey, (perShape.get(shapeKey) ?? 0) + 1);
if (out.length % 10 === 0) console.log(`${out.length} puzzles (${tried} tried, ${Math.round((Date.now() - t0) / 1000)}s)`);
}
// spread the ratings evenly over 600–1900 by rank, keeping the order
out.sort((x, y) => x.rating - y.rating || x.line.length - y.line.length);
out.forEach((p, i) => { p.rating = Math.round((600 + (1300 * i) / Math.max(1, out.length - 1)) / 10) * 10; });
// stable ids by content
const ids = new Set();
for (const p of out) {
let h = 2166136261;
for (const ch of p.b + '|' + p.w + '|' + p.goal) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619) >>> 0; }
let id = 'T' + h.toString(36).slice(0, 5).toUpperCase();
while (ids.has(id)) id += 'X';
ids.add(id);
p.id = id;
}
const here = dirname(fileURLToPath(import.meta.url));
const file = join(here, '..', 'src', 'games', 'go', 'GoPuzzleData.js');
const body = out.map((p) => ` ${JSON.stringify({ id: p.id, rating: p.rating, goal: p.goal, shape: p.shape, kind: p.kind, theme: p.theme, attacker: p.attacker, b: p.b, w: p.w, region: p.region, first: p.first, line: p.line })},`).join('\n');
writeFileSync(file, `// GoPuzzleData.js: Hōun's life-and-death problems, generated by
// tools/genGoPuzzles.js (do not edit by hand; re-run the generator).
// Points are SGF-style pairs: column letter then row letter, 'aa' top-left.
// Black always plays first. goal: 'kill' (Black attacks) or 'live'.
// region: the points either side may play. first: the one correct move.
// line: a main line (Black, White, Black, …) ending when the result is sure.
export const PUZZLE_SIZE = ${SIZE};
export const PUZZLES = [
${body}
];
`);
console.log(`wrote ${out.length} puzzles to ${file} in ${Math.round((Date.now() - t0) / 1000)}s (${tried} candidates)`);
const by = {};
for (const p of out) by[p.theme] = (by[p.theme] ?? 0) + 1;
console.log('themes', by, 'kill', out.filter((p) => p.goal === 'kill').length, 'live', out.filter((p) => p.goal === 'live').length);