Menu
CoddyTech

Two Paddles

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

Two players share one keyboard. The left player uses W and S, the right player the Up and Down arrows. Each paddle is a Rect that moves up and down only.

left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)

Letter keys are pygame.K_w, pygame.K_s and so on, in lower case. Read all four keys from one pygame.key.get_pressed(), so both players can hold keys at the same time.

Keep both paddles in the window with clamp_ip, as you did with the basket.

challenge icon

Challenge

Easy

Add a paddle for each player.

  1. Before the loop, make left = pygame.Rect(20, 160, 12, 80) and right = pygame.Rect(568, 160, 12, 80).
  2. Move left 6 pixels up or down with W and S, and right with Up and Down. Keep both in the window.
  3. Draw left in blue (80, 160, 255) and right in red (235, 80, 80).

Press Play and press W and Up: both paddles move. 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

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

    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, (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