import pygame
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Create the game window
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong Game")
# Define the paddles
paddle_width, paddle_height = 10, 100
paddle_speed = 5
left_paddle = pygame.Rect(50, HEIGHT // 2 - paddle_height // 2, paddle_width, paddle_height)
right_paddle = pygame.Rect(WIDTH - 50 - paddle_width, HEIGHT // 2 - paddle_height // 2, paddle_width, paddle_height)
# Define the ball
ball_width, ball_speed = 10, 5
ball = pygame.Rect(WIDTH // 2 - ball_width // 2, HEIGHT // 2 - ball_width // 2, ball_width, ball_width)
ball_direction = [random.choice((1, -1)), random.choice((1, -1))]
# Game variables
left_score, right_score = 0, 0
font = pygame.font.Font(None, 36)
# Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move paddles
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and left_paddle.top > 0:
left_paddle.y -= paddle_speed
if keys[pygame.K_s] and left_paddle.bottom < HEIGHT:
left_paddle.y += paddle_speed
if keys[pygame.K_UP] and right_paddle.top > 0:
right_paddle.y -= paddle_speed
if keys[pygame.K_DOWN] and right_paddle.bottom < HEIGHT:
right_paddle.y += paddle_speed
# Move the ball
ball.x += ball_speed * ball_direction[0]
ball.y += ball_speed * ball_direction[1]
# Ball collisions with paddles
if ball.colliderect(left_paddle) or ball.colliderect(right_paddle):
ball_direction[0] *= -1
# Ball collisions with top and bottom walls
if ball.top <= 0 or ball.bottom >= HEIGHT:
ball_direction[1] *= -1
# Scoring
if ball.left <= 0:
right_score += 1
ball = pygame.Rect(WIDTH // 2 - ball_width // 2, HEIGHT // 2 - ball_width // 2, ball_width, ball_width)
ball_direction = [random.choice((1, -1)), random.choice((1, -1))]
elif ball.right >= WIDTH:
left_score += 1
ball = pygame.Rect(WIDTH // 2 - ball_width // 2, HEIGHT // 2 - ball_width // 2, ball_width, ball_width)
ball_direction = [random.choice((1, -1)), random.choice((1, -1))]
# Clear the screen
screen.fill(BLACK)
# Draw paddles and ball
pygame.draw.rect(screen, WHITE, left_paddle)
pygame.draw.rect(screen, WHITE, right_paddle)
pygame.draw.ellipse(screen, WHITE, ball)
# Draw the scores
left_text = font.render(str(left_score), True, WHITE)
right_text = font.render(str(right_score), True, WHITE)
screen.blit(left_text, (WIDTH // 4, 20))
screen.blit(right_text, (3 * WIDTH // 4 - right_text.get_width(), 20))
# Update the display
pygame.display.flip()
# Quit the game
pygame.quit()