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

Both Walls

Now make it bounce forever, off both edges.

You could write two if statements — one per wall. But there is a neater way: whichever wall you hit, the answer is the same. Reverse whatever direction you currently have.

state["dx"] = state["dx"] * -1

Multiplying by -1 turns 1 into -1, and -1 back into 1. One line, both walls, and it keeps working if you change the speed later.

Start at column 2 with dx of 1 so the test sees a left bounce quickly.

Expected output
3/1 4/1 5/1 6/1 7/1 8/1 9/1 10/1 11/1 12/1 13/1 14/1 15/1 16/1 17/1 18/1 19/1 20/1 21/1 22/1 23/1 24/1 25/1 26/1 27/1 28/1 29/1 30/1 31/1 32/1 33/1 34/1 35/1 36/1 37/1 38/1 39/-1 38/-1 37/-1 36/-1 35/-1 34/-1 33/-1 32/-1 31/-1 30/-1 29/-1 28/-1 27/-1 26/-1 25/-1 24/-1 23/-1 22/-1 21/-1 20/-1 19/-1 18/-1 17/-1 16/-1 15/-1 14/-1 13/-1 12/-1 11/-1 10/-1 9/-1 8/-1 7/-1 6/-1 5/-1 4/-1 3/-1 2/-1 1/-1 0/1 1/1 2/1 3/1 4/1 5/1 6/1 7/1 8/1 9/1 10/1 11/1 12/1
Need a hint?
3 available · costs 5 XP each
python
def new_game():
return {"x": 2, "dx": 1}


def update(state, keys):
state["x"] = state["x"] + state["dx"]
if state["x"] >= WIDTH - 1:
state["dx"] = -1
# This only turns around at the right. Handle the left wall too.
return state


def draw(state):
grid = blank_grid()
grid[6][state["x"]] = "red"
return grid