Problem Statement
Without special handling, chess game logic cannot correctly enforce or recognize unique moves like castling and en passant. This leads to incorrect game states, illegal moves being allowed, and a poor player experience.
Jump into concepts and practice - no test required
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Player Move │──────▶│ Move Validator│──────▶│ Game State │
│ Input │ │ (includes │ │ (tracks board,│
│ │ │ special moves)│ │ move history) │
└───────────────┘ └───────────────┘ └───────────────┘
│ ▲
│ │
└───────────────────────┘This diagram shows the flow from player input through move validation including special moves, updating the game state with board and move history.
### Before: naive move validation without special moves class ChessGame: def is_valid_move(self, start, end): # Only basic move validation return self.is_valid_basic_move(start, end) ### After: enhanced validation including castling and en passant class ChessGame: def __init__(self): self.board = ... self.move_history = [] self.king_moved = {'white': False, 'black': False} self.rook_moved = {'white': {'a': False, 'h': False}, 'black': {'a': False, 'h': False}} def is_valid_move(self, start, end): if self.is_castling_move(start, end): return self.can_castle(start, end) if self.is_en_passant_move(start, end): return self.can_en_passant(start, end) return self.is_valid_basic_move(start, end) def can_castle(self, start, end): # Check king and rook unmoved, path clear, not in check pass def can_en_passant(self, start, end): # Check last move was opponent pawn double step adjacent pass def is_castling_move(self, start, end): # Detect castling move pattern pass def is_en_passant_move(self, start, end): # Detect en passant move pattern pass
def can_castle(king_moved, rook_moved, path_clear):
if king_moved or rook_moved:
return False
if not path_clear:
return False
return True
print(can_castle(True, False, True))def can_en_passant(pawn_pos, opponent_pawn_pos, last_move):
if last_move == 'two_squares_forward' and abs(pawn_pos[0] - opponent_pawn_pos[0]) == 1:
return True
return False
# Example call
print(can_en_passant((4,4), (5,4), 'two_squares_forward'))