From f13e4f300e4eda0223843b98d1ae5e67c762c244 Mon Sep 17 00:00:00 2001 From: fr2d9y2 Date: Thu, 6 Apr 2017 14:05:55 -0700 Subject: [PATCH] Elaborate: add forward/backward movement --- mars-rover/src/rover.py | 24 +++++++++++---- mars-rover/test/test_rover.py | 56 +++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/mars-rover/src/rover.py b/mars-rover/src/rover.py index 34ba97f..80f3558 100644 --- a/mars-rover/src/rover.py +++ b/mars-rover/src/rover.py @@ -1,6 +1,7 @@ class Rover: global commands + global deltas def __init__(self, x, y, orientation): self.x = x @@ -10,17 +11,30 @@ def __init__(self, x, y, orientation): def move(self, commands): self.moveBy(commands[0]) + # use command pattern and lookup to avoid switch statements :) def moveBy(self, commandKey): command = commands[commandKey] - command(self) + delta = deltas[self.orientation] + command(self, delta) - def move_forward(self): - self.y += 1 + def move_forward(self, delta): + self.x += delta[0] + self.y += delta[1] - def move_backward(self): - self.y -= 1 + def move_backward(self, delta): + self.x -= delta[0] + self.y -= delta[1] + # commands to dispatch for each move key commands = { 'f': move_forward, 'b': move_backward } + + # x,y deltas to move forward for each orientation + deltas = { + 'N': [ +0, +1 ], + 'S': [ +0, -1 ], + 'E': [ +1, +0 ], + 'W': [ -1, +0 ] + } diff --git a/mars-rover/test/test_rover.py b/mars-rover/test/test_rover.py index 4e3e9fb..be534b6 100644 --- a/mars-rover/test/test_rover.py +++ b/mars-rover/test/test_rover.py @@ -16,6 +16,12 @@ def test_initial_y(self): def test_initial_orientation(self): assert_equal('N', r.orientation) +class TestMovesOrientationNorth: + + def setup(self): + global r + r = rover.Rover(10, 21, 'N') + def test_move_f(self): r.move(list("f")) assert_equal(22, r.y) @@ -25,3 +31,53 @@ def test_move_b(self): r.move(list("b")) assert_equal(10, r.x) assert_equal(20, r.y) + +class TestMovesOrientationSouth: + + def setup(self): + # tried using self.r, but it gets too wordy using self.r everywhere + global r + r = rover.Rover(10, 21, 'S') + + def test_move_forward(self): + r.move(list("f")) + assert_equal(10, r.x) + assert_equal(20, r.y) + + def test_move_backward(self): + r.move(list("b")) + assert_equal(10, r.x) + assert_equal(22, r.y) + +# would love use use test generators! +class TestMovesOrientationEast: + + def setup(self): + global r + r = rover.Rover(10, 21, 'E') + + def test_move_forward(self): + r.move(list('f')) + assert_equal(11, r.x) + assert_equal(21, r.y) + + def test_move_backward(self): + r.move(list("b")) + assert_equal(9, r.x) + assert_equal(21, r.y) + +class TestMovesOrientationWest: + + def setup(self): + global r + r = rover.Rover(10, 21, 'W') + + def test_move_forward(self): + r.move(list("f")) + assert_equals(9, r.x) + assert_equals(21, r.y) + + def test_move_backward(self): + r.move(list("b")) + assert_equal(11, r.x) + assert_equal(21, r.y)