rover: add obstacle detection to Commander
This commit is contained in:
parent
556acf8095
commit
ce0241b3f4
|
@ -1,4 +1,6 @@
|
||||||
import enum
|
import enum
|
||||||
|
from copy import deepcopy
|
||||||
|
from typing import List
|
||||||
|
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
@ -15,6 +17,10 @@ class Direction(enum.Enum):
|
||||||
WEST = "W"
|
WEST = "W"
|
||||||
|
|
||||||
|
|
||||||
|
class ObstacleError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
DIRECTIONS = [Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST]
|
DIRECTIONS = [Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST]
|
||||||
|
|
||||||
|
|
||||||
|
@ -60,9 +66,11 @@ class Rover(BaseModel):
|
||||||
|
|
||||||
class Commander(BaseModel):
|
class Commander(BaseModel):
|
||||||
rover: Rover = Rover()
|
rover: Rover = Rover()
|
||||||
|
obstacles: List[Vector] = []
|
||||||
|
|
||||||
def parse_execute(self, commands: str):
|
def parse_execute(self, commands: str):
|
||||||
for command in commands:
|
for command in commands:
|
||||||
|
save: Vector = deepcopy(self.rover.pos)
|
||||||
if command == "F":
|
if command == "F":
|
||||||
self.rover.forward()
|
self.rover.forward()
|
||||||
elif command == "B":
|
elif command == "B":
|
||||||
|
@ -71,3 +79,6 @@ class Commander(BaseModel):
|
||||||
self.rover.turn_left()
|
self.rover.turn_left()
|
||||||
elif command == "R":
|
elif command == "R":
|
||||||
self.rover.turn_right()
|
self.rover.turn_right()
|
||||||
|
if self.rover.pos in self.obstacles:
|
||||||
|
self.rover.pos = save
|
||||||
|
raise ObstacleError
|
||||||
|
|
|
@ -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():
|
def test_rover_constructor():
|
||||||
|
@ -217,3 +218,10 @@ def test_commander_complex_command():
|
||||||
com = Commander()
|
com = Commander()
|
||||||
com.parse_execute("FRFRFLB")
|
com.parse_execute("FRFRFLB")
|
||||||
assert com.rover == Rover(dir=Direction.EAST)
|
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)
|
||||||
|
|
Loading…
Reference in a new issue