From 4ae73410bda3098763fa39b0783eef4fbf180539 Mon Sep 17 00:00:00 2001 From: Pavel Lutskov Date: Tue, 14 Dec 2021 21:12:59 +0100 Subject: [PATCH] Implement make_move function on engine --- rs/src/board.rs | 30 ++++++++++++++++++++++++------ rs/src/ui.rs | 16 ++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/rs/src/board.rs b/rs/src/board.rs index cd262d6..7c82b1e 100644 --- a/rs/src/board.rs +++ b/rs/src/board.rs @@ -205,19 +205,25 @@ pub struct Board { } impl Board { - pub fn get_at(&self, position: &Position) -> Option<&Piece> { + fn get_at(&self, position: &Position) -> Option<&Piece> { self.state.get(position) } - pub fn set_at( - &mut self, - position: Position, - piece_or_empty: Option, - ) { + 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), }; } + fn move_from_to( + &mut self, + source: &Position, + target: Position, + ) -> Result<(), ()> { + let (_, piece) = self.state.remove_entry(source).ok_or(())?; + self.set_at(target, Some(piece)); + Ok(()) + } + pub fn new() -> Board { Board { state: Default::default(), @@ -255,4 +261,16 @@ impl Board { }); Some(valid_moves.chain(valid_captures).collect()) } + pub fn make_move( + &mut self, + source: &Position, + target: Position, + ) -> Result<(), ()> { + if !self.get_legal_moves(source).ok_or(())?.contains(&target) { + Err(()) + } else { + // We checked that there is a piece at source in get_legal_moves + self.move_from_to(source, target) + } + } } diff --git a/rs/src/ui.rs b/rs/src/ui.rs index 187700a..2be95de 100644 --- a/rs/src/ui.rs +++ b/rs/src/ui.rs @@ -120,6 +120,21 @@ impl Ui { } } } + fn make_move(&mut self, args: &[&str]) -> Result { + if args.len() != 2 { + return Err("make_move takes 2 args".to_owned()); + }; + let source = board::Position::parse(args[0]) + .map_err(|_| format!("Error parsing source {}", args[0]))?; + let target = board::Position::parse(args[1]) + .map_err(|_| format!("Error parsing target {}", args[1]))?; + match self.board.make_move(&source, target) { + Err(()) => { + Err(format!("Move not possible {}-{}", args[0], args[1])) + } + Ok(()) => Ok(self.board.to_string()), + } + } fn handle_command(&mut self, s: &str) -> Result { let mut cmd = s.split(','); // There will be at least an empty string => otherwise panic @@ -128,6 +143,7 @@ impl Ui { match cmd_type { "get_state" => self.get_state(&args), "get_moves" => self.get_moves(&args), + "make_move" => self.make_move(&args), "" => Err("No command given".to_owned()), _ => Err("Invalid command".to_owned()), }