rover: add obstacle detection to Commander

This commit is contained in:
Bruno BELANYI 2019-11-16 03:19:50 +01:00
parent 556acf8095
commit ce0241b3f4
2 changed files with 20 additions and 1 deletions

View file

@ -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

View file

@ -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)