0

my Python code has a circle which moves from the right of the screen to the left but it stops. I would like it to bounce off the left edge and continue moving to the right and then bounce off the right edge to the left and so on. I think I'm missing a line. I have tried several things but it doesn't seem to be working. Please see code below. Any advice would be very grateful.

import pygame


pygame.init()
size = width, height = 400, 300
screen = pygame.display.set_mode(size)

x_pos = 380
y_pos = 280
r = 20

running = True
while running: # game cycle
    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    pygame.draw.circle(screen, (0, 255, 0), (x_pos, y_pos), r)
    if x_pos > 20: # do not let the ball roll out of the screen    
        x_pos -= 1 
        


        
    pygame.time.delay(5) # delay in milliseconds
    pygame.display.flip()
pygame.quit()

I think I am expecting another IF statement which allows it to bounce off the edge. I would like to continue using the code that I have, and I'm looking for just one or two lines that can hopefully solve my problems. I don't want the code to be completely revamped.

Faz
  • 1
  • 1

2 Answers2

0

you could define a veriable xSpeed which is initially positive. every frame you would add xSpeed to the current x Position. when ever the ball hits the right or left wall xSpeed's sign should get flipped.

Anton
  • 563
  • 4
  • 13
0

You need to change your move method a bit, you need to remove the else blocks as they mess up ball's movement, just always move the ball once when calling move. You can also combine checking whether ball is on edge for an axis in one line (using or):

def move(self):

    if self.top <= 0 or self.bottom >= HEIGHT:
        self.speedY *= -1

    if self.left <= 0 or self.right >= WIDTH:
        self.speedX *= -1

    self.y += self.speedY
    self.x += self.speedX
Being_shawn
  • 122
  • 9