Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Produce valid FEN strings for game struct #49

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/board.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ pub struct Board {
checkers: BitBoard,
hash: u64,
en_passant: Option<Square>,
en_passant_target: Option<Square>,
}

/// What is the status of this game?
Expand Down Expand Up @@ -71,6 +72,7 @@ impl Board {
checkers: EMPTY,
hash: 0,
en_passant: None,
en_passant_target: None,
}
}

Expand Down Expand Up @@ -807,6 +809,39 @@ impl Board {
self.en_passant
}

/// Give me the en_passant_target square, if it exists.
///
/// ```
/// use chess::{Board, ChessMove, Square};
///
/// let move1 = ChessMove::new(Square::D2,
/// Square::D4,
/// None);
///
/// let move2 = ChessMove::new(Square::H7,
/// Square::H5,
/// None);
///
/// let move3 = ChessMove::new(Square::D4,
/// Square::D5,
/// None);
///
/// let move4 = ChessMove::new(Square::E7,
/// Square::E5,
/// None);
///
/// let board = Board::default().make_move_new(move1)
/// .make_move_new(move2)
/// .make_move_new(move3)
/// .make_move_new(move4);
///
/// assert_eq!(board.en_passant_target(), Some(Square::E6));
/// ```
#[inline]
pub fn en_passant_target(self) -> Option<Square> {
self.en_passant_target
}

/// Set the en_passant square. Note: This must only be called when self.en_passant is already
/// None.
fn set_ep(&mut self, sq: Square) {
Expand All @@ -821,6 +856,10 @@ impl Board {
}
}

fn set_ep_target(&mut self, sq: Option<Square>) {
self.en_passant_target = sq;
}

/// Is a particular move legal? This function is very slow, but will work on unsanitized
/// input.
///
Expand Down Expand Up @@ -904,6 +943,9 @@ impl Board {
result.xor(captured, dest_bb, !self.side_to_move);
}

// Reset en_passant target
result.set_ep_target(None);

