[board] Implement placing a piece in a mutable position

This commit is contained in:
Eryn Wells 2023-12-23 09:31:41 -07:00
parent 153e21b693
commit 366f15ca12
2 changed files with 72 additions and 3 deletions

View file

@ -19,11 +19,11 @@ impl BitBoard {
self.0 == 0
}
fn has_piece_at(&self, sq: &Square) -> bool {
pub fn has_piece_at(&self, sq: &Square) -> bool {
(self.0 & (1 << sq.index)) > 0
}
fn place_piece_at(&mut self, sq: &Square) {
pub fn place_piece_at(&mut self, sq: &Square) {
self.0 |= 1 << sq.index
}

View file

@ -1,6 +1,8 @@
// Eryn Wells <eryn@erynwells.me>
use crate::bitboard::BitBoard;
use crate::piece::{Color, Piece, PiecePlacementError, PieceShape};
use crate::square::Square;
use std::fmt;
mod color {
@ -80,11 +82,78 @@ impl Position {
}
}
fn piece_at_square(&self, sq: &str) {}
fn place_piece(&mut self, piece: &Piece, square: &Square) -> Result<(), PiecePlacementError> {
let mut bitboard = self.bitboard_for_piece_mut(piece);
if bitboard.has_piece_at(&square) {
return Err(PiecePlacementError::PieceExistsOnSquare);
}
bitboard.place_piece_at(&square);
Ok(())
}
fn bitboard_for_piece(&self, piece: &Piece) -> &BitBoard {
let color_index: usize = match piece.color {
Color::White => 0,
Color::Black => 1,
};
let piece_index: usize = match piece.piece {
PieceShape::Pawn => 0,
PieceShape::Knight => 1,
PieceShape::Bishop => 2,
PieceShape::Rook => 3,
PieceShape::Queen => 4,
PieceShape::King => 5,
};
&self.pieces_per_type[color_index][piece_index]
}
fn bitboard_for_piece_mut(&mut self, piece: &Piece) -> &mut BitBoard {
let color_index: usize = match piece.color {
Color::White => 0,
Color::Black => 1,
};
let piece_index: usize = match piece.piece {
PieceShape::Pawn => 0,
PieceShape::Knight => 1,
PieceShape::Bishop => 2,
PieceShape::Rook => 3,
PieceShape::Queen => 4,
PieceShape::King => 5,
};
&mut self.pieces_per_type[color_index][piece_index]
}
}
impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "abcdefg")
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn place_piece_at() {
let mut position = Position::empty();
let piece = Piece::new(Color::White, PieceShape::Queen);
let square = Square::from_algebraic_string("e4").expect("Unable to get e4 square");
position
.place_piece(&piece, &square)
.expect("Unable to place white queen on e4");
position
.place_piece(&piece, &square)
.expect_err("Placed white queen on e4 a second time?!");
println!("{:?}", position);
}
}