From bfe59b931653a1068a1bc677c05f36d55b02e032 Mon Sep 17 00:00:00 2001 From: "Steinar H. Gunderson" Date: Sun, 25 Dec 2022 21:02:13 +0100 Subject: [PATCH] Chess.js: In move_from_san(), only bother generating relevant candidate moves. --- www/js/chess.js | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/www/js/chess.js b/www/js/chess.js index 531a08f..3c97b64 100644 --- a/www/js/chess.js +++ b/www/js/chess.js @@ -1176,10 +1176,10 @@ var Chess = function(fen) { return ''; } - // Find all pseudolegal moves featuring the given piece attacking + // Find all pseudolegal moves featuring the given piece moving to // the given square (using symmetry of all non-pawn-or-castle moves, - // we simply generate moves backwards). Does not support kings - // or pawns. Assumes there's not already a piece of our own color + // we simply generate moves backwards). Does not support pawns. + // Assumes there's not already a piece of our own color // on the destination square. function find_attacking_moves(to, piece, us) { let moves = []; @@ -1204,8 +1204,8 @@ var Chess = function(fen) { break; } - /* break if knight */ - if (piece === 'n') break; + /* break if knight or king */ + if (piece === 'n' || piece === 'k') break; } } @@ -1259,7 +1259,23 @@ var Chess = function(fen) { } } - var moves = generate_moves(); + let moves; + let piece_matches = clean_move.match(/^([NBRQK])x?([a-h][1-8])$/); + if (piece_matches) { + // Only look for moves by the given piece to the given square. + let to = SQUARES[piece_matches[2]]; + if (board[to] != null && board[to].color === turn) { + // Cannot capture our own piece. + return null; + } + moves = find_attacking_moves(to, piece_matches[1].toLowerCase(), turn); + // Legal moves only. + moves = possibly_filter_moves(moves, turn, true); + } else { + // Fallback (also used for pawns): Any (legal) moves. + moves = generate_moves(); + } + for (var i = 0, len = moves.length; i < len; i++) { // try the strict parser first, then the sloppy parser if requested // by the user -- 2.39.2