Exerpad
🔥 0
0 XP
Exercise 5 · Chapter: BounceOptional+50 XP

Corner to Corner

Put both bounces in one animation and you get the classic screensaver: a dot ricocheting around the whole rectangle.

Start at x of 2, y of 2, with both dx and dy at 1.

Nothing new to learn here — it is the last two exercises running at the same time. That is worth noticing: you did not need a "diagonal bounce" idea. Two independent bounces, one on each axis, produce it for free.

This is how nearly all game movement works. Each axis minds its own business.

Expected output
3/3 4/4 5/5 6/6 7/7 8/8 9/9 10/10 11/11 12/12 13/13 14/12 15/11 16/10 17/9
Need a hint?
3 available · costs 5 XP each
python
def new_game():
return {"x": 2, "y": 2, "dx": 1, "dy": 1}


def update(state, keys):
state["x"] = state["x"] + state["dx"]
if state["x"] <= 0 or state["x"] >= WIDTH - 1:
state["dx"] = state["dx"] * -1
# Now do the same for y.
return state


def draw(state):
grid = blank_grid()
grid[state["y"]][state["x"]] = "orange"
return grid