Skip to content

Commit 0de3d1c

Browse files
committed
Do not lose info about invalid castling rights
1 parent 1383e5f commit 0de3d1c

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

chess/__init__.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1889,17 +1889,27 @@ def set_fen(self, fen):
18891889
flag = flag.lower()
18901890
backrank = BB_RANK_1 if color == WHITE else BB_RANK_8
18911891
rooks = self.occupied_co[color] & self.rooks & backrank
1892+
king = self.occupied_co[color] & self.kings & backrank
18921893

18931894
if flag == "q":
18941895
# Select the leftmost rook.
1895-
self.castling_rights |= (rooks & -rooks)
1896+
mask = rooks & -rooks
1897+
1898+
if king and bit_scan(mask) < bit_scan(king):
1899+
self.castling_rights |= mask
1900+
else:
1901+
self.castling_rights |= BB_FILE_A & backrank
18961902
elif flag == "k":
18971903
# Select the rightmost rook.
18981904
mask = BB_VOID
18991905
while rooks:
1900-
mask = (rooks & -rooks)
1906+
mask = rooks & -rooks
19011907
rooks = rooks & (rooks - 1)
1902-
self.castling_rights |= mask
1908+
1909+
if king and bit_scan(king) < bit_scan(mask):
1910+
self.castling_rights |= mask
1911+
else:
1912+
self.castling_rights |= BB_FILE_H & backrank
19031913
else:
19041914
self.castling_rights |= BB_FILES[FILE_NAMES.index(flag)] & backrank
19051915

test.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,10 @@ def test_invalid_castling_rights(self):
333333
self.assertEqual(board.status(), chess.STATUS_BAD_CASTLING_RIGHTS)
334334
self.assertEqual(board.fen(), "4k2r/8/8/8/8/8/8/R1K5 w k - 0 1")
335335

336+
board = chess.Board("1r2k3/8/1p6/8/8/5P2/8/1R2KR2 w KQkq - 0 1", chess960=True)
337+
self.assertEqual(board.status(), chess.STATUS_BAD_CASTLING_RIGHTS)
338+
self.assertEqual(board.fen(), "1r2k3/8/1p6/8/8/5P2/8/1R2KR2 w KQq - 0 1")
339+
336340
def test_insufficient_material(self):
337341
# Starting position.
338342
board = chess.Board()

0 commit comments

Comments
 (0)