0

Is there a condition that can be added to this code that will cause the x_direction to change making the ball appear to bounce if width is exceeded?Something like: if x_val > width x_direction == x_direction * -1? (likewise for the y_direction).

import pygame
BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE = (50,50,255)
YELLOW = (255,255,0)
width = 64
height = 480
pygame.init()
size = (width,height)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pong")
done = False
clock = pygame.time.Clock()
ball_width = 20
x_val = 150
y_val = 200
x_direction = 1
y_direction = 1

while not done:
    for event in pygame.event.get():
       if event.type == pygame.QUIT:
           done = True

x_val = x_val + x_direction
y_val = y_val + y_direction  
screen.fill (BLACK)
# condition to go here to make ball bounce

pygame.draw.rect(screen, BLUE, (x_val,y_val,ball_width,20))      
pygame.display.flip()
clock.tick(60)

pygame.quit()

Pieman
  • 3
  • 3
  • *Something like: if x_val > width x_direction == x_direction * -1?* This makes sense to me, although 1) You want `=` instead of `==` 2) This would only handle one side of the screen. 3) In traditional pong, the ball doesn't bounce off of the left and right sides of the screen; instead it counts as a point for one player. On another note, most of the game logic should probably be contained within the `while not done` loop (though this may just be a formatting issue with your post). – 0x5453 Nov 06 '18 at 20:21

1 Answers1

0

Your x_val and y_val need to be incremented inside of the main loop, otherwise they will be incremented once and never again.

You are very close to having the conditional you need. Here is some code that makes the ball change directions if it hits the walls of the screen:

if x_val < 0 or x_val > width:
    x_direction = x_direction * -1

if y_val < 0 or x_val > height:
   y_direction = y_direction * -1

This code would have to be included in the main loop as well, since we need to check the position of the ball to see if it is colliding with the wall on every frame.

Since your ball has a size and your x_val and y_val variables represent the center of your ball, you will have to include the ball size in the conditional above to make the ball bounce from its edge as opposed to its center.

  • 1
    I understand that thank you comments are frowned upon but as a first time user, thank you for your response which was very helpful. I have voted for and ticked your answer. – Pieman Nov 07 '18 at 12:35