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

How Games Work

Here's what you're about to build:

What this step looks like when it works

You've been building Coin Quest all course long — a hero, a coin pouch, a backpack, a shop gate, an add_coins function. Time to put them together into something you can actually play.

Where you'll use this
Every game you've ever played — Mario, Minecraft, the little dinosaur that runs when your internet drops — works the way you're about to build. There is no second, fancier way. This is the way.

A game is a flipbook

Draw a stick figure on a page. On the next page, draw it slightly lower. Flip between them fast and the figure falls.

That's a game. A picture, then a slightly different picture, over and over. Each picture is called a frame. Coin Quest draws 20 frames every second.

Two questions, twenty times a second

To make each frame the computer asks you two questions:

  1. What changed? The hero moved a bit. A rock got closer. That's update.
  2. What does it look like now? That's draw.

You write those two answers as functions, and the computer asks them forever:

update  ->  draw  ->  update  ->  draw  ->  update  ->  draw  ->  ...

You do not write the loop. That's the surprising part. You just answer the two questions, and the game engine does the asking.

The state

Between frames, the game has to remember things: where the hero is, how many coins you've got, whether you're still alive. All of that lives in one dictionary called the state — exactly like the hero dictionary you built in the Dictionaries chapter.

python
state = {"y": 0, "vy": 0, "x": 0, "score": 0, "is_playing": True}
Output
Press Run to see the output.

update gets the state, changes it, and hands it back. draw gets the state and turns it into a picture.

The picture

The picture is a grid of coloured squares — the same __grid__ you painted pixel art with. The track is 40 squares wide and 14 squares tall.

You get these for free in every Coin Quest exercise:

NameWhat it is
blank_grid()a fresh empty track, sky above, dirt below
WIDTH40 — how many squares across
HEIGHT14 — how many squares down
GROUND12 — the row the hero stands on
Did you know?
The dinosaur in Chrome's "no internet" page is about 2,300 lines of code. The game you're about to write is under 40. The other 2,260 lines are menus, high-score saving, and making it work on phones.

Keys

update also gets a second thing: keys, telling you what's held down right now.

python
if keys["space"]:
print("jumping!")
Output
Press Run to see the output.

Check yourself

Pause & predict — what will this print?
state = {"y": 0}
state["y"] = state["y"] + 3

Ready? Let's draw a hero.