Exerpad
🔥 1
10 XP
Lesson · Chapter: Dodge+10 XP for reading

Something to Lose

You have a hero who jumps and a world that scrolls. That is not yet a game, because nothing can go wrong.

A game needs three more things, and none of them are hard:

  1. a way to lose — collision
  2. a way for the game to stop — a flag in the state
  3. a reason to care — a score

Collision is just comparing numbers

There is no physics engine here. A crash is an if:

python
for rock in state["rocks"]:
if rock == 6 and state["y"] == 0:
state["is_playing"] = False
Output
Press Run to see the output.

"Is a rock in the hero's column, and is the hero on the ground?" If yes, they touched. If the hero is in the air, the rock passes underneath.

That's it. Every collision in every game is some version of "are these two things in the same place?"

A flag that stops the world

python
def update(state, keys):
if not state["is_playing"]:
return state
...
Output
Press Run to see the output.

Return early and nothing else in update runs — rocks stop, gravity stops, the picture freezes. One if at the top of the function turns the whole game off.

is_playing is an ordinary True/False in the state, exactly like the booleans you met in Milestone 1.

The HUD

hud(state) is a fourth function you can write. Whatever string it returns gets printed under the game:

python
def hud(state):
return "Score: " + str(state["score"])
Output
Press Run to see the output.

str() matters. "Score: " + 5 is the crash you met back in Variables — Python will not glue a number onto text for you.

Order inside update

The order these happen in changes the game:

python
1. if not playing: return
2. handle keys (jump)
3. move the hero (gravity)
4. move the world (rocks)
5. check collisions
6. score
Output
Press Run to see the output.

Check collisions after everything has moved, or you're testing where things used to be. That is the single most common source of "it hit me but it clearly missed!" — and players notice immediately.