Exercise 5 · Chapter: One Moving DotOptional+50 XP
Wrap Around
Run the earlier exercises long enough and the dot walks off the edge and crashes — there is no column 40.
Make it come back around instead. Move 5 columns per frame, and when it would
pass the right edge, wrap to the left.
The whole fix is one operator:
state["x"] = (state["x"] + 5) % WIDTH
% is remainder, from the Math chapter. Dividing by WIDTH means the answer
can never be WIDTH — it rolls over to 0. That is the entire trick behind
looping backgrounds, clocks, and anything cyclical.
Watch the numbers climb to 35 and then land back on 0.
Expected output
5 10 15 20 25 30 35 0 5
Need a hint?
3 available · costs 5 XP each
python
def update(state, keys):
state["x"] = state["x"] + 5
# This walks off the edge. Use % WIDTH so it wraps back to the left.
return state
def draw(state):
grid = blank_grid()
grid[6][state["x"]] = "magenta"
return grid