Bounce
Lesson 30 of 40 in Coddy's Make Games with Pygame course.
A ball bounces off the top and bottom edges. At the moment it touches one, flip the sign of vy: moving down becomes moving up by the same amount.
if ball.top <= 0 or ball.bottom >= 400:
vy = -vyTest with <= and >=, not ==. The ball moves 4 pixels a frame, so its bottom goes 395, 399, 403 and is never exactly 400.
The left and right edges are where points are scored, so the ball does not bounce there. For now it flies out.
Challenge
EasyAfter moving the ball, flip vy when the ball's top is at 0 or less, or its bottom at 400 or more.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
ball = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
ball.x += vx
ball.y += vy
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (255, 196, 0), ball)
pygame.display.flip()
clock.tick(60)
pygame.quit()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Make Games with Pygame
1The Game Loop
Open a WindowFill the Background4Two Players and a Ball
The BallBouncePractice on your own: Pygame playground