Exercise 2 · Chapter: Colour and TimeRequired+50 XP
Flashing Square
Take the solid block from Chapter 1 and make it change colour every frame.
Here's the shape of it. update decides which colour — as a number:
state["colour"] = state["t"] % len(COLOURS)
and draw turns that number into paint:
colour = COLOURS[state["colour"]]
That is the update/draw split again, and this is a good example of why it's worth keeping. The decision is a number in the state, so it can be tested, printed, and reasoned about. The picture is just what that number looks like.
The trace prints state["colour"], so you should see 1 2 3 4 5 0 — six
colours, cycling.
Paint rows 4 to 7, columns 10 to 19, as before.
Need a hint?
3 available · costs 5 XP each
python
COLOURS = ["red", "orange", "gold", "lime", "cyan", "violet"]
def new_game():
return {"t": 0, "colour": 0}
def update(state, keys):
state["t"] = state["t"] + 1
# Work out which colour to use: t % len(COLOURS)
return state
def draw(state):
grid = blank_grid()
colour = COLOURS[state["colour"]]
for row in range(4, 8):
for col in range(10, 20):
grid[row][col] = colour
return grid