671 lines
29 KiB
JavaScript
671 lines
29 KiB
JavaScript
// ChessAI.js — the engine behind every opponent at the Stone Tables.
|
||
//
|
||
// Negamax / principal-variation search on ChessLogic's 0x88 position with
|
||
// make/unmake; iterative deepening inside a time budget; a transposition
|
||
// table; quiescence search with static exchange (SEE) pruning; killer and
|
||
// history move ordering; null-move pruning, late-move reductions, reverse
|
||
// futility pruning and check extensions; a tapered evaluation (material,
|
||
// piece-square tables, pawn structure, passed pawns, king shelter, mobility,
|
||
// bishop pair, rooks on open files, mop-up for won endgames).
|
||
//
|
||
// Skill 1..5 shapes the time/depth budget, scoring noise, and how often the
|
||
// opponent "slips" to a weaker candidate — so a rookie hangs pieces and a
|
||
// shark plays like a strong club player (~1800–2000 at the top).
|
||
//
|
||
// API
|
||
// chooseMove(game, skill, { ms, rng }) → { m, score, book, opening }
|
||
// bestMove(pos, { ms, depth }) → { m, score, depth, pv }
|
||
// analyze(pos, { ms, depth, margin }) → [{ m, score }] best first
|
||
// evaluateWhite(pos, { ms }) → centipawns from White's side
|
||
// describeIdea(pos, m, score) → a short plain-English reason
|
||
// wantsDraw / drawDecision / shouldResign → the opponent's table manners
|
||
|
||
import * as L from './ChessLogic.js';
|
||
import { bookMoves } from './ChessBook.js';
|
||
|
||
const { P, N, B, R, Q, K, WHITE, BLACK } = L;
|
||
export const MATE = 30000;
|
||
const MATE_BOUND = MATE - 512;
|
||
const INF = 32000;
|
||
|
||
export const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3)));
|
||
|
||
export const PROFILES = {
|
||
1: { ms: 120, depth: 2, noise: 150, slip: 0.30, topN: 6, wild: 0.08, bookPly: 4 },
|
||
2: { ms: 220, depth: 3, noise: 70, slip: 0.16, topN: 4, wild: 0.02, bookPly: 6 },
|
||
3: { ms: 450, depth: 5, noise: 32, slip: 0.07, topN: 3, wild: 0, bookPly: 10 },
|
||
4: { ms: 900, depth: 8, noise: 12, slip: 0.025, topN: 2, wild: 0, bookPly: 16 },
|
||
5: { ms: 1500, depth: 64, noise: 0, slip: 0, topN: 1, wild: 0, bookPly: 24 },
|
||
};
|
||
export const profileOf = (skill) => PROFILES[clampSkill(skill)];
|
||
|
||
// ── evaluation ─────────────────────────────────────────────────────────────
|
||
const MG_VAL = [0, 90, 320, 335, 480, 950, 0];
|
||
const EG_VAL = [0, 115, 300, 320, 530, 980, 0];
|
||
const PHASE_W = [0, 0, 1, 1, 2, 4, 0];
|
||
|
||
// tables from White's point of view, row 0 = rank 8
|
||
const T = (rows) => {
|
||
const t = new Int16Array(128);
|
||
for (let r = 0; r < 8; r++) for (let f = 0; f < 8; f++) t[r * 16 + f] = rows[r][f];
|
||
return t;
|
||
};
|
||
const PST_MG = [null,
|
||
T([[0, 0, 0, 0, 0, 0, 0, 0], [50, 50, 50, 50, 50, 50, 50, 50], [10, 10, 20, 30, 30, 20, 10, 10], [5, 5, 10, 25, 25, 10, 5, 5],
|
||
[0, 0, 0, 22, 22, 0, 0, 0], [5, -5, -10, 2, 2, -10, -5, 5], [5, 10, 10, -22, -22, 10, 10, 5], [0, 0, 0, 0, 0, 0, 0, 0]]),
|
||
T([[-50, -40, -30, -30, -30, -30, -40, -50], [-40, -20, 0, 0, 0, 0, -20, -40], [-30, 0, 10, 15, 15, 10, 0, -30], [-30, 5, 15, 20, 20, 15, 5, -30],
|
||
[-30, 0, 15, 20, 20, 15, 0, -30], [-30, 5, 10, 15, 15, 10, 5, -30], [-40, -20, 0, 5, 5, 0, -20, -40], [-50, -35, -30, -30, -30, -30, -35, -50]]),
|
||
T([[-20, -10, -10, -10, -10, -10, -10, -20], [-10, 0, 0, 0, 0, 0, 0, -10], [-10, 0, 5, 10, 10, 5, 0, -10], [-10, 5, 5, 10, 10, 5, 5, -10],
|
||
[-10, 0, 10, 10, 10, 10, 0, -10], [-10, 10, 10, 10, 10, 10, 10, -10], [-10, 8, 0, 0, 0, 0, 8, -10], [-20, -10, -12, -10, -10, -12, -10, -20]]),
|
||
T([[0, 0, 0, 0, 0, 0, 0, 0], [5, 10, 10, 10, 10, 10, 10, 5], [-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5],
|
||
[-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5], [0, 0, 0, 5, 5, 3, 0, 0]]),
|
||
T([[-20, -10, -10, -5, -5, -10, -10, -20], [-10, 0, 0, 0, 0, 0, 0, -10], [-10, 0, 5, 5, 5, 5, 0, -10], [-5, 0, 5, 5, 5, 5, 0, -5],
|
||
[0, 0, 5, 5, 5, 5, 0, -5], [-10, 5, 5, 5, 5, 5, 0, -10], [-10, 0, 5, 0, 0, 0, 0, -10], [-20, -10, -10, -5, -5, -10, -10, -20]]),
|
||
T([[-30, -40, -40, -50, -50, -40, -40, -30], [-30, -40, -40, -50, -50, -40, -40, -30], [-30, -40, -40, -50, -50, -40, -40, -30], [-30, -40, -40, -50, -50, -40, -40, -30],
|
||
[-20, -30, -30, -40, -40, -30, -30, -20], [-10, -20, -20, -20, -20, -20, -20, -10], [20, 20, -5, -5, -5, -5, 20, 20], [20, 30, 10, 0, 0, 10, 30, 20]]),
|
||
];
|
||
const PST_EG = [null,
|
||
T([[0, 0, 0, 0, 0, 0, 0, 0], [80, 80, 80, 80, 80, 80, 80, 80], [50, 50, 50, 50, 50, 50, 50, 50], [30, 30, 30, 30, 30, 30, 30, 30],
|
||
[15, 15, 15, 15, 15, 15, 15, 15], [5, 5, 5, 5, 5, 5, 5, 5], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]),
|
||
PST_MG[2], PST_MG[3],
|
||
T([[0, 0, 0, 0, 0, 0, 0, 0], [5, 5, 5, 5, 5, 5, 5, 5], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
|
||
[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]),
|
||
PST_MG[5],
|
||
T([[-50, -40, -30, -20, -20, -30, -40, -50], [-30, -20, -10, 0, 0, -10, -20, -30], [-30, -10, 20, 30, 30, 20, -10, -30], [-30, -10, 30, 40, 40, 30, -10, -30],
|
||
[-30, -10, 30, 40, 40, 30, -10, -30], [-30, -10, 20, 30, 30, 20, -10, -30], [-30, -30, 0, 0, 0, 0, -30, -30], [-50, -30, -30, -30, -30, -30, -30, -50]]),
|
||
];
|
||
const PASS_MG = [0, 5, 10, 15, 25, 40, 60, 0];
|
||
const PASS_EG = [0, 10, 20, 35, 60, 100, 150, 0];
|
||
const KN_D = [-33, -31, -18, -14, 14, 18, 31, 33];
|
||
const BI_D = [-17, -15, 15, 17];
|
||
const RO_D = [-16, -1, 1, 16];
|
||
|
||
const wMax = new Int8Array(10), bMin = new Int8Array(10), wCnt = new Int8Array(10), bCnt = new Int8Array(10);
|
||
|
||
/** Static evaluation from the side to move's point of view. */
|
||
export function evaluate(pos) {
|
||
const b = pos.b;
|
||
let mg = 0, eg = 0, phase = 0;
|
||
let wb = 0, bb = 0, wMat = 0, bMat = 0, wPieces = 0, bPieces = 0;
|
||
wMax.fill(-1); bMin.fill(8); wCnt.fill(0); bCnt.fill(0);
|
||
// pass 1: pawns per file
|
||
for (let s = 0; s < 128; s++) {
|
||
if (s & 0x88) { s += 7; continue; }
|
||
const p = b[s];
|
||
if ((p & 7) !== P) continue;
|
||
const f = (s & 7) + 1, r = s >> 4;
|
||
if (p === P) { wCnt[f]++; if (r > wMax[f]) wMax[f] = r; } else { bCnt[f]++; if (r < bMin[f]) bMin[f] = r; }
|
||
}
|
||
for (let s = 0; s < 128; s++) {
|
||
if (s & 0x88) { s += 7; continue; }
|
||
const p = b[s];
|
||
if (!p) continue;
|
||
const t = p & 7, white = p < 8;
|
||
const r = s >> 4, f = s & 7;
|
||
const idx = white ? s : ((7 - r) << 4) | f;
|
||
let m = MG_VAL[t] + PST_MG[t][idx], e = EG_VAL[t] + PST_EG[t][idx];
|
||
phase += PHASE_W[t];
|
||
if (t === P) {
|
||
const F = f + 1;
|
||
if (white) {
|
||
if (wCnt[F] > 1) { m -= 10; e -= 18; }
|
||
if (!wCnt[F - 1] && !wCnt[F + 1]) { m -= 12; e -= 14; }
|
||
if (bMin[F - 1] >= r && bMin[F] >= r && bMin[F + 1] >= r) { const rr = 7 - r; m += PASS_MG[rr]; e += PASS_EG[rr]; }
|
||
} else {
|
||
if (bCnt[F] > 1) { m -= 10; e -= 18; }
|
||
if (!bCnt[F - 1] && !bCnt[F + 1]) { m -= 12; e -= 14; }
|
||
if (wMax[F - 1] <= r && wMax[F] <= r && wMax[F + 1] <= r) { const rr = r; m += PASS_MG[rr]; e += PASS_EG[rr]; }
|
||
}
|
||
} else if (t === N) {
|
||
let mob = 0;
|
||
for (let i = 0; i < 8; i++) { const d = s + KN_D[i]; if (!(d & 0x88)) { const q = b[d]; if (!q || (q < 8) !== white) mob++; } }
|
||
m += (mob - 4) * 4; e += (mob - 4) * 4;
|
||
} else if (t === B || t === R || t === Q) {
|
||
if (t === B) { if (white) wb++; else bb++; }
|
||
const D = t === B ? BI_D : RO_D;
|
||
let mob = 0;
|
||
if (t !== Q) {
|
||
for (let i = 0; i < 4; i++) {
|
||
const dd = D[i];
|
||
let d = s + dd;
|
||
while (!(d & 0x88)) { const q = b[d]; if (!q) mob++; else { if ((q < 8) !== white) mob++; break; } d += dd; }
|
||
}
|
||
if (t === B) { m += (mob - 6) * 4; e += (mob - 6) * 5; } else { m += (mob - 6) * 2; e += (mob - 6) * 4; }
|
||
}
|
||
if (t === R) {
|
||
const F = f + 1;
|
||
const own = white ? wCnt[F] : bCnt[F], opp = white ? bCnt[F] : wCnt[F];
|
||
if (!own) { if (!opp) { m += 22; e += 10; } else { m += 10; e += 5; } }
|
||
if ((white && r === 1) || (!white && r === 6)) { m += 10; e += 18; }
|
||
}
|
||
} else if (t === K) {
|
||
// pawn shelter in front of a castled-looking king
|
||
const dir = white ? -16 : 16;
|
||
let sh = 0;
|
||
for (let df = -1; df <= 1; df++) {
|
||
const c = s + dir + df;
|
||
if (c & 0x88) continue;
|
||
if (b[c] === (white ? P : P | 8)) sh += 12;
|
||
else if (!((c + dir) & 0x88) && b[c + dir] === (white ? P : P | 8)) sh += 6;
|
||
else sh -= 8;
|
||
}
|
||
m += sh;
|
||
}
|
||
if (t !== P && t !== K) { if (white) { wMat += MG_VAL[t]; wPieces++; } else { bMat += MG_VAL[t]; bPieces++; } }
|
||
if (white) { mg += m; eg += e; } else { mg -= m; eg -= e; }
|
||
}
|
||
if (wb >= 2) { mg += 30; eg += 45; }
|
||
if (bb >= 2) { mg -= 30; eg -= 45; }
|
||
if (phase > 24) phase = 24;
|
||
let score = Math.round((mg * phase + eg * (24 - phase)) / 24);
|
||
// mop-up: drive a lone king to the edge and walk ours over
|
||
const diff = wMat - bMat;
|
||
if (phase <= 8 && Math.abs(diff) >= 300) {
|
||
const strong = diff > 0 ? WHITE : BLACK;
|
||
const weakK = pos.kings[strong ^ 1], strongK = pos.kings[strong];
|
||
const wr = weakK >> 4, wf = weakK & 7, sr = strongK >> 4, sf = strongK & 7;
|
||
const centre = Math.max(3 - wr, wr - 4) + Math.max(3 - wf, wf - 4);
|
||
const dist = Math.abs(wr - sr) + Math.abs(wf - sf);
|
||
const bonus = centre * 12 + (14 - dist) * 5;
|
||
score += strong === WHITE ? bonus : -bonus;
|
||
}
|
||
// a minor piece up with no pawns can't win
|
||
if (!wCnt.some((x) => x) && wMat - bMat < 400 && wMat <= 335 + 0 && score > 0) score >>= 3;
|
||
if (!bCnt.some((x) => x) && bMat - wMat < 400 && bMat <= 335 && score < 0) score >>= 3;
|
||
void wPieces; void bPieces;
|
||
score += pos.side === WHITE ? 10 : -10;
|
||
return pos.side === WHITE ? score : -score;
|
||
}
|
||
|
||
// ── static exchange evaluation ─────────────────────────────────────────────
|
||
const SEE_VAL = [0, 100, 320, 330, 500, 900, 20000];
|
||
function leastAttacker(pos, sq, side) {
|
||
const att = L.attackersOf(pos, sq, side);
|
||
let best = -1, bv = 1e9;
|
||
for (const s of att) { const v = SEE_VAL[pos.b[s] & 7]; if (v < bv) { bv = v; best = s; } }
|
||
return best;
|
||
}
|
||
/** Material balance (for the mover) of the capture sequence on the move's target. */
|
||
export function see(pos, m) {
|
||
const from = m & 127, to = (m >> 7) & 127, fl = (m >> 17) & 15, promo = (m >> 14) & 7;
|
||
if (fl & L.F_CASTLE) return 0;
|
||
const b = pos.b;
|
||
const saved = [];
|
||
const set = (s, v) => { saved.push(s, b[s]); b[s] = v; };
|
||
let side = pos.side;
|
||
const gain = [SEE_VAL[(fl & L.F_EP) ? P : (b[to] & 7)]];
|
||
const mover = b[from];
|
||
let onSq = promo || (mover & 7);
|
||
if (fl & L.F_EP) set(to + (side === WHITE ? 16 : -16), 0);
|
||
set(to, promo ? (promo | (side << 3)) : mover);
|
||
set(from, 0);
|
||
let d = 0;
|
||
for (;;) {
|
||
side ^= 1;
|
||
const a = leastAttacker(pos, to, side);
|
||
if (a < 0) break;
|
||
d++;
|
||
gain[d] = SEE_VAL[onSq] - gain[d - 1];
|
||
if (Math.max(-gain[d - 1], gain[d]) < 0) break;
|
||
onSq = b[a] & 7;
|
||
set(to, b[a]);
|
||
set(a, 0);
|
||
}
|
||
while (d > 0) { gain[d - 1] = -Math.max(-gain[d - 1], gain[d]); d--; }
|
||
for (let i = saved.length - 2; i >= 0; i -= 2) b[saved[i]] = saved[i + 1];
|
||
return gain[0];
|
||
}
|
||
|
||
// ── transposition table ────────────────────────────────────────────────────
|
||
const TT_BITS = 20, TT_SIZE = 1 << TT_BITS, TT_MASK = TT_SIZE - 1;
|
||
const ttKey = new Int32Array(TT_SIZE), ttMove = new Int32Array(TT_SIZE), ttScore = new Int16Array(TT_SIZE);
|
||
const ttDepth = new Int8Array(TT_SIZE), ttFlag = new Uint8Array(TT_SIZE);
|
||
const EXACT = 1, LOWER = 2, UPPER = 3;
|
||
export function clearTT() { ttKey.fill(0); ttMove.fill(0); ttFlag.fill(0); }
|
||
function ttStore(pos, depth, score, flag, move, ply) {
|
||
const i = pos.lo & TT_MASK;
|
||
if (ttFlag[i] && ttKey[i] === pos.hi && ttDepth[i] > depth && flag !== EXACT) return;
|
||
if (score > MATE_BOUND) score += ply; else if (score < -MATE_BOUND) score -= ply;
|
||
ttKey[i] = pos.hi; ttMove[i] = move; ttScore[i] = score; ttDepth[i] = depth; ttFlag[i] = flag;
|
||
}
|
||
|
||
// ── search ─────────────────────────────────────────────────────────────────
|
||
class Searcher {
|
||
constructor(pos, { ms = 1000, depth = 64, rootFilter = null } = {}) {
|
||
this.pos = pos;
|
||
this.deadline = Date.now() + ms;
|
||
this.maxDepth = depth;
|
||
this.nodes = 0;
|
||
this.stop = false;
|
||
this.killers = new Int32Array(256);
|
||
this.history = new Int32Array(16 * 128);
|
||
this.rootFilter = rootFilter;
|
||
}
|
||
|
||
timeUp() {
|
||
if ((++this.nodes & 1023) === 0 && Date.now() > this.deadline) this.stop = true;
|
||
return this.stop;
|
||
}
|
||
|
||
isDraw(ply) {
|
||
const pos = this.pos;
|
||
if (pos.half >= 100) return true;
|
||
const Lh = pos.histLo.length;
|
||
const lim = Math.max(0, Lh - pos.half);
|
||
for (let i = Lh - 2; i >= lim; i -= 2) {
|
||
if (pos.histLo[i] === pos.lo && pos.histHi[i] === pos.hi) return true;
|
||
}
|
||
void ply;
|
||
return L.insufficientMaterial(pos);
|
||
}
|
||
|
||
scoreMoves(moves, ttm, ply) {
|
||
const b = this.pos.b;
|
||
const scores = new Int32Array(moves.length);
|
||
const k0 = this.killers[ply * 2], k1 = this.killers[ply * 2 + 1];
|
||
for (let i = 0; i < moves.length; i++) {
|
||
const m = moves[i];
|
||
if (m === ttm) { scores[i] = 2e9; continue; }
|
||
const fl = (m >> 17) & 15, to = (m >> 7) & 127, from = m & 127;
|
||
const promo = (m >> 14) & 7;
|
||
if (fl & L.F_CAP) {
|
||
const v = (fl & L.F_EP) ? P : (b[to] & 7);
|
||
scores[i] = 1e8 + SEE_VAL[v] * 10 - SEE_VAL[b[from] & 7] / 10 + (promo === Q ? 5e6 : 0);
|
||
} else if (promo) scores[i] = promo === Q ? 9e7 : -1e6;
|
||
else if (m === k0) scores[i] = 8e7;
|
||
else if (m === k1) scores[i] = 7e7;
|
||
else scores[i] = this.history[b[from] * 128 + to];
|
||
}
|
||
return scores;
|
||
}
|
||
|
||
qsearch(alpha, beta, ply) {
|
||
if (this.timeUp()) return 0;
|
||
const pos = this.pos;
|
||
const stand = evaluate(pos);
|
||
if (stand >= beta) return stand;
|
||
if (stand > alpha) alpha = stand;
|
||
if (ply > 60) return stand;
|
||
const moves = L.genMoves(pos, [], true);
|
||
const scores = this.scoreMoves(moves, 0, Math.min(ply, 127));
|
||
for (let i = 0; i < moves.length; i++) {
|
||
let bi = i;
|
||
for (let j = i + 1; j < moves.length; j++) if (scores[j] > scores[bi]) bi = j;
|
||
const m = moves[bi]; moves[bi] = moves[i]; moves[i] = m;
|
||
const sc = scores[bi]; scores[bi] = scores[i]; scores[i] = sc;
|
||
const fl = (m >> 17) & 15, promo = (m >> 14) & 7;
|
||
if (fl & L.F_CAP && !promo) {
|
||
const v = (fl & L.F_EP) ? P : (pos.b[(m >> 7) & 127] & 7);
|
||
if (stand + SEE_VAL[v] + 200 < alpha) continue; // delta pruning
|
||
if (see(pos, m) < 0) continue; // losing capture
|
||
} else if (promo && promo !== Q) continue;
|
||
if (!L.makeMove(pos, m)) continue;
|
||
const s = -this.qsearch(-beta, -alpha, ply + 1);
|
||
L.unmakeMove(pos);
|
||
if (this.stop) return 0;
|
||
if (s > alpha) { alpha = s; if (s >= beta) return s; }
|
||
}
|
||
return alpha;
|
||
}
|
||
|
||
search(depth, alpha, beta, ply, nullOk = true) {
|
||
const pos = this.pos;
|
||
if (this.timeUp()) return 0;
|
||
if (ply > 0) {
|
||
if (this.isDraw(ply)) return 0;
|
||
// mate-distance pruning
|
||
const ma = -MATE + ply, mb = MATE - ply - 1;
|
||
if (ma > alpha) alpha = ma;
|
||
if (mb < beta) beta = mb;
|
||
if (alpha >= beta) return alpha;
|
||
}
|
||
const inCheck = pos.inCheck();
|
||
if (inCheck && ply < 60) depth++;
|
||
if (depth <= 0) return this.qsearch(alpha, beta, ply);
|
||
const pv = beta - alpha > 1;
|
||
// transposition table
|
||
const ti = pos.lo & TT_MASK;
|
||
let ttm = 0;
|
||
if (ttFlag[ti] && ttKey[ti] === pos.hi) {
|
||
ttm = ttMove[ti];
|
||
if (ply > 0 && ttDepth[ti] >= depth && !pv) {
|
||
let s = ttScore[ti];
|
||
if (s > MATE_BOUND) s -= ply; else if (s < -MATE_BOUND) s += ply;
|
||
const f = ttFlag[ti];
|
||
if (f === EXACT || (f === LOWER && s >= beta) || (f === UPPER && s <= alpha)) return s;
|
||
}
|
||
}
|
||
let staticEval = 0;
|
||
if (!pv && !inCheck) {
|
||
staticEval = evaluate(pos);
|
||
// reverse futility
|
||
if (depth <= 3 && staticEval - 110 * depth >= beta && Math.abs(beta) < MATE_BOUND) return staticEval;
|
||
// null move
|
||
if (nullOk && depth >= 3 && staticEval >= beta && this.hasPieces(pos.side)) {
|
||
const r = depth >= 6 ? 3 : 2;
|
||
L.makeNull(pos);
|
||
const s = -this.search(depth - 1 - r, -beta, -beta + 1, ply + 1, false);
|
||
L.unmakeNull(pos);
|
||
if (this.stop) return 0;
|
||
if (s >= beta) return Math.abs(s) > MATE_BOUND ? beta : s;
|
||
}
|
||
}
|
||
const moves = L.genMoves(pos, []);
|
||
let filter = null;
|
||
if (ply === 0 && this.rootFilter) filter = this.rootFilter;
|
||
const scores = this.scoreMoves(moves, ttm, ply);
|
||
let legal = 0, best = -INF, bestMove = 0;
|
||
const a0 = alpha;
|
||
for (let i = 0; i < moves.length; i++) {
|
||
let bi = i;
|
||
for (let j = i + 1; j < moves.length; j++) if (scores[j] > scores[bi]) bi = j;
|
||
const m = moves[bi]; moves[bi] = moves[i]; moves[i] = m;
|
||
const sc = scores[bi]; scores[bi] = scores[i]; scores[i] = sc;
|
||
if (filter && !filter.has(m)) continue;
|
||
const fl = (m >> 17) & 15;
|
||
const quiet = !(fl & L.F_CAP) && !((m >> 14) & 7);
|
||
// futility at the frontier for quiet moves
|
||
if (!pv && !inCheck && quiet && depth === 1 && legal > 0 && staticEval + 150 < alpha) {
|
||
if (!L.makeMove(pos, m)) continue;
|
||
const gc = pos.inCheck();
|
||
L.unmakeMove(pos);
|
||
if (!gc) { legal++; continue; }
|
||
}
|
||
if (!L.makeMove(pos, m)) continue;
|
||
legal++;
|
||
const givesCheck = pos.inCheck();
|
||
let s;
|
||
if (legal === 1) s = -this.search(depth - 1, -beta, -alpha, ply + 1);
|
||
else {
|
||
let red = 0;
|
||
if (depth >= 3 && legal > 3 && quiet && !inCheck && !givesCheck && m !== this.killers[ply * 2] && m !== this.killers[ply * 2 + 1]) {
|
||
red = 1 + (legal > 8 ? 1 : 0) + (depth >= 8 && legal > 16 ? 1 : 0);
|
||
if (pv) red = Math.max(0, red - 1);
|
||
}
|
||
s = -this.search(depth - 1 - red, -alpha - 1, -alpha, ply + 1);
|
||
if (!this.stop && s > alpha && red) s = -this.search(depth - 1, -alpha - 1, -alpha, ply + 1);
|
||
if (!this.stop && s > alpha && s < beta) s = -this.search(depth - 1, -beta, -alpha, ply + 1);
|
||
}
|
||
L.unmakeMove(pos);
|
||
if (this.stop) return 0;
|
||
if (ply === 0 && this.rootScores) this.rootScores.set(m, s);
|
||
if (s > best) {
|
||
best = s; bestMove = m;
|
||
if (s > alpha) {
|
||
alpha = s;
|
||
if (ply === 0) { this.rootBest = m; this.rootBestScore = s; }
|
||
if (s >= beta) {
|
||
if (quiet) {
|
||
if (this.killers[ply * 2] !== m) { this.killers[ply * 2 + 1] = this.killers[ply * 2]; this.killers[ply * 2] = m; }
|
||
const hi = pos.b[m & 127] * 128 + ((m >> 7) & 127);
|
||
this.history[hi] += depth * depth;
|
||
if (this.history[hi] > 1e6) for (let k = 0; k < this.history.length; k++) this.history[k] >>= 1;
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if (!legal) return inCheck ? -MATE + ply : 0;
|
||
ttStore(pos, depth, best, best >= beta ? LOWER : best > a0 ? EXACT : UPPER, bestMove, ply);
|
||
return best;
|
||
}
|
||
|
||
hasPieces(side) {
|
||
const b = this.pos.b;
|
||
for (let s = 0; s < 128; s++) {
|
||
if (s & 0x88) { s += 7; continue; }
|
||
const p = b[s];
|
||
if (p && (p >> 3) === side) { const t = p & 7; if (t !== P && t !== K) return true; }
|
||
}
|
||
return false;
|
||
}
|
||
|
||
pv(first, n = 8) {
|
||
const pos = this.pos;
|
||
const line = [];
|
||
let m = first;
|
||
let made = 0;
|
||
while (m && line.length < n) {
|
||
const legal = L.legalMoves(pos);
|
||
if (!legal.includes(m)) break;
|
||
line.push(m);
|
||
L.makeMove(pos, m); made++;
|
||
const i = pos.lo & TT_MASK;
|
||
m = ttFlag[i] && ttKey[i] === pos.hi ? ttMove[i] : 0;
|
||
}
|
||
while (made--) L.unmakeMove(pos);
|
||
return line;
|
||
}
|
||
}
|
||
|
||
/** Iterative deepening; returns { m, score, depth, pv, nodes }. */
|
||
export function bestMove(pos, { ms = 1000, depth = 64, minDepth = 1 } = {}) {
|
||
const p = pos.clone();
|
||
const S = new Searcher(p, { ms, depth });
|
||
const legal = L.legalMoves(p);
|
||
if (!legal.length) return { m: 0, score: p.inCheck() ? -MATE : 0, depth: 0, pv: [], nodes: 0 };
|
||
let best = legal[0], bestScore = 0, done = 0;
|
||
let prev = 0;
|
||
for (let d = 1; d <= depth; d++) {
|
||
S.rootBest = 0;
|
||
let s;
|
||
if (d >= 4 && Math.abs(prev) < MATE_BOUND) {
|
||
let lo = prev - 40, hi = prev + 40;
|
||
s = S.search(d, lo, hi, 0);
|
||
if (!S.stop && (s <= lo || s >= hi)) { S.rootBest = 0; s = S.search(d, -INF, INF, 0); }
|
||
} else s = S.search(d, -INF, INF, 0);
|
||
if (S.stop && d > minDepth) {
|
||
// a partial iteration that already found a better move is still usable
|
||
if (S.rootBest && S.rootBestScore > bestScore && done) { best = S.rootBest; bestScore = S.rootBestScore; }
|
||
break;
|
||
}
|
||
if (S.rootBest) { best = S.rootBest; bestScore = s; }
|
||
prev = s; done = d;
|
||
if (Math.abs(s) > MATE_BOUND && d > 2 && MATE - Math.abs(s) <= d) break;
|
||
if (legal.length === 1 && d >= 2) break;
|
||
if (S.stop) { S.stop = false; S.deadline = 0; break; }
|
||
}
|
||
return { m: best, score: bestScore, depth: done, pv: S.pv(best), nodes: S.nodes };
|
||
}
|
||
|
||
/**
|
||
* Scores for every root move (best first). Moves within `margin` of the best
|
||
* are scored exactly; the rest are known to be at least `margin` worse.
|
||
*/
|
||
export function analyze(pos, { ms = 500, depth = 64, margin = 250 } = {}) {
|
||
const p = pos.clone();
|
||
const legal = L.legalMoves(p);
|
||
if (!legal.length) return [];
|
||
const S = new Searcher(p, { ms, depth });
|
||
let result = legal.map((m) => ({ m, score: 0 }));
|
||
for (let d = 1; d <= depth; d++) {
|
||
const order = result.map((r) => r.m);
|
||
const scores = new Map();
|
||
let best = -INF;
|
||
let complete = true;
|
||
for (const m of order) {
|
||
L.makeMove(p, m);
|
||
const lo = best === -INF ? -INF : best - margin;
|
||
const s = -S.search(d - 1, -INF, -lo, 1);
|
||
L.unmakeMove(p);
|
||
if (S.stop) { complete = false; break; }
|
||
scores.set(m, s);
|
||
if (s > best) best = s;
|
||
}
|
||
if (!complete && d > 1) break;
|
||
if (scores.size) {
|
||
result = order.map((m) => ({ m, score: scores.has(m) ? scores.get(m) : -INF })).sort((a, b) => b.score - a.score);
|
||
}
|
||
if (!complete) break;
|
||
if (Math.abs(result[0].score) > MATE_BOUND && d > 2) break;
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/** Centipawns from White's point of view after a short search. */
|
||
export function evaluateWhite(pos, { ms = 120, depth = 64 } = {}) {
|
||
const r = bestMove(pos, { ms, depth });
|
||
let s = r.score;
|
||
if (!r.m) s = pos.inCheck() ? -MATE : 0;
|
||
return pos.side === WHITE ? s : -s;
|
||
}
|
||
|
||
export function mateIn(score) {
|
||
if (Math.abs(score) <= MATE_BOUND) return 0;
|
||
const plies = MATE - Math.abs(score);
|
||
return Math.sign(score) * Math.ceil(plies / 2);
|
||
}
|
||
|
||
// ── choosing a move at a skill level ───────────────────────────────────────
|
||
/**
|
||
* game: a ChessLogic.Chess. Returns { m, score, book, rich }.
|
||
* opts.ms overrides the profile's thinking budget (for clocks).
|
||
*/
|
||
export function chooseMove(game, skill, { ms = null, rng = Math.random } = {}) {
|
||
const prof = profileOf(skill);
|
||
const pos = game.pos;
|
||
const legal = L.legalMoves(pos);
|
||
if (!legal.length) return null;
|
||
// the book
|
||
if (game.startFen === L.START_FEN && game.ply < prof.bookPly) {
|
||
const opts = bookMoves(game);
|
||
if (opts.length && rng() < (skill >= 2 ? 0.95 : 0.6)) {
|
||
const total = opts.reduce((a, o) => a + o.w, 0);
|
||
let x = rng() * total;
|
||
for (const o of opts) { x -= o.w; if (x <= 0) return { m: o.m, score: 0, book: true }; }
|
||
return { m: opts[0].m, score: 0, book: true };
|
||
}
|
||
}
|
||
const budget = ms ?? prof.ms;
|
||
// the occasional wild move (rookies)
|
||
if (prof.wild && rng() < prof.wild) {
|
||
return { m: legal[Math.floor(rng() * legal.length)], score: 0, book: false, wild: true };
|
||
}
|
||
if (prof.topN === 1) {
|
||
const r = bestMove(pos, { ms: budget, depth: prof.depth });
|
||
return { m: r.m, score: r.score, book: false, depth: r.depth };
|
||
}
|
||
const ranked = analyze(pos, { ms: budget, depth: prof.depth, margin: Math.max(80, prof.noise * 3) });
|
||
// never miss a forced mate or walk into one when there's a sane choice
|
||
const bestS = ranked[0].score;
|
||
if (bestS > MATE_BOUND && skill >= 3) return { m: ranked[0].m, score: bestS, book: false };
|
||
let pool = ranked.slice(0, prof.topN).filter((r) => r.score > -MATE_BOUND || r === ranked[0]);
|
||
if (!pool.length) pool = [ranked[0]];
|
||
let pick;
|
||
if (rng() < prof.slip && pool.length > 1) {
|
||
pick = pool[1 + Math.floor(rng() * (pool.length - 1))];
|
||
} else {
|
||
let bestV = -Infinity;
|
||
for (const r of pool) {
|
||
const v = r.score + (rng() * 2 - 1) * prof.noise;
|
||
if (v > bestV) { bestV = v; pick = r; }
|
||
}
|
||
}
|
||
return { m: pick.m, score: pick.score, book: false };
|
||
}
|
||
|
||
/** Thinking budget under a clock: a slice of what's left plus most of the increment. */
|
||
export function clockBudget(skill, remainingMs, incMs, ply) {
|
||
const prof = profileOf(skill);
|
||
if (remainingMs == null) return prof.ms;
|
||
const movesLeft = Math.max(18, 40 - Math.floor(ply / 2) * 0.5);
|
||
const slice = remainingMs / movesLeft + incMs * 0.75;
|
||
return Math.max(60, Math.min(prof.ms, slice, remainingMs * 0.25));
|
||
}
|
||
|
||
// ── table manners ──────────────────────────────────────────────────────────
|
||
/** Would the AI (whose last search said `score`, from its side) offer a draw? */
|
||
export function wantsDraw(score, ply, skill) {
|
||
if (ply < 60) return false;
|
||
const k = clampSkill(skill);
|
||
return Math.abs(score) <= 25 + (5 - k) * 10;
|
||
}
|
||
|
||
/** Response to your draw offer. score = the AI's view of the position. */
|
||
export function drawDecision(score, ply, skill) {
|
||
if (ply < 20) return { accept: false, why: 'early' };
|
||
const k = clampSkill(skill);
|
||
if (score <= -150) return { accept: true, why: 'worse' };
|
||
if (score <= 40 - k * 5 && ply >= 50) return { accept: true, why: 'level' };
|
||
return { accept: false, why: score > 150 ? 'better' : 'play' };
|
||
}
|
||
|
||
/** Resign when hopelessly lost for a few moves running (skill 3+ only). */
|
||
export function shouldResign(history, skill) {
|
||
if (clampSkill(skill) < 3 || history.length < 3) return false;
|
||
return history.slice(-3).every((s) => s <= -1100);
|
||
}
|
||
|
||
// ── explaining a move ──────────────────────────────────────────────────────
|
||
const NAME = ['', 'pawn', 'knight', 'bishop', 'rook', 'queen', 'king'];
|
||
|
||
/** A short reason ("forks the king and rook") for a move, given the search score from the mover's side. */
|
||
export function describeIdea(pos, m, score = 0) {
|
||
const p = pos.clone();
|
||
const from = m & 127, to = (m >> 7) & 127, fl = (m >> 17) & 15, promo = (m >> 14) & 7;
|
||
const us = p.side;
|
||
const piece = p.b[from] & 7;
|
||
const victim = (fl & L.F_EP) ? P : (p.b[to] & 7);
|
||
const mate = mateIn(score);
|
||
if (!L.makeMove(p, m)) return 'keeps things steady';
|
||
try {
|
||
if (!L.hasLegalMove(p) && p.inCheck()) return 'is checkmate';
|
||
if (mate > 0) return `forces mate in ${mate}`;
|
||
if (promo) return `promotes to a ${NAME[promo]}`;
|
||
if (fl & L.F_CASTLE) return 'tucks the king away and connects the rooks';
|
||
// what does the moved piece attack now?
|
||
const ks = (fl & L.F_CASTLE) ? -1 : to;
|
||
const targets = [];
|
||
if (ks >= 0) {
|
||
for (let s = 0; s < 128; s++) {
|
||
if (s & 0x88) { s += 7; continue; }
|
||
const q = p.b[s];
|
||
if (!q || (q >> 3) === us) continue;
|
||
const atk = L.attackersOf(p, s, us);
|
||
if (atk.includes(ks)) targets.push(q & 7);
|
||
}
|
||
}
|
||
const big = targets.filter((t) => t === K || SEE_VAL[t] > SEE_VAL[piece] || t === R || t === Q).sort((a, b) => SEE_VAL[b] - SEE_VAL[a]);
|
||
if (big.length >= 2) return `forks the ${NAME[big[0]]} and ${NAME[big[1]]}`;
|
||
if (victim) {
|
||
if (score >= 150) return `wins the ${NAME[victim]}`;
|
||
return `takes the ${NAME[victim]}`;
|
||
}
|
||
if (p.inCheck()) return score >= 200 ? 'checks, and the attack keeps rolling' : 'gives check';
|
||
if (score >= 250) return 'sets up a winning threat';
|
||
// did it rescue a piece that was hanging?
|
||
L.unmakeMove(p);
|
||
const wasAttacked = L.isAttacked(p, from, us ^ 1) && piece !== P && piece !== K;
|
||
L.makeMove(p, m);
|
||
if (wasAttacked) return `gets the ${NAME[piece]} out of trouble`;
|
||
const row = from >> 4, home = us === WHITE ? 7 : 0;
|
||
if ((piece === N || piece === B) && row === home) return `develops the ${NAME[piece]}`;
|
||
const tf = to & 7, tr = to >> 4;
|
||
if (piece === P && tf >= 2 && tf <= 5 && tr >= 2 && tr <= 5) return 'grabs space in the centre';
|
||
if (targets.length) return `puts pressure on the ${NAME[targets.sort((a, b) => SEE_VAL[b] - SEE_VAL[a])[0]]}`;
|
||
return 'improves the position';
|
||
} finally {
|
||
// p is a clone — nothing to restore
|
||
}
|
||
}
|
||
|
||
/** Is the moved piece left hanging (a cheap "you're dropping material" test)? */
|
||
export function dropsMaterial(pos, m) {
|
||
const p = pos.clone();
|
||
if (!L.makeMove(p, m)) return 0;
|
||
// best capture reply by SEE
|
||
const caps = L.genMoves(p, [], true);
|
||
let worst = 0;
|
||
for (const c of caps) {
|
||
if (!(((c >> 17) & 15) & L.F_CAP)) continue;
|
||
const v = see(p, c);
|
||
if (v > worst) {
|
||
if (!L.makeMove(p, c)) continue;
|
||
L.unmakeMove(p);
|
||
worst = v;
|
||
}
|
||
}
|
||
return worst;
|
||
}
|