Grid: Squirrel Magic
This problem has two parts, and you can get full credit for each part regardless of what you did on the other part. We have a Grid representing Stanford campus and every square is either a squirrel 's', a tree 't', an acorn 'a', or empty None. The function squirrel_magic(grid, x, y, n) will be called with an in-bounds x, y, to attempt a squirrel "move" to make an acorn disappear. (a.) Write code for the move with these steps:
1. There must be a squirrel at x, y for the move to proceed.
2. If there is an acorn in the square immediately below the squirrel, then the acorn disappears and the move is over.
3. Otherwise, if there is an acorn in the row immediately above the squirrel and exactly n squares to the left of the squirrel, then the acorn disappears and the move is over. The parameter n will be an int value 1 or greater.
In all cases, the function should return the grid (changed or not) when done.
def squirrel_magic(grid, x, y, n):
(b.) Write one Doctest for a call to squirrel_magic() where an acorn disappears. As a reminder of the syntax, here is a working Doctest from the movie scroll_left() lecture example which shifts each letter one square to the left.
>>> grid = Grid.build([['a', 'b', 'c'], ['d', None, None]])
>>> scroll_left(grid)
[['b', 'c', None], [None, None, None]]
# squirrel_magic() Doctests:
View solution
def squirrel_magic(grid, x, y, n):
if grid.get(x, y) != 's':
return grid
# Acorn below
if grid.in_bounds(x, y + 1) and grid.get(x, y + 1) == 'a':
grid.set(x, y + 1, None)
return grid
# Acorn - up and to the left
if grid.in_bounds(x - n, y - 1) and grid.get(x - n, y - 1) == 'a':
grid.set(x - n, y - 1, None)
return grid
# No acorn
return grid
One working doctest
>>> grid = Grid.build([[None, 's', None], [None, 'a', None]])
>>> squirrel_magic(grid, 1, 0, 1)
[[None, 's', None], [None, None, None]]
Why it works
- Check bounds before reading either target square.
- Returning after the first match gives the acorn below priority.
- The doctest leaves the squirrel in place and removes the acorn.