From baf4c19f1dd28a51bf474d9cd652868b80cb781d Mon Sep 17 00:00:00 2001 From: Jesse McDonald Date: Sun, 15 Mar 2020 12:58:14 -0500 Subject: [PATCH] clean up the logic around en passant and pawn promotion --- js/chess.js | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/js/chess.js b/js/chess.js index 98d06f1..23e0a2a 100644 --- a/js/chess.js +++ b/js/chess.js @@ -280,35 +280,32 @@ function movePiece(priorBoard, side, from, to){ from: from, to: to }; + if (took !== ' ') { board.move.took = took; } + if (replaced !== ' ') { board.move.replaced = replaced; } + if (alongside !== ' ') { board.move.alongside = alongside; } + if (type === 'k' && actuallyFrom[0] === 'e' && to[0] === 'g') { board.move.castle = true; boardPut(board, 'h' + actuallyFrom[1], side, ' '); boardPut(board, 'f' + actuallyFrom[1], side, 'r'); } - if (type === 'k' && actuallyFrom[0] === 'e' && to[0] === 'c') { + else if (type === 'k' && actuallyFrom[0] === 'e' && to[0] === 'c') { board.move.queen_castle = true; boardPut(board, 'a' + actuallyFrom[1], side, ' '); boardPut(board, 'd' + actuallyFrom[1], side, 'r'); } - if (type === 'p' && (isDark(side) ? (to[1] === '1') : (to[1] === '8'))) { - board.move.promotion = 'q'; /* TODO: allow other choices */ - type = 'q'; - } - if (alongside === 'p' && (isDark(other) ? (to[1] === '1') : (to[1] === '8'))) { - board.move.promotion = 'q'; /* TODO: allow other choices */ - alongside = 'q'; - } - if (type === 'p' && alongside === ' ' && replaced === ' ' && to[0] !== actuallyFrom[0]) { + else if (type === 'p' && alongside === ' ' && replaced === ' ' && to[0] !== actuallyFrom[0]) { let otherBoard = priorBoard; + /* scan for the opponent's last move, since this could be part of a chain */ while (otherBoard && otherBoard.move && otherBoard.move.side[0] === side[0]) { otherBoard = otherBoard.prior; } @@ -318,9 +315,11 @@ function movePiece(priorBoard, side, from, to){ const moveFrom = (move.from === 'phantom') ? otherBoard.prior.phantom.from : move.from; if (move.side[0] === other[0] && moveFrom[1] != to[1]) { board.move.en_passant = true; - alongside = 'p'; board.move.took = 'p'; + /* move the opponent's pawn back one space */ boardPut(board, move.to, other, ' '); + boardPut(board, to, other, 'p'); + /* see if we replaced a piece from the other square */ replacedFrom = move.to; replaced = boardGet(board, replacedFrom, side); boardPut(board, replacedFrom, side, ' '); @@ -329,6 +328,16 @@ function movePiece(priorBoard, side, from, to){ } } + if (type === 'p' && to[1] === (isDark(side) ? '1' : '8')) { + board.move.promotion = 'q'; /* TODO: allow other choices */ + type = 'q'; + } + + if (alongside === 'p' && to[1] === (isDark(other) ? '1' : '8')) { + board.move.promotion = 'q'; /* TODO: allow other choices */ + alongside = 'q'; + } + if (from === 'phantom') { delete board.phantom; } else {