From 4f3469b3e3fd61561cbd6982728e2e4c79c1441b Mon Sep 17 00:00:00 2001 From: Pavel Lutskov Date: Sun, 5 Dec 2021 15:42:07 +0100 Subject: [PATCH] Change Board state to HashMap --- rs/src/board.rs | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/rs/src/board.rs b/rs/src/board.rs index da6bd2a..bfdb25b 100644 --- a/rs/src/board.rs +++ b/rs/src/board.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + #[derive(Clone)] enum Color { Black, @@ -25,7 +27,7 @@ impl Color { } } -#[derive(Clone)] +#[derive(PartialEq, Eq, Hash, Clone)] pub struct Position { rank: Rank, file: File, @@ -56,7 +58,7 @@ impl Position { } } -#[derive(PartialEq, Clone, Copy)] +#[derive(PartialEq, Eq, Hash, Clone, Copy)] pub enum Rank { _1, _2, @@ -68,7 +70,7 @@ pub enum Rank { _8, } -#[derive(PartialEq, Clone, Copy)] +#[derive(PartialEq, Eq, Hash, Clone, Copy)] pub enum File { A, B, @@ -204,17 +206,22 @@ impl Piece { } pub struct Board { - state: [[Option; File::ALL_VALUES.len()]; Rank::ALL_VALUES.len()], + state: HashMap, } impl Board { - pub fn get_at(&self, position: &Position) -> &Option { - &self.state[position.rank.get_index() as usize] - [position.file.get_index() as usize] + pub fn get_at(&self, position: &Position) -> Option<&Piece> { + return self.state.get(position); } - fn set_at(&mut self, position: &Position, piece_or_empty: Option) { - self.state[position.rank.get_index() as usize] - [position.file.get_index() as usize] = piece_or_empty; + pub fn set_at( + &mut self, + position: Position, + piece_or_empty: Option, + ) { + match piece_or_empty { + Some(piece) => self.state.insert(position, piece), + None => self.state.remove(&position), + }; } pub fn new() -> Board { let mut board = Board { @@ -222,9 +229,12 @@ impl Board { }; for piece_type in &[PieceType::Pawn] { for (piece, position) in piece_type.initial_setup() { - board.set_at(&position, Some(piece)); + board.set_at(position, Some(piece)); } } board } + pub fn iter(&self) -> impl Iterator { + self.state.iter() + } }