Change Board state to HashMap

This commit is contained in:
2021-12-05 15:42:07 +01:00
parent 81626aefec
commit 4f3469b3e3

View File

@@ -1,3 +1,5 @@
use std::collections::HashMap;
#[derive(Clone)] #[derive(Clone)]
enum Color { enum Color {
Black, Black,
@@ -25,7 +27,7 @@ impl Color {
} }
} }
#[derive(Clone)] #[derive(PartialEq, Eq, Hash, Clone)]
pub struct Position { pub struct Position {
rank: Rank, rank: Rank,
file: File, file: File,
@@ -56,7 +58,7 @@ impl Position {
} }
} }
#[derive(PartialEq, Clone, Copy)] #[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub enum Rank { pub enum Rank {
_1, _1,
_2, _2,
@@ -68,7 +70,7 @@ pub enum Rank {
_8, _8,
} }
#[derive(PartialEq, Clone, Copy)] #[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub enum File { pub enum File {
A, A,
B, B,
@@ -204,17 +206,22 @@ impl Piece {
} }
pub struct Board { pub struct Board {
state: [[Option<Piece>; File::ALL_VALUES.len()]; Rank::ALL_VALUES.len()], state: HashMap<Position, Piece>,
} }
impl Board { impl Board {
pub fn get_at(&self, position: &Position) -> &Option<Piece> { pub fn get_at(&self, position: &Position) -> Option<&Piece> {
&self.state[position.rank.get_index() as usize] return self.state.get(position);
[position.file.get_index() as usize]
} }
fn set_at(&mut self, position: &Position, piece_or_empty: Option<Piece>) { pub fn set_at(
self.state[position.rank.get_index() as usize] &mut self,
[position.file.get_index() as usize] = piece_or_empty; position: Position,
piece_or_empty: Option<Piece>,
) {
match piece_or_empty {
Some(piece) => self.state.insert(position, piece),
None => self.state.remove(&position),
};
} }
pub fn new() -> Board { pub fn new() -> Board {
let mut board = Board { let mut board = Board {
@@ -222,9 +229,12 @@ impl Board {
}; };
for piece_type in &[PieceType::Pawn] { for piece_type in &[PieceType::Pawn] {
for (piece, position) in piece_type.initial_setup() { for (piece, position) in piece_type.initial_setup() {
board.set_at(&position, Some(piece)); board.set_at(position, Some(piece));
} }
} }
board board
} }
pub fn iter(&self) -> impl Iterator<Item = (&Position, &Piece)> {
self.state.iter()
}
} }