diff --git a/engine/src/board.ts b/engine/src/board.ts index 270aec7..8787117 100644 --- a/engine/src/board.ts +++ b/engine/src/board.ts @@ -69,8 +69,6 @@ export class BoardState { this.state.halfMoves++; } - this.updateCastlingRights(from); - this.state.board[toIndex] = this.state.board[fromIndex]; this.state.board[fromIndex] = 0; @@ -78,6 +76,9 @@ export class BoardState { this.state.fullMoves++; } this.state.isWhiteTurn = !this.state.isWhiteTurn; + + this.maybeMakeCastlingMove(from, to); + this.updateCastlingRights(from); } get(square: TSquare): TPiece | undefined { @@ -142,6 +143,35 @@ export class BoardState { return castlingRights.join(""); } + private maybeMakeCastlingMove(from: TSquare, to: TSquare) { + const fromIndex = this.toIndex(from); + const castlingRights = this.state.castlingRights; + + if ( + (from === "e1" && to === "g1" && castlingRights.K) || + (from === "e8" && to === "g8" && castlingRights.k) + ) { + const right = fromIndex + 1; + const rookIndex = fromIndex + 3; + if (!this.state.board[right]) { + this.state.board[right] = this.state.board[rookIndex]; + this.state.board[rookIndex] = 0; + } + } + + if ( + (from === "e1" && to === "c1" && castlingRights.Q) || + (from === "e8" && to === "c8" && castlingRights.q) + ) { + const left = fromIndex - 1; + const rookIndex = fromIndex - 4; + if (!this.state.board[left]) { + this.state.board[left] = this.state.board[rookIndex]; + this.state.board[rookIndex] = 0; + } + } + } + // Updates the castling rights. This function assumes that the move has // already been determined to be valid. private updateCastlingRights(from: TSquare) { diff --git a/engine/src/perft.test.ts b/engine/src/perft.test.ts index fbc939f..21da033 100644 --- a/engine/src/perft.test.ts +++ b/engine/src/perft.test.ts @@ -48,7 +48,7 @@ describe("perft", () => { }); it("Kiwipete", () => { - const expectedStates: number[] = []; + const expectedStates: number[] = [48]; const actualStates = runPerftTest( expectedStates.length, "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1"