Bouncing screensaver (ala DVD screensaver) sticking to edges of screen


x = randint(50, width-60)
y = randint(50, height-60)
while True:
    x_speed = 1
    y_speed = 1
    if (x + 74 >= width) or (x <= 0):
        x_speed *= -1
    if (y + 38 >= height) or (y <= 0):
        y_speed *= -1
    x += x_speed
    y += y_speed

This code is meant to make the physics of a ‘DVD screensaver’. The 74/38 numbers are the dimensions of the screensaver picture. The screensaver should bounce around the screen, colliding with the walls.
However, when I ran the program, the picture I used stuck to the wall, oscillating back and forth one pixel as it moved across the wall, eventually stopping in a corner, where it vibrated similarly.

It seems as though it keeps flipping the x_speed / y_speed variables from + to – repeatedly, which keeps it on the border, which makes it keep flipping. It should just flip once, and then bounce away.

Here are the things I tried:

  • Changing the dimensions of the screen: It just makes it stick to a point further away from the edge of the screen

  • Adding a cooldown for when it can flip the speed variables (setting a variable to a number then incrementing it back to 0 each tick before it can re-flip): It goes past the edge of the screen, jittering back a pixel each time the cooldown ends.

  • Changing the dimensions of the picture (not visually, but in the physics): This only made it stick slightly past the edge of the screen.

I cannot think of anything else to try. I have looked for alternative code, but none of it works with my program/it isn’t in Python. Can anyone see any problems with the code?

Asked By: Commodore 64



Because of the while loop, the variables x_speed and y_speed are being instanced over and over again in each loop and don’t change.

Instead, put these variables outside the while loop so they don’t get instanced again.

Answered By: Blue Robin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.