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

A Walking Hero

Make the hero walk.

update adds 1 to state["x"] each frame, and draw stamps the hero at left = state["x"], on row 5.

Notice how little there is to do. Chapter 2 moved a single square; this moves a twelve-square shape, and the difference is nothing — because stamp already knows how to put a sprite wherever you point it.

That is what a good function buys you. The complicated part happened once.

Expected output
........................................
........................................
........................................
........................................
........................................
..AA....................................
.AAAA...................................
..A.A...................................
........................................
........................................
........................................
........................................
........................................
########################################
........................................
........................................
........................................
........................................
........................................
...AA...................................
..AAAA..................................
...A.A..................................
........................................
........................................
........................................
........................................
........................................
########################################
........................................
........................................
........................................
........................................
........................................
....AA..................................
...AAAA.................................
....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:
grid[top + r][left + c] = colour


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


def update(state, keys):
# Move the hero one column right each frame.
return state


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