From bfbb9ef404cefa3c5e0b20fb9e94336050e1e743 Mon Sep 17 00:00:00 2001 From: Sage Vaillancourt Date: Wed, 30 Dec 2020 22:50:07 -0500 Subject: [PATCH] Added castling --- src/index.js | 42 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/src/index.js b/src/index.js index 25cc578..fc9a91b 100644 --- a/src/index.js +++ b/src/index.js @@ -285,18 +285,38 @@ class Board extends React.Component { [[1, 1], [1, -1], [-1, 1], [-1, -1], [0, 1], [0, -1], [1, 0], [-1, 0]] .forEach(delta => tryAddMove(x + delta[0], y + delta[1])); if (piece.moves === 0) { - const [x, y] = this.getXandY(this.findIndex(piece)); + const kingIndex = this.findIndex(piece); + const [x, y] = this.getXandY(kingIndex); + let leftRook = this.pieceAt(0, y); if(isRook(leftRook) && leftRook.moves === 0) { - // Check if between space puts king in check // Check if spaces between rook and king are empty - // add move(x: x - 2, y, castle: [x, y]) + if(this.pieceAt(1, y) == null && + this.pieceAt(2, y) == null && + this.pieceAt(3, y) == null) { + // Check if between space puts king in check + let board = this.clone(); + board.state.squares[board.getIndex(x - 1, y)] = piece; + board.state.squares[kingIndex] = null; + if(board.inCheck(piece) == null) { + moves.push({x: x - 2, y, castle: [x - 1, y]}); + } + } } + let rightRook = this.pieceAt(7, y); if(isRook(rightRook) && rightRook.moves === 0) { - // Check if between space puts king in check // Check if spaces between rook and king are empty - // add move(x: x + 2, y, castle: [x, y]) + if(this.pieceAt(5, y) == null && + this.pieceAt(6, y) == null) { + // Check if between space puts king in check + let board = this.clone(); + board.state.squares[board.getIndex(x + 1, y)] = piece; + board.state.squares[kingIndex] = null; + if(board.inCheck(piece) == null) { + moves.push({x: x + 2, y, castle: [x + 1, y]}); + } + } } } } @@ -411,6 +431,18 @@ class Board extends React.Component { if (move.passant) { squares[this.getIndex(move.passant.x, move.passant.y)] = null; } + if (move.castle) { + // .castle holds the position where the rook should end up + // King moved left + const rookX = move.castle[0] > move.x ? 0 : 7; + console.log("Replace "); + console.log(move.castle); + console.log("With "); + console.log([rookX, move.castle[1]]); + squares[this.getIndex(move.castle[0], move.castle[1])] = + squares[this.getIndex(rookX, move.castle[1])]; + squares[this.getIndex(rookX, move.castle[1])] = null; + } // Remove existing passantable states squares.forEach(square => { if (square) {