Skip to content

Commit

Permalink
Elaborate: add forward/backward movement
Browse files Browse the repository at this point in the history
  • Loading branch information
fr2d9y2 authored and fr2d9y2 committed Apr 6, 2017
1 parent 4712b10 commit f13e4f3
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 5 deletions.
24 changes: 19 additions & 5 deletions mars-rover/src/rover.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
class Rover:

global commands
global deltas

def __init__(self, x, y, orientation):
self.x = x
Expand All @@ -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 ]
}
56 changes: 56 additions & 0 deletions mars-rover/test/test_rover.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)

0 comments on commit f13e4f3

Please sign in to comment.