Skip to content

Commit 21a6da1

Browse files
author
miskibin
committed
feat: Refactor king movement logic to improve handling of forbidden squares during captures
1 parent e6338b4 commit 21a6da1

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

draughts/boards/standard.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -177,11 +177,8 @@ def _get_king_legal_moves_from(
177177
Args:
178178
square: The current square of the king
179179
is_capture_mandatory: Whether we're in a capture sequence
180-
forbidden_squares: Squares of previously captured pieces that cannot be crossed
180+
forbidden_squares: Mutable set of previously captured piece squares (modified in-place)
181181
"""
182-
if forbidden_squares is None:
183-
forbidden_squares = set()
184-
185182
moves = []
186183
pos = self._pos # Local reference for faster access
187184
turn_val = self.turn.value
@@ -191,7 +188,7 @@ def _get_king_legal_moves_from(
191188
dir_len = len(direction)
192189
for idx, target in enumerate(direction):
193190
# Check if path crosses a forbidden square (previously captured piece)
194-
if target in forbidden_squares:
191+
if forbidden_squares and target in forbidden_squares:
195192
break
196193

197194
target_val = pos[target]
@@ -203,17 +200,23 @@ def _get_king_legal_moves_from(
203200
i = idx + 1
204201
while i < dir_len and pos[direction[i]] == EMPTY:
205202
# Check landing square is not forbidden
206-
if direction[i] in forbidden_squares:
203+
if forbidden_squares and direction[i] in forbidden_squares:
207204
i += 1
208205
continue
209206

210207
move = Move(
211208
[square, direction[i]], [target], [target_val]
212209
)
213210
self.push(move, False)
214-
# Add the captured square to forbidden set for subsequent captures
215-
new_forbidden = forbidden_squares | {target}
216-
sub_moves = self._get_king_legal_moves_from(direction[i], True, new_forbidden)
211+
# Add captured square to forbidden set (backtracking pattern)
212+
if forbidden_squares is None:
213+
forbidden_squares = {target}
214+
sub_moves = self._get_king_legal_moves_from(direction[i], True, forbidden_squares)
215+
forbidden_squares = None
216+
else:
217+
forbidden_squares.add(target)
218+
sub_moves = self._get_king_legal_moves_from(direction[i], True, forbidden_squares)
219+
forbidden_squares.discard(target)
217220
self.pop(False)
218221

219222
if sub_moves:

0 commit comments

Comments
 (0)