From ce0241b3f44f65a6207cac9eef632de809b420a5 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 16 Nov 2019 03:19:50 +0100 Subject: [PATCH] rover: add obstacle detection to Commander --- rover/rover.py | 11 +++++++++++ rover/test_rover.py | 10 +++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/rover/rover.py b/rover/rover.py index babb4ea..2cf29e9 100644 --- a/rover/rover.py +++ b/rover/rover.py @@ -1,4 +1,6 @@ import enum +from copy import deepcopy +from typing import List from pydantic import BaseModel @@ -15,6 +17,10 @@ class Direction(enum.Enum): WEST = "W" +class ObstacleError(RuntimeError): + pass + + DIRECTIONS = [Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST] @@ -60,9 +66,11 @@ class Rover(BaseModel): class Commander(BaseModel): rover: Rover = Rover() + obstacles: List[Vector] = [] def parse_execute(self, commands: str): for command in commands: + save: Vector = deepcopy(self.rover.pos) if command == "F": self.rover.forward() elif command == "B": @@ -71,3 +79,6 @@ class Commander(BaseModel): self.rover.turn_left() elif command == "R": self.rover.turn_right() + if self.rover.pos in self.obstacles: + self.rover.pos = save + raise ObstacleError diff --git a/rover/test_rover.py b/rover/test_rover.py index 90d44b1..99e886d 100644 --- a/rover/test_rover.py +++ b/rover/test_rover.py @@ -1,4 +1,5 @@ -from rover import Commander, Direction, Rover, Vector +import pytest +from rover import Commander, Direction, ObstacleError, Rover, Vector def test_rover_constructor(): @@ -217,3 +218,10 @@ def test_commander_complex_command(): com = Commander() com.parse_execute("FRFRFLB") assert com.rover == Rover(dir=Direction.EAST) + + +def test_commander_command_with_obstacles(): + com = Commander(obstacles=[Vector(x=1, y=0), Vector(x=1, y=2)]) + with pytest.raises(ObstacleError): + com.parse_execute("FFRF") + assert com.rover == Rover(pos=Vector(x=0, y=2), dir=Direction.EAST)