Exerpad
🔥 0
0 XP
Exercise 5 · Chapter: Draw a SpriteOptional+50 XP

A Whole Scene

One stamp call draws one thing. Three calls draw a scene.

Build this picture:

  • a TREE at row 8, column 6
  • another TREE at row 8, column 28
  • the HERO at row 9, column state["x"], walking right

Stamp the trees first and the hero last. Whatever you paint later wins, so the hero walks in front of the scenery. Painting order is the only depth your grid has, and it's enough.

This is a complete scene made of two sprites and one function — and it is genuinely all a 2D game does when it draws a frame.

Expected output
........................................
........................................
........................................
........................................
........................................
........................................
........................................
........................................
........A.....................A.........
....BB.AAA...................AAA........
...BBBBAAAA.................AAAAA.......
....B.B.A.....................A.........
........A.....................A.........
########################################
........................................
........................................
........................................
........................................
........................................
........................................
........................................
........................................
........A.....................A.........
.....BBAAA...................AAA........
....BBBBAAA.................AAAAA.......
.....B.BA.....................A.........
........A.....................A.........
########################################
........................................
........................................
........................................
........................................
........................................
........................................
........................................
........................................
........A.....................A.........
......BBAA...................AAA........
.....BBBBAA.................AAAAA.......
......B.B.....................A.........
........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],
]

TREE = [
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 1],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
]


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:
if 0 <= top + r < HEIGHT and 0 <= left + c < WIDTH:
grid[top + r][left + c] = colour


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


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


def draw(state):
grid = blank_grid()
# Two trees at row 8 (columns 6 and 28), then the hero at row 9.
stamp(grid, HERO, 9, state["x"], "gold")