2015-11-16 17:36:54 +01:00
|
|
|
NORTH, EAST, SOUTH, WEST = range(4)
|
2015-11-08 09:31:58 +01:00
|
|
|
|
|
|
|
|
|
2015-11-16 17:36:54 +01:00
|
|
|
class Compass(object):
|
|
|
|
|
compass = [NORTH, EAST, SOUTH, WEST]
|
|
|
|
|
|
|
|
|
|
def __init__(self, bearing=NORTH):
|
|
|
|
|
self.bearing = bearing
|
|
|
|
|
|
|
|
|
|
def left(self):
|
|
|
|
|
self.bearing = self.compass[self.bearing - 1]
|
|
|
|
|
|
|
|
|
|
def right(self):
|
|
|
|
|
self.bearing = self.compass[(self.bearing + 1) % 4]
|
2015-11-08 09:31:58 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class Robot(object):
|
2015-11-16 17:36:54 +01:00
|
|
|
def __init__(self, bearing=NORTH, x=0, y=0):
|
|
|
|
|
self.compass = Compass(bearing)
|
|
|
|
|
self.x = x
|
|
|
|
|
self.y = y
|
2015-11-08 09:31:58 +01:00
|
|
|
|
|
|
|
|
def advance(self):
|
2015-11-16 17:36:54 +01:00
|
|
|
if self.bearing == NORTH:
|
|
|
|
|
self.y += 1
|
|
|
|
|
elif self.bearing == SOUTH:
|
|
|
|
|
self.y -= 1
|
|
|
|
|
elif self.bearing == EAST:
|
|
|
|
|
self.x += 1
|
|
|
|
|
elif self.bearing == WEST:
|
|
|
|
|
self.x -= 1
|
2015-11-08 09:31:58 +01:00
|
|
|
|
|
|
|
|
def turn_left(self):
|
2015-11-16 17:36:54 +01:00
|
|
|
self.compass.left()
|
2015-11-08 09:31:58 +01:00
|
|
|
|
|
|
|
|
def turn_right(self):
|
2015-11-16 17:36:54 +01:00
|
|
|
self.compass.right()
|
2015-11-08 09:31:58 +01:00
|
|
|
|
|
|
|
|
def simulate(self, commands):
|
|
|
|
|
instructions = {'A': self.advance,
|
|
|
|
|
'R': self.turn_right,
|
|
|
|
|
'L': self.turn_left}
|
|
|
|
|
for cmd in commands:
|
|
|
|
|
if cmd in instructions:
|
|
|
|
|
instructions[cmd]()
|
2015-11-16 17:36:54 +01:00
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def bearing(self):
|
|
|
|
|
return self.compass.bearing
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def coordinates(self):
|
|
|
|
|
return (self.x, self.y)
|