Here we define the `ToyRobot` and `Table` class.

ToyRobot

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 sense of direction inside the ToyRobot comes from the Direction class itself. If we want the robot to move left, we simply update it's facing direction or self.f by calling self.f.left().

Because self.f is an instance of Direction, the actual turning of left and right is already taken care of.

The robot does the moving based on the direction it is current in:

  • To move the robot North, it updates it's y by y+1 and keeps x as same.
  • To move the robot West, it updates it's x by x-1 and keeps y as same.
  • To move the robot East, it updates it's x by x+1 and keeps y as same.
  • To move the robot South, it updates it's y by y-1 and keeps x as same.

The internal working of movement is taken care of by using the sin and cos math functions inspired from here.

class ToyRobot[source]

ToyRobot(x, y, idx=None, th=5, tw=5, verbose=False)

The actual ToyRobot class the does the moving.

Table

A basic Table class that checks if the robot or a tuple of (x, y) is inside the Table. This is done by creating a __contains__ method.

class Table[source]

Table(h=5, w=5)

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

Tests

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()
Converted 01_direction.ipynb.
Converted 02_robot.ipynb.
Converted 03_main.ipynb.
Converted 04_tests.ipynb.
Converted index.ipynb.