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

Your Own State

So far you've used state["x"] and state["y"] — but you never created them. They were already there, because the computer hands you a starting state if you don't make one.

That runs out fast. To bounce, the dot has to remember which way it is going, and there is no key for that.

new_game sets things up

python
def new_game():
return {"x": 5, "dx": 1}
Output
Press Run to see the output.

new_game runs once, before the first frame. Whatever dictionary you return becomes the state, and update gets it from then on.

The name dx is the usual shorthand for "the change in x" — how much x moves each frame. Call it whatever you like; dx is what most people write.

Now three functions work together:

functionwhen it runsjob
new_game()once, at the startbuild the starting state
update(state, keys)every framechange the numbers
draw(state)every frameturn numbers into a picture

If you write new_game, you own the whole state. x and y are no longer handed to you — if your dictionary doesn't have them and your draw asks for them, you get a KeyError. Put in everything you need.

Turning around

A bounce is a direction that flips sign:

python
state["x"] = state["x"] + state["dx"]

if state["x"] >= WIDTH - 1:
state["dx"] = -1
Output
Press Run to see the output.

Adding -1 moves left. Adding 1 moves right. Multiplying by -1 flips whichever one you have:

python
state["dx"] = state["dx"] * -1
Output
Press Run to see the output.

That one line handles both walls, which is why it's worth knowing.

Why WIDTH - 1

The columns are numbered 0 to 39. WIDTH is 40, so the last real column is WIDTH - 1. Check against WIDTH instead and you'll try to paint column 40, which does not exist — and Python will say so:

IndexError: list assignment index out of range

The off-by-one at the edge is the classic bug in this chapter. Expect it once.