Two Paddles
Lesson 31 of 40 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
Easy- Before the loop, make
left = pygame.Rect(20, 160, 12, 80)andright = pygame.Rect(568, 160, 12, 80). - Move
left6 pixels up or down with W and S, andrightwith Up and Down. Keep both in the window. - Draw
leftin blue(80, 160, 255)andrightin red(235, 80, 80).
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()
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