Below is a simple Python implementation of the classic Pong game using the Pygame library. This code creates a two-player game where one player controls the left paddle with the 'W' and 'S' keys, and the other controls the right paddle with the UP and DOWN arrow keys. The ball bounces off the walls and paddles, and scores are updated when the ball goes out of bounds.
Requirements:
- You need to have Pygame installed. You can install it using pip:
pip install pygame
- This code uses the
random module for randomizing the ball's initial direction.
Code Explanation:
- The game window is 800x600 pixels.
- Paddles are controlled by keyboard input and cannot move off the screen.
- The ball bounces off the top/bottom walls and paddles. If it goes past a paddle, a point is scored, and the ball resets.
- Scores are displayed at the top of the screen.
- The game runs at 60 frames per second for smooth animation.
- Press the close button or ESC key to quit.
Here's the complete Python code:
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Constants for the game
WIDTH, HEIGHT = 800, 600
PADDLE_WIDTH, PADDLE_HEIGHT = 20, 100
BALL_SIZE = 20
PADDLE_SPEED = 5
BALL_SPEED_X = 5
BALL_SPEED_Y = 5
FPS = 60
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")
# Clock for controlling frame rate
clock = pygame.time.Clock()
# Font for displaying scores
font = pygame.font.Font(None, 74)
# Initial positions and velocities
# Paddles
paddle_a_x = 50
paddle_a_y = HEIGHT // 2 - PADDLE_HEIGHT // 2
paddle_b_x = WIDTH - 50 - PADDLE_WIDTH
paddle_b_y = HEIGHT // 2 - PADDLE_HEIGHT // 2
# Ball
ball_x = WIDTH // 2 - BALL_SIZE // 2
ball_y = HEIGHT // 2 - BALL_SIZE // 2
ball_dx = BALL_SPEED_X * random.choice([-1, 1]) # Random horizontal direction
ball_dy = BALL_SPEED_Y * random.choice([-1, 1]) # Random vertical direction
# Scores
score_a = 0
score_b = 0
# Main game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# Get keys pressed
keys = pygame.key.get_pressed()
# Move paddle A (left) with W and S keys
if keys[pygame.K_w] and paddle_a_y > 0:
paddle_a_y -= PADDLE_SPEED
if keys[pygame.K_s] and paddle_a_y < HEIGHT - PADDLE_HEIGHT:
paddle_a_y += PADDLE_SPEED
# Move paddle B (right) with UP and DOWN arrows
if keys[pygame.K_UP] and paddle_b_y > 0:
paddle_b_y -= PADDLE_SPEED
if keys[pygame.K_DOWN] and paddle_b_y < HEIGHT - PADDLE_HEIGHT:
paddle_b_y += PADDLE_SPEED
# Update ball position
ball_x += ball_dx
ball_y += ball_dy
# Ball collision with top and bottom walls
if ball_y <= 0 or ball_y >= HEIGHT - BALL_SIZE:
ball_dy = -ball_dy # Reverse vertical direction
# Ball collision with paddles (simple rectangle overlap check)
if (paddle_a_x <= ball_x <= paddle_a_x + PADDLE_WIDTH and
paddle_a_y <= ball_y <= paddle_a_y + PADDLE_HEIGHT):
ball_dx = -ball_dx # Reverse horizontal direction on paddle A hit
elif (paddle_b_x <= ball_x + BALL_SIZE <= paddle_b_x + PADDLE_WIDTH and
paddle_b_y <= ball_y <= paddle_b_y + PADDLE_HEIGHT):
ball_dx = -ball_dx # Reverse horizontal direction on paddle B hit
# Check if ball goes out of bounds (scoring)
if ball_x <= 0: # Ball goes past left side, score for B
score_b += 1
# Reset ball position and velocity
ball_x = WIDTH // 2 - BALL_SIZE // 2
ball_y = HEIGHT // 2 - BALL_SIZE // 2
ball_dx = BALL_SPEED_X * random.choice([-1, 1])
ball_dy = BALL_SPEED_Y * random.choice([-1, 1])
elif ball_x >= WIDTH - BALL_SIZE: # Ball goes past right side, score for A
score_a += 1
# Reset ball position and velocity
ball_x = WIDTH // 2 - BALL_SIZE // 2
ball_y = HEIGHT // 2 - BALL_SIZE // 2
ball_dx = BALL_SPEED_X * random.choice([-1, 1])
ball_dy = BALL_SPEED_Y * random.choice([-1, 1])
# Draw everything
screen.fill(BLACK) # Clear the screen with black
# Draw paddles
pygame.draw.rect(screen, WHITE, (paddle_a_x, paddle_a_y, PADDLE_WIDTH, PADDLE_HEIGHT))
pygame.draw.rect(screen, WHITE, (paddle_b_x, paddle_b_y, PADDLE_WIDTH, PADDLE_HEIGHT))
# Draw ball
pygame.draw.rect(screen, WHITE, (ball_x, ball_y, BALL_SIZE, BALL_SIZE))
# Draw scores
score_text_a = font.render(str(score_a), True, WHITE)
score_text_b = font.render(str(score_b), True, WHITE)
screen.blit(score_text_a, (WIDTH // 4, 10)) # Left score
screen.blit(score_text_b, (3 * WIDTH // 4, 10)) # Right score
# Update the display
pygame.display.flip()
# Cap the frame rate
clock.tick(FPS)
# Quit Pygame
pygame.quit()
sys.exit()
How to Run:
- Save the code in a file, e.g.,
pong.py.
- Run the file using Python:
python pong.py
- Use the controls:
- Left paddle: 'W' (up) and 'S' (down).
- Right paddle: UP arrow (up) and DOWN arrow (down).
- Quit: Close the window or press ESC.
Notes:
- This is a basic version. The ball's bounce is simple and doesn't include angle variations based on paddle hit position. If you want more advanced features (e.g., sound, AI opponent, or better collision detection), I can help extend this code.
- The game might have minor issues with fast ball speeds passing through paddles, but it's generally fine for low speeds.
- Feel free to modify constants like paddle speed or ball size to tweak the gameplay. If you have any questions or need improvements, let me know!