Exerpad
🔥 0
0 XP
Exercise 4 · Chapter: DodgeRequired+50 XP

Jump to Survive

Add the jump back in, and the game becomes playable.

Order inside update:

  1. if not playing, return
  2. jump if space is pressed and the hero is on the ground
  3. move the hero (y, vy, floor)
  4. move the rocks
  5. check collisions

Now a rock in column 6 is only fatal if the hero is on the ground. Jump in time and it passes underneath.

The test presses space on the very first frame. By the time the rock arrives the hero is in the air, and is_playing stays 1 all the way through — the first time in this milestone that a decision you make changes the outcome.

Expected output
1/4 1/7 1/9 1/10 1/10 1/9
Need a hint?
3 available · costs 5 XP each
python
def new_game():
return {"y": 0, "vy": 0, "rocks": [10, 22, 34], "is_playing": True}


def update(state, keys):
if not state["is_playing"]:
return state
# Jump if space is pressed and the hero is on the ground.
# Then move the hero: y += vy, vy -= 1, and stop at the floor.
for i in range(len(state["rocks"])):
state["rocks"][i] = state["rocks"][i] - 1
if state["rocks"][i] < 0:
state["rocks"][i] = WIDTH - 1
for i in range(len(state["rocks"])):
if state["rocks"][i] == 6 and state["y"] == 0:
state["is_playing"] = False
return state


def draw(state):
grid = blank_grid()
for i in range(len(state["rocks"])):
grid[GROUND][state["rocks"][i]] = "dimgray"
grid[GROUND - state["y"]][6] = "gold"
return grid