// CAEL chess engine in JavaScript: a line-by-line port of cael_chess/core.py // (mailbox move generation, alpha-beta search, evaluation with weights fitted // to master games). Runs as a Web Worker or under Node for tests. "use strict"; const OFF = 99, MAXPLY = 128, MAXMOVES = 256, HISTLEN = 4096, INF = 32000, MATE = 31000, MATE_BOUND = 30000; const N_DIRS = [-21, -19, -12, -8, 8, 12, 19, 21], B_DIRS = [-11, -9, 9, 11], R_DIRS = [-10, -1, 1, 10]; const K_DIRS = [-11, -10, -9, -1, 1, 9, 10, 11]; const VAL = [0, 100, 320, 330, 500, 900, 20000], PHASE_INC = [0, 0, 1, 1, 2, 4, 0]; const NFEAT = 105, NBASIC = 19, EXT = 768, NPARAM = EXT + 2 * NFEAT, FOFF = 512; const F_BACKWARD = 25, F_CONN = 26, F_CONNR = 27, F_PBLOCK = 28, F_KD2 = 29, F_KZW = 30, F_SCN = 31, F_SCL = 32; const F_TMIN = 33, F_TROOK = 34, F_SPACE = 35, F_BPAWNS = 36, F_MBEHIND = 37, F_KPDIST = 38; const F_MOBN = 39, F_MOBB = 48, F_MOBR = 62, F_MOBQ = 77; const ATT_W = [0, 0, 2, 2, 3, 5, 0]; const SQ64 = new Int32Array(120).fill(-1), SQ120 = new Int32Array(64); for (let r = 0; r < 8; r++) for (let f = 0; f < 8; f++) { SQ64[21 + f + 10 * r] = r * 8 + f; SQ120[r * 8 + f] = 21 + f + 10 * r; } // lookup tables for the evaluation (same as core.py) const ZONE = new Uint8Array(2 * 120 * 120), DIST = new Int32Array(120 * 120), SQCOL = new Int32Array(120); const KREL = new Uint8Array(240), SPACE_SQ = new Int32Array(24); for (let a = 0; a < 120; a++) { if (SQ64[a] >= 0) SQCOL[a] = ((SQ64[a] & 7) + (SQ64[a] >> 3)) & 1; for (let c = 0; c < 120; c++) { if (SQ64[a] < 0 || SQ64[c] < 0) continue; const df = Math.abs((SQ64[a] & 7) - (SQ64[c] & 7)), dr = (SQ64[c] >> 3) - (SQ64[a] >> 3); DIST[a * 120 + c] = Math.max(df, Math.abs(dr)); ZONE[a * 120 + c] = (df <= 1 && (Math.abs(dr) <= 1 || dr === 2)) ? 1 : 0; // white king (up +1) ZONE[14400 + a * 120 + c] = (df <= 1 && (Math.abs(dr) <= 1 || dr === -2)) ? 1 : 0; // black king (up -1) } } for (const d of [-21, -19, -12, -8, 8, 12, 19, 21]) KREL[d + 120] = 1; { let j = 0; for (let w = 0; w < 2; w++) { j = w * 12; for (const rk of [1, 2, 3]) { const r = w === 0 ? rk : 7 - rk; for (let f = 2; f < 6; f++) SPACE_SQ[j++] = SQ120[r * 8 + f]; } } } const CASTLE_MASK = new Int32Array(120).fill(15); CASTLE_MASK[25] = 15 & ~3; CASTLE_MASK[28] = 15 & ~1; CASTLE_MASK[21] = 15 & ~2; CASTLE_MASK[95] = 15 & ~12; CASTLE_MASK[98] = 15 & ~4; CASTLE_MASK[91] = 15 & ~8; // zobrist keys as two 32-bit halves let seed = 0x9e3779b9; function rnd() { seed ^= seed << 13; seed >>>= 0; seed ^= seed >>> 17; seed ^= seed << 5; seed >>>= 0; return seed; } const ZL = new Uint32Array(13 * 120), ZH = new Uint32Array(13 * 120); for (let i = 0; i < 13 * 120; i++) { ZL[i] = rnd(); ZH[i] = rnd(); } const ZCL = new Uint32Array(16), ZCH = new Uint32Array(16); for (let i = 0; i < 16; i++) { ZCL[i] = rnd(); ZCH[i] = rnd(); } const ZEL = new Uint32Array(120), ZEH = new Uint32Array(120); for (let i = 0; i < 120; i++) { ZEL[i] = rnd(); ZEH[i] = rnd(); } const ZSL = rnd(), ZSH = rnd(); // pawn-structure key (st[7]) for correction history: pawns only const PZ = new Int32Array(13 * 120); for (let i = 0; i < 120; i++) { PZ[5 * 120 + i] = rnd() | 0; PZ[7 * 120 + i] = rnd() | 0; } // history tables in one array (same layout as core.py) const H_BUT = 0, H_CM = 2 * 120 * 120, H_CONT = H_CM + 832, H_CORR = H_CONT + 832 * 832, CORR_N = 16384; const HH_LEN = H_CORR + 2 * CORR_N, HIST_MAX = 16384; const S_STATIC = MAXMOVES - 1, S_MOVE = MAXMOVES - 2, S_EXCL = MAXMOVES - 3; function grav(hh, i, bonus) { hh[i] += bonus - Math.floor(hh[i] * Math.abs(bonus) / HIST_MAX); } const LMR = new Int32Array(64 * 64); for (let d = 1; d < 64; d++) for (let m = 1; m < 64; m++) LMR[d * 64 + m] = Math.floor(0.75 + Math.log(d) * Math.log(m) / 2.25); const mfrom = m => m & 127, mto = m => (m >> 7) & 127, mpromo = m => (m >> 14) & 7, mflag = m => (m >> 17) & 3; const enc = (fr, to, pr, fl) => fr | (to << 7) | (pr << 14) | (fl << 17); class Engine { // switches as in core.py; 8 history 2 (+26 Elo), 9 singular extensions (+22), 10 ProbCut (+10) constructor(params, ttBits = 20, cfg = [1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1], shared = null) { this.P = new Int32Array(NPARAM); this.P.set(params.slice(0, NPARAM)); this.cfg = new Int32Array(16); this.cfg.set(cfg.slice(0, 16)); this.b = new Int32Array(120); this.st = new Int32Array(8); // side, castle, ep, halfmove, wk, bk, histIndex, pawn key this.hl = new Uint32Array(HISTLEN + MAXPLY + 8); this.hh_ = new Uint32Array(HISTLEN + MAXPLY + 8); this.und = new Int32Array((HISTLEN + MAXPLY + 8) * 6); this.mvs = new Int32Array((MAXPLY + 2) * MAXMOVES); this.scs = new Int32Array((MAXPLY + 2) * MAXMOVES); this.kil = new Int32Array((MAXPLY + 2) * 2); this.hist = new Int32Array(HH_LEN); const n = 1 << ttBits; this.ttMask = n - 1; if (shared) { // hash table in SharedArrayBuffers, used by every search worker at once this.ttk = new Uint32Array(shared.ttk); this.ttc = new Uint32Array(shared.ttc); this.ttm = new Int32Array(shared.ttm); this.ttd = new Int8Array(shared.ttd); this.ttf = new Int8Array(shared.ttf); this.tts = new Int16Array(shared.tts); this.ttMask = this.ttk.length - 1; this.stopFlag = new Int32Array(shared.stop); } else { this.ttk = new Uint32Array(n); this.ttc = new Uint32Array(n); this.ttm = new Int32Array(n); this.ttd = new Int8Array(n); this.ttf = new Int8Array(n); this.tts = new Int16Array(n); this.stopFlag = null; } this.scr = new Int32Array(FOFF + 128); this.nodes = 0; this.stop = false; this.deadline = 0; this.nodeLimit = 0; this.seldepth = 0; this.rootBest = 0; this.rootScore = 0; } // ------------------------------------------------------------ position setFen(fen) { const b = this.b, st = this.st; b.fill(OFF); for (let i = 0; i < 64; i++) b[SQ120[i]] = 0; const [pl, side, cast, ep, half] = fen.split(" "); const map = { p: 1, n: 2, b: 3, r: 4, q: 5, k: 6 }; let r = 7, f = 0; for (const ch of pl) { if (ch === "/") { r--; f = 0; continue; } if (ch >= "1" && ch <= "8") { f += +ch; continue; } const t = map[ch.toLowerCase()], v = ch === ch.toUpperCase() ? t : -t, s = SQ120[r * 8 + f]; b[s] = v; if (v === 6) st[4] = s; if (v === -6) st[5] = s; f++; } st[0] = side === "w" ? 1 : -1; let cr = 0; if (cast.includes("K")) cr |= 1; if (cast.includes("Q")) cr |= 2; if (cast.includes("k")) cr |= 4; if (cast.includes("q")) cr |= 8; st[1] = cr; st[2] = ep && ep !== "-" ? SQ120[(+ep[1] - 1) * 8 + "abcdefgh".indexOf(ep[0])] : 0; st[3] = +(half || 0); st[6] = 0; let pk = 0; for (let q = 21; q < 99; q++) if (b[q] === 1 || b[q] === -1) pk ^= PZ[(b[q] + 6) * 120 + q]; st[7] = pk; const [lo, hi] = this.computeHash(); this.hl[0] = lo; this.hh_[0] = hi; } computeHash() { const b = this.b, st = this.st; let lo = 0, hi = 0; for (let s = 21; s < 99; s++) { const p = b[s]; if (p !== 0 && p !== OFF) { lo ^= ZL[(p + 6) * 120 + s]; hi ^= ZH[(p + 6) * 120 + s]; } } lo ^= ZCL[st[1]]; hi ^= ZCH[st[1]]; if (st[2] !== 0) { lo ^= ZEL[st[2]]; hi ^= ZEH[st[2]]; } if (st[0] === -1) { lo ^= ZSL; hi ^= ZSH; } return [lo >>> 0, hi >>> 0]; } attacked(sq, by) { const b = this.b; if (by === 1) { if (b[sq - 9] === 1 || b[sq - 11] === 1) return true; } else { if (b[sq + 9] === -1 || b[sq + 11] === -1) return true; } const kn = 2 * by, kg = 6 * by, bi = 3 * by, qu = 5 * by, ro = 4 * by; for (let i = 0; i < 8; i++) if (b[sq + N_DIRS[i]] === kn) return true; for (let i = 0; i < 8; i++) if (b[sq + K_DIRS[i]] === kg) return true; for (let i = 0; i < 4; i++) { const d = B_DIRS[i]; let t = sq + d; while (b[t] === 0) t += d; if (b[t] === bi || b[t] === qu) return true; } for (let i = 0; i < 4; i++) { const d = R_DIRS[i]; let t = sq + d; while (b[t] === 0) t += d; if (b[t] === ro || b[t] === qu) return true; } return false; } kingSq(side) { return side === 1 ? this.st[4] : this.st[5]; } make(m) { const b = this.b, st = this.st, fr = mfrom(m), to = mto(m), pr = mpromo(m), fl = mflag(m), side = st[0], i = st[6]; let lo = this.hl[i], hi = this.hh_[i]; const p = b[fr], cap = b[to], u = i * 6; this.und[u] = cap; this.und[u + 1] = st[1]; this.und[u + 2] = st[2]; this.und[u + 3] = st[3]; this.und[u + 4] = m; this.und[u + 5] = st[7]; let pk = st[7] ^ PZ[(p + 6) * 120 + fr]; if (cap !== 0) pk ^= PZ[(cap + 6) * 120 + to]; if (fl === 2) pk ^= PZ[(-side + 6) * 120 + (to - 10 * side)]; if (st[2] !== 0) { lo ^= ZEL[st[2]]; hi ^= ZEH[st[2]]; } lo ^= ZCL[st[1]]; hi ^= ZCH[st[1]]; lo ^= ZL[(p + 6) * 120 + fr]; hi ^= ZH[(p + 6) * 120 + fr]; b[fr] = 0; if (cap !== 0) { lo ^= ZL[(cap + 6) * 120 + to]; hi ^= ZH[(cap + 6) * 120 + to]; } if (fl === 2) { const cs = to - 10 * side; lo ^= ZL[(-side + 6) * 120 + cs]; hi ^= ZH[(-side + 6) * 120 + cs]; b[cs] = 0; } const np = pr !== 0 ? pr * side : p; b[to] = np; lo ^= ZL[(np + 6) * 120 + to]; hi ^= ZH[(np + 6) * 120 + to]; st[7] = pk ^ PZ[(np + 6) * 120 + to]; if (fl === 3) { let rf, rt; if (to === 27) { rf = 28; rt = 26; } else if (to === 23) { rf = 21; rt = 24; } else if (to === 97) { rf = 98; rt = 96; } else { rf = 91; rt = 94; } const rk = b[rf]; b[rf] = 0; b[rt] = rk; lo ^= ZL[(rk + 6) * 120 + rf] ^ ZL[(rk + 6) * 120 + rt]; hi ^= ZH[(rk + 6) * 120 + rf] ^ ZH[(rk + 6) * 120 + rt]; } if (p === 6) st[4] = to; else if (p === -6) st[5] = to; st[1] = st[1] & CASTLE_MASK[fr] & CASTLE_MASK[to]; lo ^= ZCL[st[1]]; hi ^= ZCH[st[1]]; st[2] = 0; if (fl === 1) { st[2] = fr + 10 * side; lo ^= ZEL[st[2]]; hi ^= ZEH[st[2]]; } st[3] = (p === 1 || p === -1 || cap !== 0) ? 0 : st[3] + 1; st[0] = -side; lo ^= ZSL; hi ^= ZSH; st[6] = i + 1; this.hl[i + 1] = lo >>> 0; this.hh_[i + 1] = hi >>> 0; } unmake() { const b = this.b, st = this.st, i = st[6] - 1, u = i * 6, m = this.und[u + 4]; const fr = mfrom(m), to = mto(m), pr = mpromo(m), fl = mflag(m); st[0] = -st[0]; const side = st[0]; let p = b[to]; if (pr !== 0) p = side; b[fr] = p; b[to] = this.und[u]; if (fl === 2) b[to - 10 * side] = -side; if (fl === 3) { let rf, rt; if (to === 27) { rf = 28; rt = 26; } else if (to === 23) { rf = 21; rt = 24; } else if (to === 97) { rf = 98; rt = 96; } else { rf = 91; rt = 94; } b[rf] = b[rt]; b[rt] = 0; } if (p === 6) st[4] = fr; else if (p === -6) st[5] = fr; st[1] = this.und[u + 1]; st[2] = this.und[u + 2]; st[3] = this.und[u + 3]; st[7] = this.und[u + 5]; st[6] = i; } makeNull() { const st = this.st, i = st[6], u = i * 6; let lo = this.hl[i], hi = this.hh_[i]; this.und[u + 5] = st[7]; this.und[u] = 0; this.und[u + 1] = st[1]; this.und[u + 2] = st[2]; this.und[u + 3] = st[3]; this.und[u + 4] = 0; if (st[2] !== 0) { lo ^= ZEL[st[2]]; hi ^= ZEH[st[2]]; } st[2] = 0; st[3]++; st[0] = -st[0]; lo ^= ZSL; hi ^= ZSH; st[6] = i + 1; this.hl[i + 1] = lo >>> 0; this.hh_[i + 1] = hi >>> 0; } unmakeNull() { const st = this.st, i = st[6] - 1, u = i * 6; st[0] = -st[0]; st[2] = this.und[u + 2]; st[3] = this.und[u + 3]; st[6] = i; } addPawn(out, base, n, fr, to, promo, caps) { if (promo) { out[base + n++] = enc(fr, to, 5, 0); if (!caps) { out[base + n++] = enc(fr, to, 2, 0); out[base + n++] = enc(fr, to, 4, 0); out[base + n++] = enc(fr, to, 3, 0); } } else out[base + n++] = enc(fr, to, 0, 0); return n; } gen(out, base, caps) { const b = this.b, st = this.st, side = st[0]; let n = 0; for (let s = 21; s < 99; s++) { const p = b[s]; if (p === 0 || p === OFF || p * side < 0) continue; const a = p * side; if (a === 1) { const fwd = 10 * side; let t = s + fwd; const promo = side === 1 ? t >= 91 : t <= 28; if (b[t] === 0) { if (promo || !caps) n = this.addPawn(out, base, n, s, t, promo, caps); if (!promo && !caps) { const start = side === 1 ? (s >= 31 && s <= 38) : (s >= 81 && s <= 88); if (start && b[t + fwd] === 0) out[base + n++] = enc(s, t + fwd, 0, 1); } } for (const c of [fwd - 1, fwd + 1]) { t = s + c; const q = b[t]; if (q !== OFF && q * side < 0) n = this.addPawn(out, base, n, s, t, promo, caps); else if (st[2] !== 0 && t === st[2]) out[base + n++] = enc(s, t, 0, 2); } } else if (a === 2 || a === 6) { const D = a === 2 ? N_DIRS : K_DIRS; for (let k = 0; k < 8; k++) { const t = s + D[k], q = b[t]; if (q === OFF) continue; if (q === 0) { if (!caps) out[base + n++] = enc(s, t, 0, 0); } else if (q * side < 0) out[base + n++] = enc(s, t, 0, 0); } } else { for (let k = 0; k < 8; k++) { let d; if (k < 4) { if (a === 4) continue; d = B_DIRS[k]; } else { if (a === 3) continue; d = R_DIRS[k - 4]; } let t = s + d; for (;;) { const q = b[t]; if (q === OFF) break; if (q === 0) { if (!caps) out[base + n++] = enc(s, t, 0, 0); } else { if (q * side < 0) out[base + n++] = enc(s, t, 0, 0); break; } t += d; } } } } if (!caps) { const cr = st[1]; if (side === 1) { if ((cr & 1) && b[26] === 0 && b[27] === 0 && b[28] === 4 && b[25] === 6 && !this.attacked(25, -1) && !this.attacked(26, -1) && !this.attacked(27, -1)) out[base + n++] = enc(25, 27, 0, 3); if ((cr & 2) && b[22] === 0 && b[23] === 0 && b[24] === 0 && b[21] === 4 && b[25] === 6 && !this.attacked(25, -1) && !this.attacked(24, -1) && !this.attacked(23, -1)) out[base + n++] = enc(25, 23, 0, 3); } else { if ((cr & 4) && b[96] === 0 && b[97] === 0 && b[98] === -4 && b[95] === -6 && !this.attacked(95, 1) && !this.attacked(96, 1) && !this.attacked(97, 1)) out[base + n++] = enc(95, 97, 0, 3); if ((cr & 8) && b[92] === 0 && b[93] === 0 && b[94] === 0 && b[91] === -4 && b[95] === -6 && !this.attacked(95, 1) && !this.attacked(94, 1) && !this.attacked(93, 1)) out[base + n++] = enc(95, 93, 0, 3); } } return n; } legal() { const tmp = new Int32Array(MAXMOVES), n = this.gen(tmp, 0, false), side = this.st[0], out = []; for (let i = 0; i < n; i++) { this.make(tmp[i]); if (!this.attacked(this.kingSq(side), -side)) out.push(tmp[i]); this.unmake(); } return out; } perft(d) { if (d === 0) return 1; const tmp = new Int32Array(MAXMOVES), n = this.gen(tmp, 0, false), side = this.st[0]; let t = 0; for (let i = 0; i < n; i++) { this.make(tmp[i]); if (!this.attacked(this.kingSq(side), -side)) t += this.perft(d - 1); this.unmake(); } return t; } static uci(m) { const sq = s => { const x = SQ64[s]; return "abcdefgh"[x & 7] + ((x >> 3) + 1); }; const pr = mpromo(m); return sq(mfrom(m)) + sq(mto(m)) + (pr ? " nbrq"[pr - 1] : ""); } pushUci(u) { for (const m of this.legal()) if (Engine.uci(m) === u) { this.make(m); return m; } throw new Error("illegal move " + u); } // ------------------------------------------------------------ evaluation evaluate(side) { const b = this.b, P = this.P, scr = this.scr; for (let i = 400; i < 432; i++) scr[i] = 0; for (let i = 416; i < 424; i++) scr[i] = 8; for (let i = 424; i < 432; i++) scr[i] = -1; for (let i = 432; i < 436; i++) scr[i] = 0; for (let k = 0; k < NFEAT; k++) scr[FOFF + k] = 0; let mg = 0, eg = 0, phase = 0, wb = 0, bb = 0, wmat = 0, bmat = 0, wminor = 0, bminor = 0, wmajor = 0, bmajor = 0; let wpawns = 0, bpawns = 0, wk = 0, bk = 0, nsq = 0; for (let s = 21; s < 99; s++) { const p = b[s]; if (p === 0 || p === OFF) continue; scr[440 + nsq++] = s; const t = p > 0 ? p : -p, s64 = SQ64[s]; let sgn = 1, idx; if (p > 0) idx = (t - 1) * 64 + s64; else { idx = (t - 1) * 64 + (s64 ^ 56); sgn = -1; } mg += sgn * P[idx]; eg += sgn * P[384 + idx]; phase += PHASE_INC[t]; const f = s64 & 7, r = s64 >> 3; if (t === 1) { scr[(p > 0 ? 432 : 434) + ((f + r) & 1)]++; if (p > 0) { scr[400 + f]++; wpawns++; if (r < scr[416 + f]) scr[416 + f] = r; } else { scr[408 + f]++; bpawns++; if (r > scr[424 + f]) scr[424 + f] = r; } continue; } if (t === 6) { if (p > 0) wk = s; else bk = s; continue; } if (p > 0) wmat += VAL[t]; else bmat += VAL[t]; if (t === 2 || t === 3) { if (p > 0) wminor++; else bminor++; } else { if (p > 0) wmajor++; else bmajor++; } if (t === 3) { if (p > 0) wb++; else bb++; } } let extOn = false, ext2On = false; for (let k = 2 * NBASIC; k < 2 * NFEAT; k++) if (P[EXT + k] !== 0) { extOn = true; break; } if (extOn) for (let k = 2 * F_BACKWARD; k < 2 * NFEAT; k++) if (P[EXT + k] !== 0) { ext2On = true; break; } if (extOn) for (let i = 128; i < 376; i++) scr[i] = 0; let unitsW = 0, unitsB = 0, nattW = 0, nattB = 0; for (let qi = 0; qi < nsq; qi++) { const s = scr[440 + qi], p = b[s], t = p > 0 ? p : -p, sgn = p > 0 ? 1 : -1, base = p > 0 ? 128 : 256; if (t === 1) { if (extOn) for (const c of [9, 11]) { const u = s + c * sgn; if (b[u] !== OFF) scr[base + u]++; } continue; } if (t === 6) { if (extOn) for (let k = 0; k < 8; k++) { const u = s + K_DIRS[k]; if (b[u] !== OFF) scr[base + u]++; } continue; } const eks = p > 0 ? bk : wk, zo = (p > 0 ? 1 : 0) * 14400 + eks * 120; let mob = 0, smob = 0, hits = 0; if (t === 2) { for (let k = 0; k < 8; k++) { const u = s + N_DIRS[k], q = b[u]; if (q === OFF) continue; if (q === 0 || q * sgn < 0) { mob++; if (ext2On && b[u + 9 * sgn] !== -sgn && b[u + 11 * sgn] !== -sgn) smob++; } if (extOn) { scr[base + u]++; if (eks !== 0 && ZONE[zo + u]) hits++; if (ext2On && q * sgn < 0 && (q === -4 * sgn || q === -5 * sgn)) scr[FOFF + F_TMIN] += sgn; } } scr[FOFF + 11] += sgn * mob; if (ext2On) scr[FOFF + F_MOBN + Math.min(smob, 8)] += sgn; } else { for (let k = 0; k < 8; k++) { let d; if (k < 4) { if (t === 4) continue; d = B_DIRS[k]; } else { if (t === 3) continue; d = R_DIRS[k - 4]; } let u = s + d; for (;;) { const q = b[u]; if (q === OFF) break; if (extOn) { scr[base + u]++; if (eks !== 0 && ZONE[zo + u]) hits++; } if (q === 0) { mob++; if (ext2On && b[u + 9 * sgn] !== -sgn && b[u + 11 * sgn] !== -sgn) smob++; u += d; continue; } if (q * sgn < 0) { mob++; if (ext2On) { if (b[u + 9 * sgn] !== -sgn && b[u + 11 * sgn] !== -sgn) smob++; if (t === 3 && (q === -4 * sgn || q === -5 * sgn)) scr[FOFF + F_TMIN] += sgn; else if (t === 4 && q === -5 * sgn) scr[FOFF + F_TROOK] += sgn; } } break; } } if (t === 3) { scr[FOFF + 12] += sgn * mob; if (ext2On) scr[FOFF + F_MOBB + Math.min(smob, 13)] += sgn; } else if (t === 4) { scr[FOFF + 13] += sgn * mob; if (ext2On) scr[FOFF + F_MOBR + Math.min(smob, 14)] += sgn; } else { scr[FOFF + 14] += sgn * mob; if (ext2On) scr[FOFF + F_MOBQ + Math.min(smob, 27)] += sgn; } } if (hits > 0) { if (p > 0) { unitsW += ATT_W[t] * hits; nattW++; } else { unitsB += ATT_W[t] * hits; nattB++; } } } if (phase > 24) phase = 24; if (wpawns === 0 && bpawns === 0 && wmajor === 0 && bmajor === 0 && wminor <= 1 && bminor <= 1) return 0; if (wb >= 2) scr[FOFF]++; if (bb >= 2) scr[FOFF]--; for (let qi = 0; qi < nsq; qi++) { const s = scr[440 + qi], p = b[s], s64 = SQ64[s], f = s64 & 7, r = s64 >> 3; if (p === 1 || p === -1) { const own = p > 0 ? 400 : 408, sgn = p > 0 ? 1 : -1; const left = f > 0 ? scr[own + f - 1] : 0, right = f < 7 ? scr[own + f + 1] : 0; if (left === 0 && right === 0) scr[FOFF + 2] += sgn; const rrel = p > 0 ? r : 7 - r; if (b[s - 1] === p || b[s + 1] === p || b[s - 9 * sgn] === p || b[s - 11 * sgn] === p) { scr[FOFF + F_CONN] += sgn; scr[FOFF + F_CONNR] += sgn * rrel; } else if (left !== 0 || right !== 0) { let sup = false; for (const ff of [f - 1, f + 1]) { if (ff >= 0 && ff <= 7) { if (p > 0 && scr[416 + ff] <= r) sup = true; if (p < 0 && scr[424 + ff] >= r) sup = true; } } const stop = s + 10 * sgn; if (!sup && (b[stop + 9 * sgn] === -sgn || b[stop + 11 * sgn] === -sgn)) scr[FOFF + F_BACKWARD] += sgn; } let passed = true; for (let ff = Math.max(f - 1, 0); ff <= Math.min(f + 1, 7); ff++) { if (p > 0) { if (scr[424 + ff] > r) passed = false; } else { if (scr[416 + ff] < r) passed = false; } } if (passed) { const rr = p > 0 ? r : 7 - r; if (rr >= 1 && rr <= 6) scr[FOFF + 3 + rr - 1] += sgn; const q = b[s + 10 * sgn]; if (q !== 0 && q !== OFF) scr[FOFF + F_PBLOCK] += sgn; } } else if (p === 4 || p === -4) { const sgn = p > 0 ? 1 : -1, own = p > 0 ? scr[400 + f] : scr[408 + f], opp = p > 0 ? scr[408 + f] : scr[400 + f]; if (own === 0) { if (opp === 0) scr[FOFF + 9] += sgn; else scr[FOFF + 10] += sgn; } if ((p > 0 && r === 6) || (p < 0 && r === 1)) scr[FOFF + 18] += sgn; } } for (let f = 0; f < 8; f++) { if (scr[400 + f] > 1) scr[FOFF + 1] += scr[400 + f] - 1; if (scr[408 + f] > 1) scr[FOFF + 1] -= scr[408 + f] - 1; } for (let who = 0; who < 2; who++) { const ks = who === 0 ? wk : bk; if (ks === 0) continue; const sgn = who === 0 ? 1 : -1, k64 = SQ64[ks], kf = k64 & 7, kr = k64 >> 3; let shield = 0, openf = 0; for (let ff = Math.max(kf - 1, 0); ff <= Math.min(kf + 1, 7); ff++) { for (let dr = 1; dr <= 2; dr++) { const rr = kr + sgn * dr; if (rr >= 0 && rr <= 7 && b[SQ120[rr * 8 + ff]] === sgn) shield++; } if ((who === 0 ? scr[400 + ff] : scr[408 + ff]) === 0) openf++; } scr[FOFF + 15] += sgn * shield; scr[FOFF + 17] += sgn * openf; } scr[FOFF + 16] = side; if (extOn) { this.extFinish(wk, bk, nsq, unitsW, unitsB, nattW, nattB); if (ext2On) this.extMore(wk, bk, nsq, unitsW, unitsB, nattW, nattB, wminor + wmajor, bminor + bmajor); } const nf = ext2On ? NFEAT : (extOn ? F_BACKWARD : NBASIC); for (let k = 0; k < nf; k++) { const c = scr[FOFF + k]; if (c !== 0) { mg += c * P[EXT + 2 * k]; eg += c * P[EXT + 2 * k + 1]; } } const num = mg * phase + eg * (24 - phase); let score = num >= 0 ? Math.floor(num / 24) : -Math.floor(-num / 24); if (bpawns === 0 && bmat === 0 && wmat >= 500 && bk !== 0) score += mopup(wk, bk); else if (wpawns === 0 && wmat === 0 && bmat >= 500 && wk !== 0) score -= mopup(bk, wk); return score * side; } extFinish(wk, bk, nsq, unitsW, unitsB, nattW, nattB) { const b = this.b, scr = this.scr; let ka = 0; if (nattW >= 2) ka += unitsW; if (nattB >= 2) ka -= unitsB; scr[FOFF + NBASIC] = ka; let threat = 0, hang = 0, pfree = 0, pkd = 0, outpost = 0; for (let qi = 0; qi < nsq; qi++) { const s = scr[440 + qi], p = b[s]; const t = p > 0 ? p : -p, sgn = p > 0 ? 1 : -1, ownMap = p > 0 ? 128 : 256, oppMap = p > 0 ? 256 : 128; if (t >= 2 && t <= 5) { if (b[s + 9 * sgn] === -sgn || b[s + 11 * sgn] === -sgn) threat -= sgn; if (scr[oppMap + s] > 0 && scr[ownMap + s] === 0) hang -= sgn; } if (t === 1) { const s64 = SQ64[s], f = s64 & 7, r = s64 >> 3; let passed = true; for (let ff = Math.max(f - 1, 0); ff <= Math.min(f + 1, 7); ff++) { if (p > 0) { if (scr[424 + ff] > r) passed = false; } else { if (scr[416 + ff] < r) passed = false; } } if (passed) { const rr = p > 0 ? r : 7 - r, stop = s + 10 * sgn; if (b[stop] === 0 && scr[oppMap + stop] === 0) pfree += sgn * rr; const ok = p > 0 ? wk : bk, ek = p > 0 ? bk : wk; if (ok !== 0 && ek !== 0) { const st64 = b[stop] !== OFF ? SQ64[stop] : SQ64[s], o64 = SQ64[ok], e64 = SQ64[ek]; const dO = Math.max(Math.abs((o64 & 7) - (st64 & 7)), Math.abs((o64 >> 3) - (st64 >> 3))); const dE = Math.max(Math.abs((e64 & 7) - (st64 & 7)), Math.abs((e64 >> 3) - (st64 >> 3))); pkd += sgn * (dE - dO) * rr; } } } else if (t === 2) { const s64 = SQ64[s], f = s64 & 7, r = s64 >> 3, rr = p > 0 ? r : 7 - r; if (rr >= 3 && rr <= 5 && (b[s - 9 * sgn] === sgn || b[s - 11 * sgn] === sgn)) { let safe = true; for (const ff of [f - 1, f + 1]) { if (ff >= 0 && ff <= 7) { if (p > 0 && scr[424 + ff] > r) safe = false; if (p < 0 && scr[416 + ff] < r) safe = false; } } if (safe) outpost += sgn; } } } scr[FOFF + NBASIC + 1] = threat; scr[FOFF + NBASIC + 2] = hang; scr[FOFF + NBASIC + 3] = pfree; scr[FOFF + NBASIC + 4] = pkd; scr[FOFF + NBASIC + 5] = outpost; } extMore(wk, bk, nsq, unitsW, unitsB, nattW, nattB, wpieces, bpieces) { const b = this.b, scr = this.scr; let kd = 0; if (nattW >= 2) kd += Math.floor(unitsW * unitsW / 16); if (nattB >= 2) kd -= Math.floor(unitsB * unitsB / 16); scr[FOFF + F_KD2] = kd; let nwn = 0, nbn = 0, kdw = 99, kdb = 99, bp = 0, mb = 0; for (let qi = 0; qi < nsq; qi++) { const s = scr[440 + qi], p = b[s]; if (p === 1 || p === -1) { if (wk !== 0) { const dd = DIST[wk * 120 + s]; if (dd < kdw) kdw = dd; } if (bk !== 0) { const dd = DIST[bk * 120 + s]; if (dd < kdb) kdb = dd; } } else if (p === 2) { scr[480 + nwn++] = s; if (b[s + 10] === 1) mb++; } else if (p === -2) { scr[490 + nbn++] = s; if (b[s - 10] === -1) mb--; } else if (p === 3) { bp += scr[432 + SQCOL[s]]; if (b[s + 10] === 1) mb++; } else if (p === -3) { bp -= scr[434 + SQCOL[s]]; if (b[s - 10] === -1) mb--; } } scr[FOFF + F_BPAWNS] = bp; scr[FOFF + F_MBEHIND] = mb; if (kdw < 99 && kdb < 99) scr[FOFF + F_KPDIST] = kdw - kdb; for (let who = 0; who < 2; who++) { const sgn = who === 0 ? 1 : -1, ek = who === 0 ? bk : wk; if (ek === 0) continue; const mine = who === 0 ? 128 : 256, theirs = who === 0 ? 256 : 128, front = -20 * sgn; let weak = 0; for (let j = 0; j < 12; j++) { const u = j < 9 ? ek + (Math.floor(j / 3) - 1) * 10 + (j % 3 - 1) : ek + front + (j - 10); if (u < 0 || u >= 120 || b[u] === OFF) continue; if (scr[mine + u] > 0 && scr[theirs + u] <= 1) weak++; } let nchk = 0; const nk = who === 0 ? nwn : nbn; if (nk > 0) { const kb = who === 0 ? 480 : 490; for (let k = 0; k < 8; k++) { const u = ek + N_DIRS[k], q = b[u]; if (q === OFF || q * sgn > 0 || scr[theirs + u] > 0) continue; for (let j = 0; j < nk; j++) if (KREL[u - scr[kb + j] + 120]) { nchk++; break; } } } let lchk = 0; for (let k = 0; k < 8; k++) { const d = k < 4 ? B_DIRS[k] : R_DIRS[k - 4]; let u = ek + d; while (b[u] === 0) { if (scr[mine + u] > 0 && scr[theirs + u] === 0) lchk++; u += d; } } scr[FOFF + F_KZW] += sgn * weak; scr[FOFF + F_SCN] += sgn * nchk; scr[FOFF + F_SCL] += sgn * lchk; } for (let who = 0; who < 2; who++) { const sgn = who === 0 ? 1 : -1, npcs = who === 0 ? wpieces : bpieces; if (npcs === 0) continue; let cnt = 0; for (let j = 0; j < 12; j++) { const u = SPACE_SQ[who * 12 + j]; if (b[u] === sgn || b[u + 9 * sgn] === -sgn || b[u + 11 * sgn] === -sgn) continue; cnt++; let v = u + 10 * sgn; for (let k = 0; k < 3; k++) { if (b[v] === sgn) { cnt++; break; } if (b[v] === OFF) break; v += 10 * sgn; } } scr[FOFF + F_SPACE] += sgn * Math.floor(cnt * npcs / 4); } } leastAttacker(sq, side) { const b = this.b; if (side === 1) { if (b[sq - 9] === 1) return sq - 9; if (b[sq - 11] === 1) return sq - 11; } else { if (b[sq + 9] === -1) return sq + 9; if (b[sq + 11] === -1) return sq + 11; } for (let i = 0; i < 8; i++) if (b[sq + N_DIRS[i]] === 2 * side) return sq + N_DIRS[i]; let best = 0, bestv = 99; for (let i = 0; i < 4; i++) { const d = B_DIRS[i]; let t = sq + d; while (b[t] === 0) t += d; const p = b[t] * side; if (b[t] !== OFF && (p === 3 || p === 5) && p < bestv) { best = t; bestv = p; } } for (let i = 0; i < 4; i++) { const d = R_DIRS[i]; let t = sq + d; while (b[t] === 0) t += d; const p = b[t] * side; if (b[t] !== OFF && (p === 4 || p === 5) && p < bestv) { best = t; bestv = p; } } if (best !== 0) return best; for (let i = 0; i < 8; i++) if (b[sq + K_DIRS[i]] === 6 * side) return sq + K_DIRS[i]; return 0; } see(fr, to) { const b = this.b, gain = new Int32Array(40), rsq = [], rpc = []; const side = b[fr] > 0 ? 1 : -1; gain[0] = VAL[Math.abs(b[to])]; let attVal = VAL[Math.abs(b[fr])]; rsq.push(fr); rpc.push(b[fr]); b[fr] = 0; let stm = -side, d = 0; while (d < 38) { const a = this.leastAttacker(to, stm); if (a === 0) break; d++; gain[d] = attVal - gain[d - 1]; if (Math.max(-gain[d - 1], gain[d]) < 0) break; attVal = VAL[Math.abs(b[a])]; rsq.push(a); rpc.push(b[a]); b[a] = 0; stm = -stm; } for (let k = 0; k < rsq.length; k++) b[rsq[k]] = rpc[k]; while (d > 0) { gain[d - 1] = -Math.max(-gain[d - 1], gain[d]); d--; } return gain[0]; } // ------------------------------------------------------------ search isRepetition() { const st = this.st, i = st[6], lo = this.hl[i], hi = this.hh_[i]; let low = i - st[3]; if (low < 0) low = 0; for (let k = i - 2; k >= low; k -= 2) if (this.hl[k] === lo && this.hh_[k] === hi) return true; return false; } hasPieces(side) { const b = this.b; for (let s = 21; s < 99; s++) { if (b[s] === OFF) continue; const p = b[s] * side; if (p >= 2 && p <= 5) return true; } return false; } timeUp() { this.nodes++; if ((this.nodes & 2047) === 0) { if (performance.now() >= this.deadline || (this.nodeLimit > 0 && this.nodes >= this.nodeLimit) || (this.stopFlag && Atomics.load(this.stopFlag, 0) !== 0)) this.stop = true; } return this.stop; } prevPT(ply, back) { if (ply < back) return -1; const v = this.scs[(ply - back) * MAXMOVES + S_MOVE]; return v >= 0 && v < 832 ? v : -1; } quietHist(m, hi, p1, p2) { const hh = this.hist, pt = (this.b[mfrom(m)] + 6) * 64 + SQ64[mto(m)]; let h = hh[H_BUT + hi * 14400 + mfrom(m) * 120 + mto(m)]; if (p1 >= 0) h += hh[H_CONT + p1 * 832 + pt]; if (p2 >= 0) h += hh[H_CONT + p2 * 832 + pt]; return h; } scoreMoves(base, n, ttmove, ply, side) { const b = this.b, mv = this.mvs, sc = this.scs, hi = side === 1 ? 0 : 1; if (this.cfg[8]) { const p1 = this.prevPT(ply, 1), p2 = this.prevPT(ply, 2), cm = p1 >= 0 ? this.hist[H_CM + p1] : 0; for (let i = 0; i < n; i++) { const m = mv[base + i]; if (m === ttmove) { sc[base + i] = 10000000; continue; } const to = mto(m), cap = b[to], pr = mpromo(m); if (cap !== 0 || mflag(m) === 2 || pr !== 0) { const victim = cap !== 0 ? VAL[Math.abs(cap)] : 100, attacker = VAL[Math.abs(b[mfrom(m)])]; sc[base + i] = 1000000 + 10 * victim - Math.floor(attacker / 10) + (pr ? VAL[pr] : 0); } else if (m === this.kil[ply * 2]) sc[base + i] = 900000; else if (m === this.kil[ply * 2 + 1]) sc[base + i] = 800000; else if (m === cm) sc[base + i] = 700000; else sc[base + i] = this.quietHist(m, hi, p1, p2); } return; } for (let i = 0; i < n; i++) { const m = mv[base + i]; if (m === ttmove) { sc[base + i] = 10000000; continue; } const to = mto(m), cap = b[to], pr = mpromo(m); if (cap !== 0 || mflag(m) === 2 || pr !== 0) { const victim = cap !== 0 ? VAL[Math.abs(cap)] : 100, attacker = VAL[Math.abs(b[mfrom(m)])]; sc[base + i] = 1000000 + 10 * victim - Math.floor(attacker / 10) + (pr ? VAL[pr] : 0); } else if (m === this.kil[ply * 2]) sc[base + i] = 900000; else if (m === this.kil[ply * 2 + 1]) sc[base + i] = 800000; else sc[base + i] = this.hist[H_BUT + hi * 14400 + mfrom(m) * 120 + to]; } } pick(base, i, n) { const mv = this.mvs, sc = this.scs; let best = i; for (let j = i + 1; j < n; j++) if (sc[base + j] > sc[base + best]) best = j; if (best !== i) { let t = mv[base + i]; mv[base + i] = mv[base + best]; mv[base + best] = t; t = sc[base + i]; sc[base + i] = sc[base + best]; sc[base + best] = t; } } qsearch(alpha, beta, ply) { if (this.timeUp()) return 0; const klo = this.hl[this.st[6]], khi = this.hh_[this.st[6]], qidx = klo & this.ttMask; const hit = this.ttk[qidx] === klo && this.ttc[qidx] === khi; if (this.cfg[5] && beta - alpha === 1 && hit) { let s = this.tts[qidx]; if (s > MATE_BOUND) s -= ply; else if (s < -MATE_BOUND) s += ply; const f = this.ttf[qidx]; if (f === 0 || (f === 1 && s >= beta) || (f === 2 && s <= alpha)) return s; } const origAlpha = alpha; const stand = this.evaluate(this.st[0]); if (ply >= MAXPLY - 1) return stand; if (stand >= beta) { if (this.cfg[5] && !hit) { this.ttk[qidx] = klo; this.ttc[qidx] = khi; this.ttm[qidx] = 0; this.ttd[qidx] = 0; this.ttf[qidx] = 1; this.tts[qidx] = stand; } return stand; } if (stand > alpha) alpha = stand; const base = ply * MAXMOVES, n = this.gen(this.mvs, base, true), side = this.st[0]; this.scoreMoves(base, n, 0, ply, side); for (let i = 0; i < n; i++) { this.pick(base, i, n); const m = this.mvs[base + i], cap = this.b[mto(m)]; if (mpromo(m) === 0) { const gain = cap !== 0 ? VAL[Math.abs(cap)] : 100; if (stand + gain + 200 < alpha) continue; if (this.cfg[0] && cap !== 0 && VAL[Math.abs(this.b[mfrom(m)])] > VAL[Math.abs(cap)] && this.see(mfrom(m), mto(m)) < 0) continue; } this.make(m); if (this.attacked(this.kingSq(side), -side)) { this.unmake(); continue; } const s = -this.qsearch(-beta, -alpha, ply + 1); this.unmake(); if (this.stop) return 0; if (s >= beta) { const same = this.ttk[qidx] === klo && this.ttc[qidx] === khi; if (this.cfg[5] && (!same || this.ttd[qidx] <= 0) && Math.abs(s) < MATE_BOUND) { this.ttk[qidx] = klo; this.ttc[qidx] = khi; this.ttm[qidx] = m; this.ttd[qidx] = 0; this.ttf[qidx] = 1; this.tts[qidx] = s; } return s; } if (s > alpha) alpha = s; } const same = this.ttk[qidx] === klo && this.ttc[qidx] === khi; if (this.cfg[5] && (!same || this.ttd[qidx] <= 0) && Math.abs(alpha) < MATE_BOUND) { if (!same) this.ttm[qidx] = 0; this.ttk[qidx] = klo; this.ttc[qidx] = khi; this.ttd[qidx] = 0; this.ttf[qidx] = alpha > origAlpha ? 0 : 2; this.tts[qidx] = alpha; } return alpha; } search(depth, alpha, beta, ply, doNull) { const st = this.st, b = this.b, side = st[0], pvNode = beta - alpha > 1, scs = this.scs, hh = this.hist, cfg = this.cfg; const row = ply * MAXMOVES, excl = scs[row + S_EXCL]; if (ply > 0) { if (st[3] >= 100 || this.isRepetition()) return 0; const ma = -MATE + ply; if (alpha < ma) alpha = ma; const mb = MATE - ply - 1; if (beta > mb) beta = mb; if (alpha >= beta) return alpha; } const chk = this.attacked(this.kingSq(side), -side); if (chk) depth++; if (depth <= 0) return this.qsearch(alpha, beta, ply); if (this.timeUp()) return 0; if (ply >= MAXPLY - 1) return this.evaluate(side); if (ply > this.seldepth) this.seldepth = ply; const klo = this.hl[st[6]], khi = this.hh_[st[6]], idx = klo & this.ttMask; let ttmove = 0; const tthit = this.ttk[idx] === klo && this.ttc[idx] === khi; if (tthit) { ttmove = this.ttm[idx]; if (ply > 0 && !pvNode && excl === 0 && this.ttd[idx] >= depth) { let s = this.tts[idx]; if (s > MATE_BOUND) s -= ply; else if (s < -MATE_BOUND) s += ply; const f = this.ttf[idx]; if (f === 0 || (f === 1 && s >= beta) || (f === 2 && s <= alpha)) return s; } } const hi = side === 1 ? 0 : 1; const raw = this.evaluate(side); let stat = raw; const cidx = H_CORR + hi * CORR_N + (st[7] & (CORR_N - 1)); if (cfg[11] && !chk) { stat = raw + Math.floor(hh[cidx] / 256); if (stat > MATE_BOUND - 1) stat = MATE_BOUND - 1; else if (stat < -MATE_BOUND + 1) stat = -MATE_BOUND + 1; } scs[row + S_STATIC] = chk ? -INF : stat; scs[row + S_MOVE] = -1; let imp = 1; if (cfg[4]) imp = (!chk && ply >= 2 && stat > scs[(ply - 2) * MAXMOVES + S_STATIC]) ? 1 : 0; const base = row; if (excl === 0) { if (cfg[3] && !pvNode && !chk && depth <= 2 && stat + 250 * depth < alpha) { const q = this.qsearch(alpha, alpha + 1, ply); if (q <= alpha) return q; } if (!pvNode && !chk) { if (depth <= 4 && Math.abs(beta) < MATE_BOUND && stat - 90 * (depth - (cfg[4] ? imp : 0)) >= beta) return stat; if (doNull && depth >= 3 && stat >= beta && this.hasPieces(side)) { const R = 3 + Math.floor(depth / 6); this.makeNull(); let s = -this.search(depth - 1 - R, -beta, -beta + 1, ply + 1, false); this.unmakeNull(); if (this.stop) return 0; if (s >= beta) { if (s > MATE_BOUND) s = beta; return s; } } // ProbCut if (cfg[10] && depth >= 5 && Math.abs(beta) < MATE_BOUND) { const rbeta = beta + 200, n = this.gen(this.mvs, base, true); this.scoreMoves(base, n, ttmove, ply, side); for (let i = 0; i < n; i++) { this.pick(base, i, n); const m = this.mvs[base + i]; if (b[mto(m)] === 0) continue; if (this.see(mfrom(m), mto(m)) < rbeta - stat) continue; const pt = (b[mfrom(m)] + 6) * 64 + SQ64[mto(m)]; this.make(m); if (this.attacked(this.kingSq(side), -side)) { this.unmake(); continue; } scs[row + S_MOVE] = pt; let s = -this.qsearch(-rbeta, -rbeta + 1, ply + 1); if (s >= rbeta) s = -this.search(depth - 4, -rbeta, -rbeta + 1, ply + 1, true); this.unmake(); if (this.stop) return 0; if (s >= rbeta) return s; } scs[row + S_MOVE] = -1; } } } if (ttmove === 0 && depth >= 5 && pvNode) depth--; // singular extension let sing = 0; if (cfg[9] && ply > 0 && excl === 0 && ttmove !== 0 && depth >= 7 && ply < (MAXPLY >> 1) && tthit && this.ttd[idx] >= depth - 3 && this.ttf[idx] !== 2 && Math.abs(this.tts[idx]) < MATE_BOUND) { const sbeta = this.tts[idx] - 2 * depth; scs[row + S_EXCL] = ttmove; const s = this.search((depth - 1) >> 1, sbeta - 1, sbeta, ply, false); scs[row + S_EXCL] = 0; if (this.stop) return 0; if (s < sbeta) sing = 1; else if (sbeta >= beta) return sbeta; scs[row + S_STATIC] = chk ? -INF : stat; } const n = this.gen(this.mvs, base, false); this.scoreMoves(base, n, ttmove, ply, side); if (cfg[1]) { for (let i = 0; i < n; i++) { const m = this.mvs[base + i], c = b[mto(m)]; if (m !== ttmove && c !== 0 && mpromo(m) === 0 && VAL[Math.abs(b[mfrom(m)])] > VAL[Math.abs(c)] && this.see(mfrom(m), mto(m)) < 0) scs[base + i] = -1000000 + VAL[Math.abs(c)]; } } const p1 = this.prevPT(ply, 1), p2 = this.prevPT(ply, 2); let best = -INF, bestmove = 0, legal = 0, quietsTried = 0; const origAlpha = alpha; for (let i = 0; i < n; i++) { this.pick(base, i, n); const m = this.mvs[base + i]; if (m === excl) continue; const cap = b[mto(m)], quiet = cap === 0 && mflag(m) !== 2 && mpromo(m) === 0; if (ply === 0 && this.rootFilter && !this.rootFilter.has(m)) continue; const pt = (b[mfrom(m)] + 6) * 64 + SQ64[mto(m)]; const qh = quiet && cfg[12] ? this.quietHist(m, hi, p1, p2) : 0; this.make(m); if (this.attacked(this.kingSq(side), -side)) { this.unmake(); continue; } legal++; const gives = this.attacked(this.kingSq(-side), side); if (quiet && !pvNode && !chk && !gives && legal > 1 && best > -MATE_BOUND) { if (depth <= 2 && stat + 120 * depth <= alpha) { this.unmake(); continue; } if (depth <= 3 && quietsTried >= (imp ? 4 + 4 * depth * depth : 3 + 2 * depth * depth)) { this.unmake(); continue; } } if (quiet) quietsTried++; scs[row + S_MOVE] = pt; const nd = depth - 1 + ((sing && m === ttmove) ? 1 : 0); let s; if (legal === 1) s = -this.search(nd, -beta, -alpha, ply + 1, true); else { let r = 0; if (depth >= 3 && legal > 3 && quiet && !chk && !gives) { r = LMR[Math.min(depth, 63) * 64 + Math.min(legal, 63)]; if (pvNode) r--; if (m === this.kil[ply * 2] || m === this.kil[ply * 2 + 1]) r--; if (cfg[2]) { const hv = hh[H_BUT + hi * 14400 + mfrom(m) * 120 + mto(m)]; if (hv > 2000) r--; else if (hv === 0 && legal > 8) r++; } if (cfg[12]) { r -= Math.floor(qh / 12000); if (!imp) r++; } if (r < 0) r = 0; if (r > nd - 1) r = nd - 1; if (r < 0) r = 0; } s = -this.search(nd - r, -alpha - 1, -alpha, ply + 1, true); if (s > alpha && r > 0) s = -this.search(nd, -alpha - 1, -alpha, ply + 1, true); if (s > alpha && s < beta) s = -this.search(nd, -beta, -alpha, ply + 1, true); } this.unmake(); if (this.stop) return 0; if (s > best) { best = s; bestmove = m; if (ply === 0) { this.rootBest = m; this.rootScore = s; } if (s > alpha) { alpha = s; if (s >= beta) { if (quiet) { if (this.kil[ply * 2] !== m) { this.kil[ply * 2 + 1] = this.kil[ply * 2]; this.kil[ply * 2] = m; } if (cfg[8]) { const bonus = depth > 13 ? 4000 : 20 * depth * depth + 100 * depth - 80; grav(hh, H_BUT + hi * 14400 + mfrom(m) * 120 + mto(m), bonus); if (p1 >= 0) { grav(hh, H_CONT + p1 * 832 + pt, bonus); hh[H_CM + p1] = m; } if (p2 >= 0) grav(hh, H_CONT + p2 * 832 + pt, bonus); for (let j = 0; j < i; j++) { const q = this.mvs[base + j]; if (q === excl || b[mto(q)] !== 0 || mflag(q) === 2 || mpromo(q) !== 0) continue; grav(hh, H_BUT + hi * 14400 + mfrom(q) * 120 + mto(q), -bonus); const qt = (b[mfrom(q)] + 6) * 64 + SQ64[mto(q)]; if (p1 >= 0) grav(hh, H_CONT + p1 * 832 + qt, -bonus); if (p2 >= 0) grav(hh, H_CONT + p2 * 832 + qt, -bonus); } } else { const hidx = H_BUT + hi * 14400 + mfrom(m) * 120 + mto(m); hh[hidx] += depth * depth; if (hh[hidx] > 400000) for (let x = 0; x < 14400; x++) hh[H_BUT + hi * 14400 + x] = Math.floor(hh[H_BUT + hi * 14400 + x] / 2); } } break; } } } } if (legal === 0) { if (excl !== 0) return alpha; return chk ? -MATE + ply : 0; } const flag = best >= beta ? 1 : (best > origAlpha ? 0 : 2); if (excl !== 0) return best; if (cfg[11] && !chk && Math.abs(best) < MATE_BOUND && (bestmove === 0 || (b[mto(bestmove)] === 0 && mpromo(bestmove) === 0))) { if (!(flag === 1 && best <= stat) && !(flag === 2 && best >= stat)) { const w = depth < 15 ? depth + 1 : 16; let tgt = (best - raw) * 256; if (tgt > 256 * 64) tgt = 256 * 64; else if (tgt < -256 * 64) tgt = -256 * 64; hh[cidx] = Math.floor((hh[cidx] * (256 - w) + tgt * w) / 256); } } let store = best; if (store > MATE_BOUND) store += ply; else if (store < -MATE_BOUND) store -= ply; if (this.ttk[idx] !== klo || this.ttc[idx] !== khi || depth >= this.ttd[idx] || flag === 0) { this.ttk[idx] = klo; this.ttc[idx] = khi; this.ttm[idx] = bestmove; this.ttd[idx] = depth; this.ttf[idx] = flag; this.tts[idx] = store; } return best; } pvLine(first, maxlen = 12) { const line = [first]; let made = 0; this.make(first); made++; const seen = new Set([this.hl[this.st[6]] + ":" + this.hh_[this.st[6]]]); while (line.length < maxlen) { const i = this.st[6], klo = this.hl[i], khi = this.hh_[i], idx = klo & this.ttMask; if (this.ttk[idx] !== klo || this.ttc[idx] !== khi || this.ttm[idx] === 0) break; const m = this.ttm[idx]; if (!this.legal().includes(m)) break; this.make(m); made++; line.push(m); const key = this.hl[this.st[6]] + ":" + this.hh_[this.st[6]]; if (seen.has(key)) break; seen.add(key); } for (let k = 0; k < made; k++) this.unmake(); return line.map(Engine.uci); } newGame() { this.ttk.fill(0); this.ttc.fill(0); this.hist.fill(0); } resetPlies() { for (let p = 0; p < MAXPLY + 2; p++) { this.scs[p * MAXMOVES + S_EXCL] = 0; this.scs[p * MAXMOVES + S_MOVE] = -1; } } // score EVERY legal move with a full-window search at each depth rankAll(fen, moves, movetime, onInfo = null) { movetime = Math.min(movetime, 29500); this.setFen(fen); for (const u of moves) this.pushUci(u); const legal = this.legal(); const start = performance.now(); this.deadline = start + movetime; this.stop = false; this.nodes = 0; this.seldepth = 0; this.kil.fill(0); this.resetPlies(); let ranked = legal.map(m => [m, 0]), reached = 0; for (let d = 1; d <= MAXPLY - 4; d++) { const cur = []; for (const [m] of ranked) { this.make(m); const s = -this.search(d - 1, -INF, INF, 1, true); this.unmake(); if (this.stop) break; cur.push([m, s]); } if (this.stop) break; ranked = cur.sort((x, y) => y[1] - x[1]); reached = d; if (onInfo) onInfo({ legal: legal.length, depth: d, ranked: ranked.map(([m, s]) => [Engine.uci(m), s]) }); if (performance.now() - start > movetime * 0.5) break; } return { legal: legal.length, depth: reached, nodes: this.nodes, ranked: ranked.map(([m, s]) => [Engine.uci(m), s]) }; } // Lazy SMP helper: search the same position, results reach the main worker through the shared table helperGo(fen, moves, movetime, k) { this.setFen(fen); for (const u of moves) this.pushUci(u); this.deadline = performance.now() + movetime; this.stop = false; this.nodes = 0; this.seldepth = 0; this.kil.fill(0); this.resetPlies(); this.rootFilter = null; for (let x = 0; x < H_CM; x++) this.hist[x] = Math.floor(this.hist[x] / 4); for (let d = 1 + (k % 2); d <= MAXPLY - 4; d++) { this.search(d, -INF, INF, 0, true); if (this.stop) break; } return { nodes: this.nodes }; } // fen + uci moves -> best move; onInfo(result) after each finished depth go(fen, moves, movetime, maxDepth = MAXPLY - 4, onInfo = null, rootMoves = null) { movetime = Math.min(movetime, 29500); this.setFen(fen); for (const u of moves) this.pushUci(u); let legal = this.legal(); this.rootFilter = null; if (rootMoves && rootMoves.length) { const want = new Set(rootMoves); const sub = legal.filter(m => want.has(Engine.uci(m))); if (sub.length && sub.length < legal.length) { legal = sub; this.rootFilter = new Set(sub); } } if (!legal.length) return { move: null }; const start = performance.now(); this.deadline = start + movetime; this.stop = false; this.nodes = 0; this.seldepth = 0; this.kil.fill(0); for (let x = 0; x < H_CM; x++) this.hist[x] = Math.floor(this.hist[x] / 4); this.resetPlies(); let best = legal[0], bestScore = 0, prev = 0; let result = { move: Engine.uci(best), source: "search", score: 0, depth: 0, pv: [Engine.uci(best)] }; if (legal.length === 1) maxDepth = Math.min(maxDepth, 4); for (let d = 1; d <= maxDepth; d++) { let alpha = -INF, beta = INF, window = 35, s = 0; if (d >= 4) { alpha = prev - window; beta = prev + window; } for (;;) { s = this.search(d, alpha, beta, 0, true); if (this.stop) break; if (s <= alpha) { alpha = Math.max(-INF, alpha - window * 3); window *= 3; } else if (s >= beta) { beta = Math.min(INF, beta + window * 3); window *= 3; } else break; } if (this.stop) { if (this.rootBest && this.rootBest !== best && d > 1 && this.rootScore > bestScore) { best = this.rootBest; bestScore = this.rootScore; result.move = Engine.uci(best); result.score = bestScore; } break; } best = this.rootBest || best; bestScore = s; prev = s; const el = performance.now() - start; result = { move: Engine.uci(best), source: "search", score: bestScore, depth: d, seldepth: this.seldepth, nodes: this.nodes, time_ms: Math.round(el), nps: Math.round(this.nodes / Math.max(el, 1) * 1000), pv: this.pvLine(best) }; if (Math.abs(bestScore) > MATE_BOUND) { const plies = MATE - Math.abs(bestScore); result.mate = Math.floor((plies + 1) / 2) * (bestScore > 0 ? 1 : -1); } if (onInfo) onInfo(result); if (Math.abs(bestScore) > MATE_BOUND && d > (MATE - Math.abs(bestScore)) + 2) break; if (el > movetime * 0.55) break; } result.nodes = this.nodes; result.time_ms = Math.round(performance.now() - start); return result; } } function mopup(wk, lk) { const l64 = SQ64[lk], w64 = SQ64[wk], lf = l64 & 7, lr = l64 >> 3; const cd = Math.max(3 - lf, lf - 4) + Math.max(3 - lr, lr - 4); const kd = Math.abs(lf - (w64 & 7)) + Math.abs(lr - (w64 >> 3)); return 300 + 20 * cd + 6 * (14 - kd); } // ------------------------------------------------------------ worker glue if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) { let eng = null, paramsKey = null, shared = null; const engineFor = (msg) => { if (!eng || paramsKey !== msg.paramsKey) { eng = new Engine(msg.params, 20, undefined, shared); paramsKey = msg.paramsKey; } return eng; }; self.onmessage = (ev) => { const msg = ev.data; if (msg.movetime) msg.movetime = Math.min(msg.movetime, 29500); // hard 30 s ceiling per turn if (msg.cmd === "shared") { shared = msg.shared; eng = null; return; } if (msg.cmd === "helper") { const r = engineFor(msg).helperGo(msg.fen, msg.moves, msg.movetime, msg.k); self.postMessage({ type: "helperdone", id: msg.id, result: r }); return; } if (msg.cmd === "go") { engineFor(msg); const r = eng.go(msg.fen, msg.moves, msg.movetime, msg.depth || MAXPLY - 4, (info) => self.postMessage({ type: "info", id: msg.id, info }), msg.rootMoves || null); eng.rootFilter = null; self.postMessage({ type: "done", id: msg.id, result: r }); } else if (msg.cmd === "rank") { engineFor(msg); const r = eng.rankAll(msg.fen, msg.moves, msg.movetime, (info) => self.postMessage({ type: "rankinfo", id: msg.id, info })); self.postMessage({ type: "rankdone", id: msg.id, result: r }); } else if (msg.cmd === "newgame" && eng) eng.newGame(); }; } if (typeof module !== "undefined") module.exports = { Engine };