chesskit-app / chesskit-swift

♟️ Swift package for implementing chess logic.
MIT License
7 stars 6 forks source link

Fixed a bug where the king could castle through pieces. #28

Closed TigranSaakyan closed 3 weeks ago

TigranSaakyan commented 1 month ago

Added a check to make sure the path between the king and the rook is clear.

pdil commented 1 month ago

Thanks! Do you have an example position where this is possible? Is it when there is a piece of the opposite color in the path? That's the only scenario I can think of. It might be helpful to some tests for this case as well.

TigranSaakyan commented 1 month ago

This occurs for all types of pieces, including those of the same color. For example, here is an early stage position, r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3 (also shown on the screenshot), where the king can castle 0-0, even though there is a bishop in the way.

For your reference, if we try to display Board.legalMoves(forPieceAt: Square("e1")), it will output [ChessKit.Square.g1, ChessKit.Square.e2], which is incorrect.

BugDemo-1 1 BugDemo-1 2

Another example is for rnbqkbnr/1p1p1pp1/p1p4p/4p3/4P3/3P1Q2/PPPB1PPP/RN2KBNR w KQkq - 0 5. Similarly, the king can mistakenly castle queen side. If we run Board.legalMoves(forPieceAt: Square("e1")) for king in this position, we get [ChessKit.Square.c1, ChessKit.Square.d1, ChessKit.Square.e2].

BugDemo-2 1 BugDemo-2 2