Skip to content

Commit abdd0b7

Browse files
committed
check king attack early on
1 parent 4ceb2bf commit abdd0b7

1 file changed

Lines changed: 25 additions & 7 deletions

File tree

check-buddy/src/board.rs

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,19 @@ impl BoardMap {
430430
}
431431
vec
432432
}
433+
/// Find the king of the given color
434+
pub fn find_king(&self, piece_color: PieceColor) -> Option<Position> {
435+
for (y, row) in self.squares.iter().enumerate() {
436+
for (x, p) in row.iter().enumerate() {
437+
if let Some(PieceType::King) = p.get_type() {
438+
if p.get_color() == piece_color {
439+
return Some([y, x]);
440+
}
441+
}
442+
}
443+
}
444+
None
445+
}
433446
pub fn get_piece_mut(&mut self, pos: Position) -> &mut Piece {
434447
self.squares[pos[0]][pos[1]].borrow_mut()
435448
}
@@ -570,13 +583,18 @@ impl BoardMap {
570583
..Default::default()
571584
};
572585
temp_board.make_move(position_move);
573-
let next_moves = temp_board.gen_all_opponent_positions();
574-
if !next_moves.iter().any(|m| {
575-
let next_piece = temp_board.squares[m[0]][m[1]];
576-
next_piece.is_piece()
577-
&& next_piece.get_color() == temp_board.active_color
578-
&& Some(PieceType::King) == next_piece.get_type()
579-
}) {
586+
587+
let king_pos = temp_board.find_king(temp_board.active_color);
588+
let opponent_color = if temp_board.active_color == PieceColor::White {
589+
PieceColor::Black
590+
} else {
591+
PieceColor::White
592+
};
593+
let in_check = king_pos
594+
.map(|pos| temp_board.is_square_attacked_by(pos, opponent_color))
595+
.unwrap_or(false);
596+
597+
if !in_check {
580598
legal_positions.push(to);
581599
}
582600

0 commit comments

Comments
 (0)