diff --git a/src/main.rs b/src/main.rs index 47f69ed..5229f42 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,8 +32,19 @@ impl World { /// Struct to store robot position. struct Position { - x: u32, - y: u32, + x: i32, + y: i32, +} + +impl Position { + /// Check if position is in the map. + fn is_valid(self, w: World) -> Result<(), String> { + if (self.x, self.y) > (0, 0) && (self.x, self.y) < (w.x as i32, w.y as i32) { + Ok(()) + } else { + Err(String::from("Invalid position.")) + } + } } /// A Robot *aka droid* is represented here. @@ -257,6 +268,22 @@ mod tests { assert_eq!(w.map, vec!['↑', '.', '.', '.']); } + #[test] + fn test_move_robot() { + let mut r: Robot = Robot { + id: 0, + o: Orientation::N, + p: Position { x: 1, y: 1 }, + q: Queue::new(), + }; + r.move_forward(); + assert_eq!(0, r.p.y); + r.move_right(); + assert_eq!(2, r.p.x); + r.move_left(); + assert_eq!(1, r.p.x); + } + #[test] fn test_empty_position() { let mut w: World = World { @@ -267,4 +294,27 @@ mod tests { w.create(); assert!(w.empty_position(Position { x: 0, y: 0 })); } + + #[test] + fn test_valid_position() { + let p: Position = Position { x: 1, y: 1 }; + let w: World = World { + x: 5, + y: 5, + map: Vec::new(), + }; + assert!(p.is_valid(w).is_ok()); + } + + #[test] + #[should_panic] + fn test_invalid_position() { + let p: Position = Position { x: -1, y: 1 }; + let w: World = World { + x: 5, + y: 5, + map: Vec::new(), + }; + assert!(p.is_valid(w).is_ok()); + } }