diff --git a/src/game.rs b/src/game.rs index 48e250c..70249f2 100644 --- a/src/game.rs +++ b/src/game.rs @@ -167,35 +167,40 @@ impl Board { Err(GameError::NullMove) } else { match self.at(from.clone()) { - Some(from_val) => { - // The current epoch is the last epoch + 1 - let epoch = self.current_epoch(); - - // Local moves vec we can return - let mut moves = vec![]; + Some(from_piece) => { + // Check if this is a valid move for this piece + if self.possible_moves(from).contains(&to) { + // The current epoch is the last epoch + 1 + let epoch = self.current_epoch(); + + // Local moves vec we can return + let mut moves = vec![]; + + // If the position we are moving to is occupied, capture the removal in the ledger + if self.inner[to.y][to.x].is_some() { + moves.push(Move { + epoch, + from: to.clone(), + to: None, + }); + } - // If the position we are moving to is occupied, capture the removal in the ledger - if self.inner[to.y][to.x].is_some() { + // Capture the intened move in the moves ledger moves.push(Move { epoch, - from: to.clone(), - to: None, + from: from.clone(), + to: Some(to.clone()), }); - } - // Capture the intened move in the moves ledger - moves.push(Move { - epoch, - from: from.clone(), - to: Some(to.clone()), - }); - - self.inner[to.y][to.x] = Some(*from_val); - self.inner[from.y][from.x] = None; + self.inner[to.y][to.x] = Some(*from_piece); + self.inner[from.y][from.x] = None; - self.moves.extend(moves.clone()); + self.moves.extend(moves.clone()); - Ok(moves) + Ok(moves) + } else { + Err(GameError::InvalidIndex) + } } None => Err(GameError::NullMove), } @@ -212,6 +217,7 @@ impl Board { } /// Returns the possible moves the piece at this tile can make. + /// !!TODO: exclude pieces on your own side!! pub(crate) fn possible_moves(&self, BoardIndex { x, y }: BoardIndex) -> HashSet { let f = |(a, b): (Option, Option)| { if let (Some(x), Some(y)) = (a, b) {