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
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:
| function | when it runs | job |
|---|---|---|
new_game() | once, at the start | build the starting state |
update(state, keys) | every frame | change the numbers |
draw(state) | every frame | turn 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:
Adding -1 moves left. Adding 1 moves right. Multiplying by -1 flips
whichever one you have:
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.