From c8aa90ee91f79165014d359e696c4c7947bdf43b Mon Sep 17 00:00:00 2001 From: claude Date: Sat, 10 Oct 2026 15:59:25 +0200 Subject: [PATCH] Add chess rules engine for the board analyser (legal moves, SAN, FEN, Chess960) --- OpenBench/static/chess.js | 607 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 607 insertions(+) create mode 100644 OpenBench/static/chess.js diff --git a/OpenBench/static/chess.js b/OpenBench/static/chess.js new file mode 100644 index 0000000..c0f879f --- /dev/null +++ b/OpenBench/static/chess.js @@ -0,0 +1,607 @@ +/* OpenBench chess rules: just enough chess for the event board analyser. + + - FEN in and out, including Chess960 ( Shredder and X-FEN castling fields ) + - Legal move generation, with castling, en passant, and promotions + - SAN parsing, so a PGN movetext can be replayed position by position + + No dependencies. Works in the browser ( window.OBChess ) and in Node, where + perft() is used to check the move generator against known node counts. */ + +(function (root, factory) { + if (typeof module === 'object' && module.exports) module.exports = factory(); + else root.OBChess = factory(); +})(typeof self !== 'undefined' ? self : this, function () { + 'use strict'; + + var START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'; + var FILES = 'abcdefgh'; + + var KNIGHT = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]]; + var KING = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; + var DIAG = [[1, 1], [1, -1], [-1, 1], [-1, -1]]; + var ORTHO = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + + var VALUES = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 }; + + /* Squares are numbered a1 = 0, b1 = 1, ... h8 = 63 */ + + function sq(file, rank) { return rank * 8 + file; } + function fileOf(square) { return square & 7; } + function rankOf(square) { return square >> 3; } + function name(square) { return FILES[square & 7] + ((square >> 3) + 1); } + + function parseSquare(text) { + if (!/^[a-h][1-8]$/.test(text || '')) return -1; + return sq(FILES.indexOf(text[0]), parseInt(text[1], 10) - 1); + } + + function colorOf(piece) { return piece === piece.toUpperCase() ? 'w' : 'b'; } + + function Position() { + this.board = new Array(64).fill(null); + this.turn = 'w'; + this.castling = { w: { k: -1, q: -1 }, b: { k: -1, q: -1 } }; // Rook files + this.ep = -1; + this.halfmove = 0; + this.fullmove = 1; + this.king = { w: -1, b: -1 }; + } + + Position.fromFen = function (fen) { + + var parts = String(fen).trim().split(/\s+/); + if (parts.length < 2) throw new Error('Bad FEN'); + + var rows = parts[0].split('/'); + if (rows.length !== 8) throw new Error('Bad FEN: expected 8 ranks'); + + var pos = new Position(); + + for (var row = 0; row < 8; row++) { + + var rank = 7 - row, file = 0; + + for (var i = 0; i < rows[row].length; i++) { + + var ch = rows[row][i]; + + if (ch >= '1' && ch <= '8') { + file += parseInt(ch, 10); + } else if ('pnbrqkPNBRQK'.indexOf(ch) !== -1) { + if (file > 7) throw new Error('Bad FEN: rank too long'); + pos.board[sq(file, rank)] = ch; + if (ch === 'K') pos.king.w = sq(file, rank); + if (ch === 'k') pos.king.b = sq(file, rank); + file++; + } else { + throw new Error('Bad FEN: unknown piece ' + ch); + } + } + + if (file !== 8) throw new Error('Bad FEN: rank length'); + } + + if (pos.king.w < 0 || pos.king.b < 0) throw new Error('Bad FEN: missing king'); + + pos.turn = parts[1] === 'b' ? 'b' : 'w'; + pos.ep = parts[3] && parts[3] !== '-' ? parseSquare(parts[3]) : -1; + pos.halfmove = parseInt(parts[4], 10) || 0; + pos.fullmove = parseInt(parts[5], 10) || 1; + + pos.parseCastling(parts[2] || '-'); + + return pos; + }; + + Position.prototype.parseCastling = function (field) { + + if (field === '-') return; + + for (var i = 0; i < field.length; i++) { + + var ch = field[i]; + var color = ch === ch.toUpperCase() ? 'w' : 'b'; + var rank = color === 'w' ? 0 : 7; + var king = this.king[color]; + + if (rankOf(king) !== rank) continue; + + var kingFile = fileOf(king); + var rook = color === 'w' ? 'R' : 'r'; + var lower = ch.toLowerCase(); + var side = null, rookFile = -1, f; + + if (lower === 'k') { + side = 'k'; // Outermost rook, as X-FEN says + for (f = 7; f > kingFile; f--) if (this.board[sq(f, rank)] === rook) { rookFile = f; break; } + } else if (lower === 'q') { + side = 'q'; + for (f = 0; f < kingFile; f++) if (this.board[sq(f, rank)] === rook) { rookFile = f; break; } + } else if (lower >= 'a' && lower <= 'h') { + rookFile = FILES.indexOf(lower); // Shredder-FEN names the file + side = rookFile > kingFile ? 'k' : 'q'; + } + + if (side && rookFile >= 0 && this.board[sq(rookFile, rank)] === rook) { + this.castling[color][side] = rookFile; + } + } + }; + + Position.prototype.toFen = function () { + + var rows = []; + + for (var rank = 7; rank >= 0; rank--) { + + var row = '', empty = 0; + + for (var file = 0; file < 8; file++) { + var piece = this.board[sq(file, rank)]; + if (!piece) { empty++; continue; } + if (empty) { row += empty; empty = 0; } + row += piece; + } + + if (empty) row += empty; + rows.push(row); + } + + var rights = '', self = this; + + ['w', 'b'].forEach(function (color) { + ['k', 'q'].forEach(function (side) { + var file = self.castling[color][side]; + if (file < 0) return; + var letter = (side === 'k' ? file === 7 : file === 0) ? side : FILES[file]; + rights += color === 'w' ? letter.toUpperCase() : letter; + }); + }); + + return [rows.join('/'), this.turn, rights || '-', this.ep >= 0 ? name(this.ep) : '-', + this.halfmove, this.fullmove].join(' '); + }; + + /* One character per square, a1 first. "." is an empty square. */ + + Position.prototype.boardString = function () { + return this.board.map(function (piece) { return piece || '.'; }).join(''); + }; + + Position.prototype.isAttacked = function (square, by) { + + var board = this.board, f = fileOf(square), r = rankOf(square), i, nf, nr, p; + + var pawn = by === 'w' ? 'P' : 'p', knight = by === 'w' ? 'N' : 'n'; + var king = by === 'w' ? 'K' : 'k', bishop = by === 'w' ? 'B' : 'b'; + var rook = by === 'w' ? 'R' : 'r', queen = by === 'w' ? 'Q' : 'q'; + + // A white pawn attacks upwards, so it sits one rank below the target + var pr = r + (by === 'w' ? -1 : 1); + if (pr >= 0 && pr < 8) { + if (f > 0 && board[sq(f - 1, pr)] === pawn) return true; + if (f < 7 && board[sq(f + 1, pr)] === pawn) return true; + } + + for (i = 0; i < 8; i++) { + nf = f + KNIGHT[i][0]; nr = r + KNIGHT[i][1]; + if (nf >= 0 && nf < 8 && nr >= 0 && nr < 8 && board[sq(nf, nr)] === knight) return true; + } + + for (i = 0; i < 8; i++) { + nf = f + KING[i][0]; nr = r + KING[i][1]; + if (nf >= 0 && nf < 8 && nr >= 0 && nr < 8 && board[sq(nf, nr)] === king) return true; + } + + for (i = 0; i < 8; i++) { + + var diagonal = i < 4, dir = diagonal ? DIAG[i] : ORTHO[i - 4]; + var slider = diagonal ? bishop : rook; + + nf = f + dir[0]; nr = r + dir[1]; + + while (nf >= 0 && nf < 8 && nr >= 0 && nr < 8) { + p = board[sq(nf, nr)]; + if (p) { + if (p === slider || p === queen) return true; + break; + } + nf += dir[0]; nr += dir[1]; + } + } + + return false; + }; + + Position.prototype.inCheck = function () { + return this.isAttacked(this.king[this.turn], this.turn === 'w' ? 'b' : 'w'); + }; + + function newMove(from, to, piece, captured) { + return { f: from, t: to, p: piece, cap: captured || null, promo: null, ep: false, castle: null, rook: -1, rookTo: -1 }; + } + + Position.prototype.pseudoMoves = function () { + + var moves = [], board = this.board, us = this.turn, them = us === 'w' ? 'b' : 'w'; + var s, f, r, i, nf, nr, target, move, type, dirs, dir, df; + + var promotions = ['q', 'r', 'b', 'n']; + + for (s = 0; s < 64; s++) { + + var piece = board[s]; + if (!piece || colorOf(piece) !== us) continue; + + type = piece.toLowerCase(); + f = fileOf(s); r = rankOf(s); + + if (type === 'p') { + + var step = us === 'w' ? 1 : -1; + var home = us === 'w' ? 1 : 6; + var last = us === 'w' ? 7 : 0; + var one = sq(f, r + step); + + if (!board[one]) { + + if (r + step === last) { + for (i = 0; i < 4; i++) { move = newMove(s, one, piece); move.promo = promotions[i]; moves.push(move); } + } else { + moves.push(newMove(s, one, piece)); + if (r === home && !board[sq(f, r + 2 * step)]) moves.push(newMove(s, sq(f, r + 2 * step), piece)); + } + } + + for (df = -1; df <= 1; df += 2) { + + nf = f + df; + if (nf < 0 || nf > 7) continue; + + var to = sq(nf, r + step); + target = board[to]; + + if (target && colorOf(target) === them) { + + if (r + step === last) { + for (i = 0; i < 4; i++) { move = newMove(s, to, piece, target); move.promo = promotions[i]; moves.push(move); } + } else { + moves.push(newMove(s, to, piece, target)); + } + + } else if (!target && to === this.ep) { + move = newMove(s, to, piece, them === 'w' ? 'P' : 'p'); + move.ep = true; + moves.push(move); + } + } + + } else if (type === 'n' || type === 'k') { + + var offsets = type === 'n' ? KNIGHT : KING; + + for (i = 0; i < 8; i++) { + nf = f + offsets[i][0]; nr = r + offsets[i][1]; + if (nf < 0 || nf > 7 || nr < 0 || nr > 7) continue; + target = board[sq(nf, nr)]; + if (!target || colorOf(target) === them) moves.push(newMove(s, sq(nf, nr), piece, target)); + } + + } else { + + dirs = type === 'b' ? DIAG : type === 'r' ? ORTHO : DIAG.concat(ORTHO); + + for (i = 0; i < dirs.length; i++) { + + dir = dirs[i]; + nf = f + dir[0]; nr = r + dir[1]; + + while (nf >= 0 && nf < 8 && nr >= 0 && nr < 8) { + target = board[sq(nf, nr)]; + if (!target) moves.push(newMove(s, sq(nf, nr), piece)); + else { if (colorOf(target) === them) moves.push(newMove(s, sq(nf, nr), piece, target)); break; } + nf += dir[0]; nr += dir[1]; + } + } + } + } + + this.castlingMoves(moves); + return moves; + }; + + Position.prototype.castlingMoves = function (moves) { + + var board = this.board, us = this.turn, them = us === 'w' ? 'b' : 'w'; + var back = us === 'w' ? 0 : 7, king = this.king[us], self = this; + + if (rankOf(king) !== back || this.isAttacked(king, them)) return; + + ['k', 'q'].forEach(function (side) { + + var rookFile = self.castling[us][side]; + if (rookFile < 0) return; + + var rookSq = sq(rookFile, back); + if (board[rookSq] !== (us === 'w' ? 'R' : 'r')) return; + + var kingFile = fileOf(king); + var kingTo = side === 'k' ? 6 : 2; + var rookTo = side === 'k' ? 5 : 3; + var file; + + // Everything on the paths of the King and the Rook must be empty, apart from those two + var span = function (a, b, visit) { + for (var x = Math.min(a, b); x <= Math.max(a, b); x++) visit(x); + }; + + var clear = true; + var empty = function (x) { + var square = sq(x, back); + if (square !== king && square !== rookSq && board[square]) clear = false; + }; + + span(kingFile, kingTo, empty); + span(rookFile, rookTo, empty); + if (!clear) return; + + // The King may not pass through, or land on, an attacked square + var safe = true; + span(kingFile, kingTo, function (x) { if (self.isAttacked(sq(x, back), them)) safe = false; }); + if (!safe) return; + + var move = newMove(king, sq(kingTo, back), board[king]); + move.castle = side; + move.rook = rookSq; + move.rookTo = sq(rookTo, back); + moves.push(move); + }); + }; + + Position.prototype.clearRookRights = function (square) { + + var f = fileOf(square), r = rankOf(square), self = this; + + ['w', 'b'].forEach(function (color) { + if (r !== (color === 'w' ? 0 : 7)) return; + if (self.castling[color].k === f) self.castling[color].k = -1; + if (self.castling[color].q === f) self.castling[color].q = -1; + }); + }; + + Position.prototype.make = function (m) { + + var board = this.board, us = this.turn; + + var undo = { + m: m, ep: this.ep, half: this.halfmove, full: this.fullmove, + wk: this.castling.w.k, wq: this.castling.w.q, bk: this.castling.b.k, bq: this.castling.b.q, + kw: this.king.w, kb: this.king.b + }; + + var piece = board[m.f]; + this.ep = -1; + + if (m.castle) { + + board[m.f] = null; + board[m.rook] = null; + board[m.t] = piece; + board[m.rookTo] = us === 'w' ? 'R' : 'r'; + + this.king[us] = m.t; + this.castling[us].k = -1; + this.castling[us].q = -1; + + } else { + + board[m.f] = null; + if (m.ep) board[sq(fileOf(m.t), rankOf(m.f))] = null; + board[m.t] = m.promo ? (us === 'w' ? m.promo.toUpperCase() : m.promo) : piece; + + if (piece === 'K' || piece === 'k') { + this.king[us] = m.t; + this.castling[us].k = -1; + this.castling[us].q = -1; + } + + this.clearRookRights(m.f); + this.clearRookRights(m.t); + + if ((piece === 'P' || piece === 'p') && Math.abs(m.t - m.f) === 16) this.ep = (m.f + m.t) / 2; + } + + this.halfmove = (piece === 'P' || piece === 'p' || m.cap) ? 0 : this.halfmove + 1; + if (us === 'b') this.fullmove++; + this.turn = us === 'w' ? 'b' : 'w'; + + return undo; + }; + + Position.prototype.unmake = function (undo) { + + var m = undo.m, board = this.board; + + this.turn = this.turn === 'w' ? 'b' : 'w'; + var us = this.turn; + + if (m.castle) { + + board[m.t] = null; + board[m.rookTo] = null; + board[m.f] = m.p; + board[m.rook] = us === 'w' ? 'R' : 'r'; + + } else { + + board[m.f] = m.p; + + if (m.ep) { + board[m.t] = null; + board[sq(fileOf(m.t), rankOf(m.f))] = m.cap; + } else { + board[m.t] = m.cap; + } + } + + this.ep = undo.ep; + this.halfmove = undo.half; + this.fullmove = undo.full; + this.castling.w.k = undo.wk; this.castling.w.q = undo.wq; + this.castling.b.k = undo.bk; this.castling.b.q = undo.bq; + this.king.w = undo.kw; this.king.b = undo.kb; + }; + + Position.prototype.legalMoves = function () { + + var legal = [], us = this.turn, them = us === 'w' ? 'b' : 'w'; + var pseudo = this.pseudoMoves(); + + for (var i = 0; i < pseudo.length; i++) { + var undo = this.make(pseudo[i]); + if (!this.isAttacked(this.king[us], them)) legal.push(pseudo[i]); + this.unmake(undo); + } + + return legal; + }; + + var SAN_RE = /^([NBRQK])?([a-h])?([1-8])?x?([a-h][1-8])(?:=?([NBRQnbrq]))?$/; + + Position.prototype.parseSan = function (san) { + + var text = String(san).replace(/[+#!?]+$/, '').trim(); + var moves = this.legalMoves(); + + var castle = /^(O-O-O|0-0-0)$/.test(text) ? 'q' : /^(O-O|0-0)$/.test(text) ? 'k' : null; + + if (castle) { + return moves.filter(function (move) { return move.castle === castle; })[0] || null; + } + + var match = SAN_RE.exec(text); + if (!match) return null; + + var type = (match[1] || 'P').toLowerCase(); + var ff = match[2] ? FILES.indexOf(match[2]) : -1; + var fr = match[3] ? parseInt(match[3], 10) - 1 : -1; + var to = parseSquare(match[4]); + var promo = match[5] ? match[5].toLowerCase() : null; + + var found = moves.filter(function (move) { + if (move.castle || move.t !== to) return false; + if (move.p.toLowerCase() !== type) return false; + if ((move.promo || null) !== promo) return false; + if (ff >= 0 && fileOf(move.f) !== ff) return false; + if (fr >= 0 && rankOf(move.f) !== fr) return false; + return true; + }); + + return found[0] || null; + }; + + function snapshot(pos, move, san, captured) { + + var legal = pos.legalMoves().length; + var check = pos.inCheck(); + var status = legal === 0 ? (check ? 'checkmate' : 'stalemate') : ''; + + return { + fen : pos.toFen(), + board : pos.boardString(), + turn : pos.turn, + from : move ? move.f : -1, + to : move ? move.t : -1, + check : check ? pos.king[pos.turn] : -1, + status : status, + san : san || '', + caps : { w: captured.w, b: captured.b } + }; + } + + /* Replays moves from a start position. Returns every position, the start + position first, and the first move that could not be played ( if any ). */ + + function replay(startFen, sans) { + + var pos = Position.fromFen(startFen || START_FEN); + var captured = { w: '', b: '' }; + var out = [snapshot(pos, null, '', captured)]; + + for (var i = 0; i < sans.length; i++) { + + var move = pos.parseSan(sans[i]); + + if (!move) { + return { positions: out, error: { ply: i, san: sans[i], turn: pos.turn } }; + } + + if (move.cap) captured[pos.turn] += move.cap; + + pos.make(move); + out.push(snapshot(pos, move, sans[i], captured)); + } + + return { positions: out, error: null }; + } + + /* Pulls a coordinate move ( like e2e4 ) out of free text, for engines that + report the illegal move they tried to play */ + + function findUciMove(text) { + + var match = /\b([a-h][1-8])([a-h][1-8])([qrbnQRBN])?\b/.exec(text || ''); + if (!match) return null; + + return { from: parseSquare(match[1]), to: parseSquare(match[2]), text: match[0] }; + } + + function material(boardString) { + + var total = { w: 0, b: 0 }; + + for (var i = 0; i < 64; i++) { + var piece = boardString[i]; + if (piece === '.') continue; + total[colorOf(piece)] += VALUES[piece.toLowerCase()]; + } + + return total; + } + + function perft(fen, depth) { + + var pos = Position.fromFen(fen); + + function walk(d) { + + var moves = pos.legalMoves(); + if (d === 1) return moves.length; + + var nodes = 0; + + for (var i = 0; i < moves.length; i++) { + var undo = pos.make(moves[i]); + nodes += walk(d - 1); + pos.unmake(undo); + } + + return nodes; + } + + return depth === 0 ? 1 : walk(depth); + } + + return { + START_FEN : START_FEN, + Position : Position, + replay : replay, + perft : perft, + material : material, + findUciMove : findUciMove, + squareName : name, + parseSquare : parseSquare, + fileOf : fileOf, + rankOf : rankOf + }; +});