Exerpad
🔥 1
10 XP
Lesson · Chapter: Many at Once+10 XP for reading

A List of Things

Everything so far has animated one thing. Rain needs a hundred.

You are not going to write x1, x2, x3. You already know the answer — a list.

python
def new_game():
return {"drops": [0, 3, 6]}
Output
Press Run to see the output.

That's three raindrops, at rows 0, 3 and 6.

Moving all of them

Loop over the list and move each one:

python
def update(state, keys):
for i in range(len(state["drops"])):
state["drops"][i] = state["drops"][i] + 1
return state
Output
Press Run to see the output.

Note state["drops"][i] = ... — you're changing the item inside the list. This is the pattern that trips people up:

python
for drop in state["drops"]:
drop = drop + 1 # DOES NOTHING
Output
Press Run to see the output.

drop is a copy of the number. Adding to it changes the copy and throws it away. To change the list you have to say which slot you're changing, and that means looping over the index.

Drawing all of them

Same shape, in draw:

python
def draw(state):
grid = blank_grid()
for i in range(len(state["drops"])):
row = state["drops"][i]
col = 8 + i * 10
grid[row][col] = "aqua"
return grid
Output
Press Run to see the output.

8 + i * 10 spreads the drops across the picture: drop 0 at column 8, drop 1 at column 18, drop 2 at column 28. Using the index for position is a handy trick — no second list needed.

One loop each, not one loop for both

update loops to change numbers. draw loops to paint. Same list, two separate passes.

It might look like you could do both in one loop and save a few lines. Don't. The moment you want to draw something twice, or update twice per frame, or skip drawing while paused, the merged version fights you.