[position] Calculate legal moves based on whether the king is in check

Use CheckingPieces to determine which and how many pieces check the king.

- If there are no checks, proceed with move generation as normal.
- If there is one checking piece, calculate push and capture masks and use those
   to generate legal moves.
- If there are more than one checking pieces, the only legal moves are king
  moves. Indicate this by setting the push and capture masks to EMPTY.
This commit is contained in:
Eryn Wells 2024-02-02 08:05:37 -08:00
parent 986758d011
commit 942c758e15

View file

@ -2,11 +2,11 @@
use super::{flags::Flags, piece_sets::PieceBitBoards, Pieces}; use super::{flags::Flags, piece_sets::PieceBitBoards, Pieces};
use crate::{ use crate::{
move_generator::{MoveSet, Moves}, check::{self, CheckingPieces},
move_generator::Moves,
position::DiagramFormatter, position::DiagramFormatter,
r#move::Castle, r#move::Castle,
sight::SightExt, sight::SightExt,
Move,
}; };
use chessfriend_bitboard::BitBoard; use chessfriend_bitboard::BitBoard;
use chessfriend_core::{Color, Piece, PlacedPiece, Shape, Square}; use chessfriend_core::{Color, Piece, PlacedPiece, Shape, Square};
@ -121,8 +121,22 @@ impl Position {
} }
pub fn moves(&self) -> &Moves { pub fn moves(&self) -> &Moves {
self.moves self.moves.get_or_init(|| {
.get_or_init(|| Moves::new(self, self.color_to_move, BitBoard::FULL, BitBoard::FULL)) let checking_pieces = self.checking_pieces();
match checking_pieces.count() {
// Normal, unrestricted move generation
0 => Moves::new(self, self.color_to_move, BitBoard::FULL, BitBoard::FULL),
1 => {
// Calculate push and capture masks for checking piece. Moves are restricted to those that intersect those masks.
let capture_mask = checking_pieces.capture_mask();
let push_mask =
checking_pieces.push_mask(self.king_bitboard(self.color_to_move));
Moves::new(self, self.color_to_move, capture_mask, push_mask)
}
// With more than one checking piece, the only legal moves are king moves.
_ => Moves::new(self, self.color_to_move, BitBoard::EMPTY, BitBoard::EMPTY),
}
})
} }
/// Return a BitBoard representing the set of squares containing a piece. /// Return a BitBoard representing the set of squares containing a piece.