Exerpad
🔥 0
0 XP
Exercise 4 · Chapter: Draw a SpriteRequired+50 XP

Stay in the Picture

Let the hero walk far enough and it reaches the right-hand edge — and stamp tries to paint a column that doesn't exist:

IndexError: list assignment index out of range

Make stamp safe. Before painting a square, check it's really inside the grid. If it isn't, skip that square and carry on with the rest.

The hero should slide off the edge gracefully, half of it visible, instead of crashing.

Use and, not two nested ifs — you learned it in Conditions, and this is exactly the shape it's for:

if 0 <= top + r < HEIGHT and 0 <= left + c < WIDTH:

A stamp that can't crash is a stamp you can stop thinking about. Every chapter after this one uses it.

Expected output
........................................
........................................
........................................
........................................
........................................
......................................AA
.....................................AAA
......................................A.
........................................
........................................
........................................
........................................
........................................
########################################
........................................
........................................
........................................
........................................
........................................
.......................................A
......................................AA
.......................................A
........................................
........................................
........................................
........................................
........................................
########################################
........................................
........................................
........................................
........................................
........................................
........................................
.......................................A
........................................
........................................
........................................
........................................
........................................
........................................
########################################
Need a hint?
3 available · costs 5 XP each
python
HERO = [
[0, 1, 1, 0],
[1, 1, 1, 1],
[0, 1, 0, 1],
]


def stamp(grid, sprite, top, left, colour):
for r in range(len(sprite)):
for c in range(len(sprite[r])):
if sprite[r][c] == 1:
# Only paint if this square is inside the grid.
grid[top + r][left + c] = colour


def new_game():
return {"x": 36}


def update(state, keys):
state["x"] = state["x"] + 1
return state


def draw(state):
grid = blank_grid()
stamp(grid, HERO, 5, state["x"], "gold")
return grid