Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading