Exerpad
🔥 0
0 XP
Exercise 3 · Chapter: GravityRequired+50 XP

Bounce Forever

A ball that stops dead is not a ball.

Keep the clamp, but instead of setting vy to 0, flip its sign. A dot falling at speed 4 now travels upward at speed 4.

Gravity keeps doing its job on the way up: vy goes -4, -3, -2, -1, 0 — the ball slows, stops, and falls again. You do not need any code for "going up". It comes free from the same two lines.

This is the same trick as the wall bounce in Chapter 3, applied to speed instead of direction.

Expected output
1/1 3/2 6/3 10/4 13/-5 9/-4 6/-3 4/-2 3/-1 3/0 4/1 6/2
Need a hint?
3 available · costs 5 XP each
python
def new_game():
return {"y": 0, "vy": 0}


def update(state, keys):
state["vy"] = state["vy"] + 1
state["y"] = state["y"] + state["vy"]
if state["y"] >= HEIGHT - 1:
state["y"] = HEIGHT - 1
state["vy"] = 0 # this stops the ball dead — make it bounce instead
return state


def draw(state):
grid = blank_grid()
grid[state["y"]][20] = "white"
return grid