Skip to content

Implement Check Detection System #76

@walshb421

Description

@walshb421

Summary

Implement check detection to prevent illegal moves that leave the king in check. This is a prerequisite for checkmate/stalemate detection and is essential for a rules-compliant chess game.

Currently, players can:

  • Move their king into check
  • Ignore being in check
  • Move pinned pieces freely

Implementation Requirements

1. Add get_king_position(color) method to ChessBoard

  • Returns the (row, col) tuple of the specified color's king
  • Should iterate through the board to find the king piece

2. Add is_square_attacked(square, by_color) method to ChessBoard

  • Returns True if any piece of by_color can attack the given square
  • Must check all opponent pieces and their possible moves
  • Used for both check detection and castling validation

3. Add is_in_check(color) method to ChessBoard

  • Returns True if the king of the specified color is in check
  • Utilizes get_king_position() and is_square_attacked()

4. Add would_be_in_check(move, color) method to ChessBoard

  • Simulates the move on a copy of the board
  • Returns True if the move would leave the king in check
  • Must handle special cases: castling through check, en passant discovered check

5. Filter illegal moves in can_move_piece()

  • After generating possible moves, filter out any that would leave the king in check
  • Update validate_move() to use the new check detection

6. Update castling validation in castling_check()

  • King cannot castle out of check
  • King cannot castle through check (squares king passes over)
  • King cannot castle into check
  • Replace the existing TODO comment with actual implementation

Acceptance Criteria

  • King cannot move to a square that is attacked
  • Pieces pinned to the king cannot move (unless along the pin line)
  • When in check, only moves that escape check are allowed
  • Castling is blocked if king is in check, passes through check, or ends in check
  • All existing move generation tests still pass

Technical Notes

  • Consider creating a simulate_move() helper that returns a board copy with a move applied
  • Be careful with performance - check detection runs for every move validation
  • The generate_moves() methods in piece classes should remain unchanged; filtering happens at the board level

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions