Exerpad
🔥 1
10 XP
Lesson · Chapter: One Moving Dot+10 XP for reading

Update

Last chapter you drew one frame. The computer drew it twenty times a second — but it was the same picture every time, so nothing appeared to move.

Movement needs a second function:

python
def update(state, keys):
state["x"] = state["x"] + 1
return state
Output
Press Run to see the output.

Now the loop is a real loop:

  1. call update — the numbers change
  2. call draw — a picture is made from those numbers
  3. put it on screen
  4. do it again, twenty times a second

update changes numbers. draw turns numbers into a picture. Keeping those two jobs apart is the single most useful habit in this milestone.

What is state?

state is a dictionary that survives between frames. Everything the animation needs to remember lives in it.

You already have some keys for free:

python
state["x"] # starts at 0
state["y"] # starts at 0
Output
Press Run to see the output.

draw reads them. update changes them. That is the whole conversation.

The rule that will catch you

update must return state. Just like draw returns the grid:

python
def update(state, keys):
state["x"] = state["x"] + 1
return state # <- easy to forget
Output
Press Run to see the output.

Miss it and you'll see "update() didn't return anything."

Ignore keys for now. It's how the keyboard gets in, and you'll use it in Chapter 9 when you build something you can actually play.

Rows count downward

Worth burning in now, because it feels backwards at first:

  • state["y"] bigger → further down the screen
  • state["y"] smaller → further up

That is just how grid[row][col] works — row 0 is the top. A dot that "falls" has a y that grows.