#[allow(deprecated)]
result.remove_their_castle_rights(CastleRights::square_to_castle_rights(
!self.side_to_move,
Expand Down Expand Up @@ -957,6 +999,7 @@ impl Board {
&& (dest_bb & get_pawn_dest_double_moves()) != EMPTY
{
result.set_ep(dest);
result.set_ep_target(Some(dest.ubackward(self.side_to_move)));
result.checkers ^= get_pawn_attacks(ksq, !result.side_to_move, dest_bb);
} else if Some(dest.ubackward(self.side_to_move)) == self.en_passant {
result.xor(
Expand Down Expand Up @@ -1041,6 +1084,11 @@ impl Board {
pub fn checkers(&self) -> &BitBoard {
&self.checkers
}

pub fn get_psuedo_fen(&self) -> String {
let board_builder: BoardBuilder = self.into();
board_builder.get_psuedo_fen()
}
}

impl fmt::Display for Board {
Expand Down
93 changes: 53 additions & 40 deletions src/board_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ pub struct BoardBuilder {
side_to_move: Color,
castle_rights: [CastleRights; 2],
en_passant: Option<File>,
en_passant_target: Option<Square>,
}

impl BoardBuilder {
Expand Down Expand Up @@ -81,6 +82,7 @@ impl BoardBuilder {
side_to_move: Color::White,
castle_rights: [CastleRights::NoRights, CastleRights::NoRights],
en_passant: None,
en_passant_target: None,
}
}

Expand All @@ -100,6 +102,7 @@ impl BoardBuilder {
/// Color::Black,
/// CastleRights::NoRights,
/// CastleRights::NoRights,
/// None,
/// None)
/// .try_into()?;
/// # Ok(())
Expand All @@ -110,12 +113,14 @@ impl BoardBuilder {
white_castle_rights: CastleRights,
black_castle_rights: CastleRights,
en_passant: Option<File>,
en_passant_target: Option<Square>,
) -> BoardBuilder {
let mut result = BoardBuilder {
pieces: [None; 64],
side_to_move: side_to_move,
castle_rights: [white_castle_rights, black_castle_rights],
en_passant: en_passant,
en_passant_target: en_passant_target,
};

for piece in pieces.into_iter() {
Expand Down Expand Up @@ -259,83 +264,90 @@ impl BoardBuilder {
self.en_passant = file;
self
}
}

impl Index<Square> for BoardBuilder {
type Output = Option<(Piece, Color)>;

fn index<'a>(&'a self, index: Square) -> &'a Self::Output {
&self.pieces[index.to_index()]
}
}

impl IndexMut<Square> for BoardBuilder {
fn index_mut<'a>(&'a mut self, index: Square) -> &'a mut Self::Output {
&mut self.pieces[index.to_index()]
}
}

impl fmt::Display for BoardBuilder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// A FEN representaion with the last two fileds, the half move clock and the full move
/// counter, omitted.
pub(crate) fn get_psuedo_fen(&self) -> String {
let mut psuedo_fen = String::new();
let mut count = 0;
for rank in ALL_RANKS.iter().rev() {
for file in ALL_FILES.iter() {
let square = Square::make_square(*rank, *file).to_index();

if self.pieces[square].is_some() && count != 0 {
write!(f, "{}", count)?;
psuedo_fen.push_str(count.to_string().as_str());
count = 0;
}

if let Some((piece, color)) = self.pieces[square] {
write!(f, "{}", piece.to_string(color))?;
psuedo_fen.push_str(piece.to_string(color).as_str());
} else {
count += 1;
}
}

if count != 0 {
write!(f, "{}", count)?;
psuedo_fen.push_str(count.to_string().as_str());
}

if *rank != Rank::First {
write!(f, "/")?;
psuedo_fen.push_str("/");
}
count = 0;
}

write!(f, " ")?;
psuedo_fen.push_str(" ");

if self.side_to_move == Color::White {
write!(f, "w ")?;
psuedo_fen.push_str("w ");
} else {
write!(f, "b ")?;
psuedo_fen.push_str("b ");
}

write!(
f,
"{}",
self.castle_rights[Color::White.to_index()].to_string(Color::White)
)?;
write!(
f,
"{}",
self.castle_rights[Color::Black.to_index()].to_string(Color::Black)
)?;
psuedo_fen.push_str(
self.castle_rights[Color::White.to_index()]
.to_string(Color::White)
.as_str(),
);
psuedo_fen.push_str(
self.castle_rights[Color::Black.to_index()]
.to_string(Color::Black)
.as_str(),
);
if self.castle_rights[0] == CastleRights::NoRights
&& self.castle_rights[1] == CastleRights::NoRights
{
write!(f, "-")?;
psuedo_fen.push_str("-");
}

write!(f, " ")?;
if let Some(sq) = self.get_en_passant() {
write!(f, "{}", sq)?;
psuedo_fen.push_str(" ");
if let Some(sq) = self.en_passant_target {
psuedo_fen.push_str(sq.to_string().as_str());
} else {
write!(f, "-")?;
psuedo_fen.push_str("-");
}

write!(f, " 0 1")
psuedo_fen
}
}

impl Index<Square> for BoardBuilder {
type Output = Option<(Piece, Color)>;

fn index<'a>(&'a self, index: Square) -> &'a Self::Output {
&self.pieces[index.to_index()]
}
}

impl IndexMut<Square> for BoardBuilder {
fn index_mut<'a>(&'a mut self, index: Square) -> &'a mut Self::Output {
&mut self.pieces[index.to_index()]
}
}

impl fmt::Display for BoardBuilder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} 0 1", self.get_psuedo_fen())
}
}

Expand Down Expand Up @@ -496,6 +508,7 @@ impl From<&Board> for BoardBuilder {
board.castle_rights(Color::White),
board.castle_rights(Color::Black),
board.en_passant().map(|sq| sq.get_file()),
board.en_passant_target(),
)
}
}
Expand Down
Loading