Pong game in Python

Below is a simple implementation of a Pong game in Python using the Pygame library. Copy and paste this code into a Python file (e.g., PongGame.py) and run it to play the game. You can further enhance it by adding features such as scoring, sound effects, or improving the graphics.

import pygame
import sys

# Initialize Pygame
pygame.init()

# Constants
WIDTH, HEIGHT = 800, 600
PADDLE_WIDTH, PADDLE_HEIGHT = 20, 100
BALL_SIZE = 20
PADDLE_SPEED = 10
BALL_SPEED = 3

# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# Create window
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong Game")

# Initialize game variables
paddle1Y = HEIGHT // 2 - PADDLE_HEIGHT // 2
paddle2Y = HEIGHT // 2 - PADDLE_HEIGHT // 2
ballX = WIDTH // 2 - BALL_SIZE // 2
ballY = HEIGHT // 2 - BALL_SIZE // 2
ballXSpeed = BALL_SPEED
ballYSpeed = BALL_SPEED

# Game loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w] and paddle1Y - PADDLE_SPEED >= 0:
        paddle1Y -= PADDLE_SPEED
    if keys[pygame.K_s] and paddle1Y + PADDLE_HEIGHT + PADDLE_SPEED <= HEIGHT:
        paddle1Y += PADDLE_SPEED
    if keys[pygame.K_UP] and paddle2Y - PADDLE_SPEED >= 0:
        paddle2Y -= PADDLE_SPEED
    if keys[pygame.K_DOWN] and paddle2Y + PADDLE_HEIGHT + PADDLE_SPEED <= HEIGHT:
        paddle2Y += PADDLE_SPEED

    # Move ball
    ballX += ballXSpeed
    ballY += ballYSpeed

    # Collision with paddles
    if (ballX <= PADDLE_WIDTH and ballY + BALL_SIZE >= paddle1Y and ballY <= paddle1Y + PADDLE_HEIGHT) or \
       (ballX + BALL_SIZE >= WIDTH - PADDLE_WIDTH and ballY + BALL_SIZE >= paddle2Y and ballY <= paddle2Y + PADDLE_HEIGHT):
        ballXSpeed = -ballXSpeed

    # Collision with top and bottom walls
    if ballY <= 0 or ballY + BALL_SIZE >= HEIGHT:
        ballYSpeed = -ballYSpeed

    # Scoring
    if ballX <= 0 or ballX + BALL_SIZE >= WIDTH:
        ballX = WIDTH // 2 - BALL_SIZE // 2
        ballY = HEIGHT // 2 - BALL_SIZE // 2
        ballXSpeed = -ballXSpeed

    # Draw everything
    screen.fill(BLACK)
    pygame.draw.rect(screen, WHITE, (0, paddle1Y, PADDLE_WIDTH, PADDLE_HEIGHT))
    pygame.draw.rect(screen, WHITE, (WIDTH - PADDLE_WIDTH, paddle2Y, PADDLE_WIDTH, PADDLE_HEIGHT))
    pygame.draw.ellipse(screen, WHITE, (ballX, ballY, BALL_SIZE, BALL_SIZE))
    pygame.draw.aaline(screen, WHITE, (WIDTH // 2, 0), (WIDTH // 2, HEIGHT), 5)

    # Update display
    pygame.display.flip()

    # Control the game speed
    pygame.time.Clock().tick(60)