Exerpad
🔥 1
10 XP
Lesson · Chapter: Colour and Time+10 XP for reading

Counting Frames

Some animations don't move anything. They just change — a flashing light, a pulsing glow, a rainbow sliding along.

All of them need the same thing first: a number that goes up every frame.

python
def new_game():
return {"t": 0}

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

t is for "time" — though really it's just "how many frames have gone by". It is the most useful number in animation, because everything else can be worked out from it.

Turning a big number into a small one

t grows forever: 500, 5000, 50000. Almost nothing you draw wants a number that big. % cuts it down to a size you can use.

python
t % 4 # goes 0, 1, 2, 3, 0, 1, 2, 3, ...
t % WIDTH # goes 0, 1, 2, ... 39, 0, 1, ...
Output
Press Run to see the output.

That is a loop with no loop. % never lets the answer reach the thing you divide by, so it wraps on its own — forever, without you writing anything.

Picking from a list

Put colours in a list and use % to choose one:

python
COLOURS = ["red", "orange", "gold", "lime", "cyan", "violet"]

colour = COLOURS[state["t"] % len(COLOURS)]
Output
Press Run to see the output.

Six colours, and t % 6 is always a valid index into them. Use len(COLOURS) rather than 6 — then adding a colour to the list just works.

Position and colour from the same number

The trick that makes rainbows: work the colour out from the column as well as the time.

python
for col in range(WIDTH):
colour = COLOURS[(col + state["t"]) % len(COLOURS)]
grid[5][col] = colour
Output
Press Run to see the output.

Each column is one step further along the colour list than the one before, so you see bands. Add t and the whole pattern slides sideways every frame.

Nothing moves. The colours just take turns.