robot_simulator.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
NORTH, EAST, SOUTH, WEST = (0, 1), (1, 0), (0, -1), (-1, 0)


class Robot:
    def __init__(self, bearing=NORTH, x=0, y=0):
        self._x, self._y = x, y
        self._dx, self._dy = bearing

    @property
    def coordinates(self):
        return self._x, self._y

    @property
    def bearing(self):
        return self._dx, self._dy

    def advance(self):
        """Move forward on current bearing"""
        self._x += self._dx
        self._y += self._dy

    def turn_left(self):
        """Turn left 90 degrees"""
        self._dx, self._dy = -self._dy, self._dx

    def turn_right(self):
        """Turn right 90 degrees"""
        self._dx, self._dy = self._dy, -self._dx

    def simulate(self, sequence):
        """Run a sequence of commands"""
        commands = {
            'L': self.turn_left,
            'R': self.turn_right,
            'A': self.advance,
        }
        for command in sequence:
            commands[command]()

Comments


You're not logged in right now. Please login via GitHub to comment