Skip to content

Commit

Permalink
Adds support for castling.
Browse files Browse the repository at this point in the history
This also allows us to pass the Kiwipete test at depth 2.
  • Loading branch information
aryann committed Oct 7, 2024
1 parent 266b3bf commit 69569fb
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
34 changes: 32 additions & 2 deletions engine/src/board.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,16 @@ export class BoardState {
this.state.halfMoves++;
}

this.updateCastlingRights(from);

this.state.board[toIndex] = this.state.board[fromIndex];
this.state.board[fromIndex] = 0;

if (!this.state.isWhiteTurn) {
this.state.fullMoves++;
}
this.state.isWhiteTurn = !this.state.isWhiteTurn;

this.maybeMakeCastlingMove(from, to);
this.updateCastlingRights(from);
}

get(square: TSquare): TPiece | undefined {
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion engine/src/perft.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down

0 comments on commit 69569fb

Please sign in to comment.