Skip to content

Instantly share code, notes, and snippets.

@46bit
Created May 18, 2017 23:19
Show Gist options
  • Select an option

  • Save 46bit/8a88e124bfbbc99817f0d219d23a6188 to your computer and use it in GitHub Desktop.

Select an option

Save 46bit/8a88e124bfbbc99817f0d219d23a6188 to your computer and use it in GitHub Desktop.
from enum import Enum, unique
@unique
class Direction(Enum):
north, east, south, west = range(1, 5)
def offset(self):
if self is Direction.north:
return [0, -1]
elif self is Direction.east:
return [1, 0]
elif self is Direction.south:
return [0, 1]
elif self is Direction.west:
return [-1, 0]
else:
raise ValueError("Unhandled direction.")
class Robot:
def __init__(self):
self.position = [0, 0]
def move(self, direction):
if direction not in Direction:
raise ValueError("Invalid direction '%s'." % direction)
direction_offset = direction.offset()
self.position[0] += direction_offset[0]
self.position[1] += direction_offset[1]
import os
import unittest
from robot import Robot, Direction
class DirectionTestCase(unittest.TestCase):
def test_offsets(self):
self.assertEqual(Direction.north.offset(), [0, -1])
self.assertEqual(Direction.east.offset(), [1, 0])
self.assertEqual(Direction.south.offset(), [0, 1])
self.assertEqual(Direction.west.offset(), [-1, 0])
class RobotTestCase(unittest.TestCase):
def test_start_position(self):
self.assertEqual(self.robot.position, [0, 0])
def test_move_basic(self):
for direction in Direction.__members__.values():
self.robot = Robot()
self.robot.move(direction)
self.assertEqual(self.robot.position, direction.offset())
def test_move_invalid(self):
with self.assertRaises(ValueError):
self.robot.move("abc")
def setUp(self):
self.robot = Robot()
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment