Exercise 5 · Chapter: Coin QuestOptional+50 XP
Coin Quest: Collect the Coins
What this step looks like when it works
🪙 It's called Coin Quest. Time to earn the name.
A coin floats 3 squares above the ground, right over each rock. Jump the rock and you grab the coin — one jump, two payoffs.
1. Bring back add_coins. You wrote this in the Functions chapter:
def add_coins(coins, amount):
return coins + amountPaste it in. Real projects reuse the pieces you already built.
2. In new_game(), add "coins": [14, 26]
3. In update, move the coins left, same as the rocks.
4. Then collect them. Loop over the coins and build a list of the ones the
hero didn't get. A coin is collected when it's at column 5 or 6 and
state["y"] is 3 or more:
kept = []
for coin in state["coins"]:
if (coin == 5 or coin == 6) and state["y"] >= 3:
state["score"] = add_coins(state["score"], 1)
else:
kept.append(coin)
state["coins"] = kept5. In draw, paint each coin "yellow" at row GROUND - 3, if it's on screen.
Watch the counter under the game.
Expected output
0 0 0 0 0 0 0 1 1 1 1 1 1
Need a hint?
4 available · costs 5 XP each
python
# Your add_coins function from the Functions chapter goes here
def new_game():
return {
"y": 0,
"vy": 0,
"x": 0,
"score": 0,
"is_playing": True,
"rocks": [14, 26],
}
def update(state, keys):
if not state["is_playing"]:
return state
if keys["space"] and state["y"] == 0:
state["vy"] = 3
state["y"] = state["y"] + state["vy"]
state["vy"] = state["vy"] - 1
if state["y"] < 0:
state["y"] = 0
state["vy"] = 0
state["x"] = state["x"] + 1
moved = []
for rock in state["rocks"]:
moved.append(rock - 1)
state["rocks"] = moved
for rock in state["rocks"]:
if (rock == 5 or rock == 6) and state["y"] == 0:
state["is_playing"] = False