fertig-classic-games/tools/genChessPuzzles.js

199 lines
8.7 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
// genChessPuzzles.js — mines original tactics puzzles for Chess ("The Stone
// Tables") from engine self-play. Nothing is copied from a puzzle site:
// games are played by ChessAI at mixed skills from book openings, and every
// position is screened for a tactic with ONE clearly best first move.
//
// mate puzzles the solver has a unique mate in 1–3 (alternative final
// mating moves are accepted by the game, so only the
// first and middle moves must be unique)
// material puzzles the best move wins ≥ 2 pawns more than any other, from
// a roughly level position, and isn't a simple recapture
//
// Each puzzle is stored Lichess-style: `fen` is the position BEFORE the
// opponent's last move, `moves` = [their move, your move, reply, your move…]
// in UCI, so the board can show how the chance arose.
//
// Usage:
// node tools/genChessPuzzles.js --seed 1 --games 60 --out /tmp/p1.json (one worker)
// node tools/genChessPuzzles.js --seed 11 --games 40 --mates --out /tmp/m11.json (mates only)
// node tools/genChessPuzzles.js --merge /tmp/p*.json (→ ChessPuzzleData.js)
import { writeFileSync, readFileSync } from 'node:fs';
import * as L from '../src/games/chess/ChessLogic.js';
import * as AI from '../src/games/chess/ChessAI.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
const arg = (k, d) => { const i = process.argv.indexOf(k); return i >= 0 ? process.argv[i + 1] : d; };
const MATE_B = AI.MATE - 512;
const MATES_ONLY = process.argv.includes('--mates'); // a mate-hunting run: mates even in won positions
function solverLine(pos, firstM, firstScore) {
// returns [uci…] for solver/opponent alternation, or null if not unique
const p = pos.clone();
const line = [L.toUci(p, firstM)];
const mate = AI.mateIn(firstScore);
L.makeMove(p, firstM);
let solverMoves = 1;
const want = mate > 0 ? mate : 3;
while (solverMoves < want) {
if (!L.hasLegalMove(p)) break;
// opponent's best defence
const rep = AI.bestMove(p, { ms: 500 });
if (!rep.m) break;
const pr = p.clone();
L.makeMove(p, rep.m);
if (!L.hasLegalMove(p)) { // defence can't leave us with nothing to do
return mate > 0 ? null : line;
}
const ranked = AI.analyze(p, { ms: 900, margin: 400 });
const best = ranked[0], second = ranked[1];
if (mate > 0) {
const left = want - solverMoves;
const mi = AI.mateIn(best.score);
if (mi <= 0 || mi > left) return null;
// the final move may have alternatives (any mate is accepted); earlier ones must be unique
if (left > 1 && second && AI.mateIn(second.score) > 0 && AI.mateIn(second.score) <= left) return null;
line.push(L.toUci(pr, rep.m), L.toUci(p, best.m));
L.makeMove(p, best.m);
solverMoves++;
continue;
}
// material: carry on only while the follow-up is clearly unique and cashes in
const fl = L.mFlags(best.m);
const unique = !second || best.score - second.score >= 200;
if (!unique || !(fl & L.F_CAP)) break;
line.push(L.toUci(pr, rep.m), L.toUci(p, best.m));
L.makeMove(p, best.m);
solverMoves++;
}
if (mate > 0 && solverMoves < want) return null;
void firstScore;
return line;
}
function themesOf(pos, line, mate) {
const t = [];
if (mate) t.push(`mateIn${mate}`);
const p = pos.clone();
const m = L.fromUci(p, line[0]);
const fl = L.mFlags(m);
if (L.mPromo(m) || line.some((u) => u.length === 5)) t.push('promotion');
const s = AI.see(p, m);
const victim = (fl & L.F_CAP) ? (fl & L.F_EP ? L.P : p.b[L.mTo(m)] & 7) : 0;
if (fl & L.F_CAP && s >= L.VALUE[victim] - 20 && victim >= L.N) t.push('hanging');
if (s < -50 && !mate) t.push('sacrifice');
if (s < -50 && mate) t.push('sacrifice');
const idea = AI.describeIdea(p, m, 300);
if (idea.startsWith('forks')) t.push('fork');
L.makeMove(p, m);
if (p.inCheck()) t.push('check');
if (!mate && !t.includes('fork') && !t.includes('hanging')) t.push('advantage');
if (line.length >= 5) t.push('long');
return t;
}
function depthToFind(pos, m) {
for (let d = 1; d <= 9; d++) {
const r = AI.bestMove(pos, { ms: 3000, depth: d });
if (r.m === m && (d >= 2 || AI.mateIn(r.score) === 1)) return d;
}
return 10;
}
function worker() {
const seed = +arg('--seed', 1), games = +arg('--games', 40), out = arg('--out', `/tmp/chess-puzzles-${seed}.json`);
const rng = mulberry32(seed * 7919);
const found = [];
const seen = new Set();
for (let gi = 0; gi < games; gi++) {
const g = new L.Chess();
const sw = 1 + Math.floor(rng() * 4), sb = 1 + Math.floor(rng() * 4);
let perGame = 0, cool = 0;
while (!g.status() && g.ply < 160) {
// screen positions after the opening, before each side moves
if (cool > 0) cool--;
else if (g.ply >= 12 && perGame < 2 && g.history.length) {
const pos = g.pos;
const quick = AI.bestMove(pos, { ms: 60 });
const prevM = g.history[g.history.length - 1];
const lastWasCapture = !!prevM.captured;
const qm = AI.mateIn(quick.score);
const promising = (qm > 0 && qm <= 3) || (!MATES_ONLY && quick.score >= 220);
if (promising) {
// level-ish before? (the side to move shouldn't already be miles ahead)
const ranked = AI.analyze(pos, { ms: 1200, margin: 400 });
const best = ranked[0], second = ranked[1];
const mate = AI.mateIn(best.score);
let take = false;
const fl = L.mFlags(best.m);
const recapture = lastWasCapture && (fl & L.F_CAP) && L.to64(L.mTo(best.m)) === prevM.to;
if (recapture) take = false;
else if (mate > 0 && mate <= 3) {
const altMate = second && AI.mateIn(second.score) > 0 && AI.mateIn(second.score) <= mate;
take = !altMate && (MATES_ONLY || !second || second.score <= 900);
} else if (!MATES_ONLY && best.score >= 220 && best.score < MATE_B && second && best.score - second.score >= 220 && second.score <= 120 && second.score >= -350) {
take = true;
}
if (take) {
const line = solverLine(pos, best.m, best.score);
const key = L.toFen(pos, { clocks: false });
if (line && !seen.has(key)) {
seen.add(key);
// the position before the opponent's last move
const before = g.after(g.ply - 1);
const themes = themesOf(pos, line, mate > 0 ? mate : 0);
const d = depthToFind(pos, best.m);
const solverN = Math.ceil(line.length / 2);
let rating = 600 + d * 140 + (solverN - 1) * 120 + (themes.includes('sacrifice') ? 150 : 0) - (themes.includes('hanging') ? 150 : 0);
if (mate === 1) rating = 600 + d * 60;
rating = Math.max(500, Math.min(2300, Math.round(rating / 10) * 10));
found.push({ fen: before.fen(), moves: [prevM.uci, ...line], rating, themes, mate: mate > 0 ? mate : 0 });
perGame++;
cool = 12;
process.stderr.write(`[seed ${seed}] game ${gi} ply ${g.ply}: ${themes.join(',')} r${rating} (${found.length})\n`);
}
}
}
}
const c = AI.chooseMove(g, g.turn === 'w' ? sw : sb, { ms: 80, rng });
if (!c) break;
g.move(c.m);
}
writeFileSync(out, JSON.stringify(found));
}
writeFileSync(out, JSON.stringify(found));
}
function merge(files) {
const all = [];
const seen = new Set();
for (const f of files) {
for (const p of JSON.parse(readFileSync(f, 'utf8'))) {
const k = p.fen.split(' ').slice(0, 4).join(' ') + p.moves[0];
if (seen.has(k)) continue;
seen.add(k);
all.push(p);
}
}
all.sort((a, b) => a.rating - b.rating || a.fen.localeCompare(b.fen));
all.forEach((p, i) => { p.id = `st${String(i + 1).padStart(3, '0')}`; });
const body = all.map((p) => ` { id: '${p.id}', fen: '${p.fen}', moves: '${p.moves.join(' ')}', rating: ${p.rating}, themes: '${p.themes.join(' ')}' },`).join('\n');
const src = `// ChessPuzzleData.js — GENERATED by tools/genChessPuzzles.js. Do not edit by hand.
// ${all.length} original tactics mined from engine self-play at the Stone Tables.
// fen: the position before the opponent's last move; moves (UCI): that move,
// then the solution (yours, their reply, yours…). Sorted by rating.
export const PUZZLES = [
${body}
];
`;
writeFileSync(new URL('../src/games/chess/ChessPuzzleData.js', import.meta.url), src);
const byTheme = {};
for (const p of all) for (const t of p.themes) byTheme[t] = (byTheme[t] ?? 0) + 1;
console.log(`${all.length} puzzles`, byTheme);
}
if (process.argv.includes('--merge')) merge(process.argv.slice(process.argv.indexOf('--merge') + 1));
else worker();