Skip to content

Commit

Permalink
Make nodes' move methods return whether successful
Browse files Browse the repository at this point in the history
  • Loading branch information
numirias committed Feb 5, 2019
1 parent 4f1b917 commit a42fab8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
16 changes: 9 additions & 7 deletions plasma/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,38 +591,40 @@ def _save_restore_state(self):
self.fixed, flip)

def move(self, direction):
"""Move this node in `direction`. Return whether node was moved."""
if self.is_root:
return
return False
if direction.orient is self.parent.orient:
old_idx = self.index
new_idx = old_idx + direction.offset
if 0 <= new_idx < len(self.parent):
p = self.parent
p[old_idx], p[new_idx] = p[new_idx], p[old_idx]
return
return True
new_sibling = self.parent.parent
else:
new_sibling = self.parent
try:
new_parent = new_sibling.parent
idx = new_sibling.index
except AttributeError:
return
return False
self.reset_size()
self.parent.remove_child(self)
new_parent.add_child(self, idx + (1 if direction.offset == 1 else 0))
return True

def move_up(self):
self.move(UP)
return self.move(UP)

def move_down(self):
self.move(DOWN)
return self.move(DOWN)

def move_right(self):
self.move(RIGHT)
return self.move(RIGHT)

def move_left(self):
self.move(LEFT)
return self.move(LEFT)

def _move_and_integrate(self, direction):
old_parent = self.parent
Expand Down
25 changes: 16 additions & 9 deletions tests/test_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,27 +177,34 @@ def test_advanced_move(self, grid):

def test_advanced_move2(self, root, grid):
a, b, c, d, e = grid
c.move_down()
res = c.move_down()
assert b.parent.tree == [b, [d, e], c]
e.move_down()
assert res == True
res = e.move_down()
assert b.parent.tree == [b, d, e, c]
e.move_left()
assert res == True
res = e.move_left()
assert root.tree == [a, e, [b, d, c]]
d.move_right()
assert res == True
res = d.move_right()
assert root.tree == [a, e, [b, c], d]
a.move_left()
assert res == True
res = a.move_left()
assert root.tree == [a, e, [b, c], d]
d.move_right()
assert res == False
res = d.move_right()
assert root.tree == [a, e, [b, c], d]
assert res == False

def test_move_blocked(self, root, grid):
a, b, c, d, e = grid
orig_tree = root.tree.copy()
a.move_up()
res = a.move_up()
assert root.tree == orig_tree
b.move_up()
assert res is False
res = b.move_up()
assert root.tree == orig_tree
b.move_right()
assert res is False

def test_move_root(self, root):
a = Node('a')
Expand Down

0 comments on commit a42fab8

Please sign in to comment.