Exercise 5 · Chapter: DodgeRequired+50 XP
Score and Restart
Two small things turn this into a real game.
Score. Add 1 to state["score"] every frame the hero survives. Survival
time is the score — no extra rules needed.
The HUD. Write a fourth function:
def hud(state):
return "Score: " + str(state["score"])Whatever it returns is printed under the game. Forget the str() and Python
refuses to glue a number onto text — the same crash you met in Variables.
Restart. One line, at the very top of update:
if keys["r"]:
return new_game()Because new_game() builds a fresh state, restarting is literally "use a new
one". Nothing needs resetting by hand — which is the reward for having put all
the game's memory in one dictionary.
That's a complete game: it runs, you can lose, you're scored, and you can go again. Chapter 11 is the same shape, bigger.
Expected output
1/Score: 1 2/Score: 2 3/Score: 3 4/Score: 4 4/Score: 4 0/Score: 0 1/Score: 1
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, "score": 0}
def update(state, keys):
# Restart on R, before anything else.
if not state["is_playing"]:
return state
if keys["space"] and state["y"] == 0:
state["vy"] = 4
state["y"] = state["y"] + state["vy"]
state["vy"] = state["vy"] - 1
if state["y"] < 0:
state["y"] = 0
state["vy"] = 0
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
# Add one to the score for surviving this frame.
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
# Write hud(state) so it returns "Score: " followed by the score.