Menu
CoddyTech

Hit the Paddle

Lesson 32 of 41 in Coddy's Make Games with Pygame course.

When the ball touches a paddle, it should head back the other way. ball.colliderect(right) tells you they touch.

Flipping the sign, vx = -vx, has a trap. If the ball is still inside the paddle on the next frame (it caught the paddle's end, or the paddle moved onto it), it flips again, and again: the ball shakes inside the paddle.

Set the direction instead of flipping it. abs(vx) is vx without its sign, so it is always positive:

if ball.colliderect(left):
    vx = abs(vx)
if ball.colliderect(right):
    vx = -abs(vx)

Off the left paddle the ball always goes right, and off the right paddle always left, however many frames they touch.

challenge icon

Challenge

Medium

Bounce the ball off the paddles.

  1. After the wall bounce, when the ball collides with left, set vx = abs(vx).
  2. When it collides with right, set vx = -abs(vx).

Press Play and catch the ball with the right paddle: it bounces back. Then Check.

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
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        left.y -= 6
    if keys[pygame.K_s]:
        left.y += 6
    if keys[pygame.K_UP]:
        right.y -= 6
    if keys[pygame.K_DOWN]:
        right.y += 6
    left.clamp_ip(screen.get_rect())
    right.clamp_ip(screen.get_rect())

    ball.x += vx
    ball.y += vy
    if ball.top <= 0 or ball.bottom >= 400:
        vy = -vy

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), left)
    pygame.draw.rect(screen, (235, 80, 80), right)
    pygame.draw.rect(screen, (255, 196, 0), ball)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Make Games with Pygame

Practice on your own: Pygame playground