Here we define the `ToyRobot` and `Table` class.
The ToyRobot
class is the robot the does the moving. This class contains the main methods left
, right
, move
, report
and a classmethod from_placement
which can be used to instantiate the robot without calling __init__
.
The robot does the moving based on the direction it is current in:
- To move the robot North, it updates it's
y
byy+1
and keepsx
as same. - To move the robot West, it updates it's
x
byx-1
and keepsy
as same. - To move the robot East, it updates it's
x
byx+1
and keepsy
as same. - To move the robot South, it updates it's
y
byy-1
and keepsx
as same.
The internal working of movement is taken care of by using the sin
and cos
math functions inspired from here.
#example use by passing tuple
assert (1,2) in Table(5,5)
assert (5,5) in Table(5,5)
assert (6,5) not in Table(5,5)
Some basic tests to make sure that the Robot
and Table
work together.
# instantiate robot on (2,2) facing `North`
r1 = ToyRobot(2,2, 0)
assert isinstance(r1.f, Direction)
assert r1.x == 2
assert r1.y == 2
assert r1.f.get_idx() == 0
# take one step forward in the current direction (North)
r1.move()
assert r1.x == 2
assert r1.y == 3
# change direction to right (East) and take one step forward
r1.right()
r1.move()
assert r1.x == 3
assert r1.y == 3
# create a new robot by using the `from_placement` method
r2 = ToyRobot.from_placement(1, 1, 0)
assert isinstance(r2, ToyRobot)
assert r2.f.get_idx()==0
assert r2.x == 1
assert r2.y == 1
# simple checks to make sure that robot is either inside or outside the table
assert ToyRobot.from_placement(1, 1, 0) in Table(5, 5)
assert ToyRobot.from_placement(2, 3, 0) in Table(5, 5)
assert ToyRobot.from_placement(5, 5, 0) in Table(5, 5)
assert ToyRobot.from_placement(5, 6, 0) is None
assert ToyRobot.from_placement(6, 5, 0) is None
from nbdev.export import *
notebook2script()