Creating a ping pong (or “Pong”) game in Python typically involves using the Pygame library, which provides functionalities for creating games and multimedia applications. Below is a simple implementation of a Pong game using Pygame.
First, make sure you have Pygame installed. If not, you can install it using pip:
pip install pygame
Now, you can use the following Python script to create a basic Pong game:
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Pong Game')
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Paddle settings
PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100
paddle_speed = 7
# Ball settings
BALL_SIZE = 20
ball_speed_x = 5 * random.choice((1, -1))
ball_speed_y = 5 * random.choice((1, -1))
# Paddle positions
left_paddle = pygame.Rect(10, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
right_paddle = pygame.Rect(WIDTH - 20, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
# Ball position
ball = pygame.Rect(WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2, BALL_SIZE, BALL_SIZE)
# Score
left_score = 0
right_score = 0
font = pygame.font.Font(None, 74)
# Game loop
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Paddle movement
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
# Ball movement
ball.x += ball_speed_x
ball.y += ball_speed_y
# Ball collision with top and bottom
if ball.top <= 0 or ball.bottom >= HEIGHT:
ball_speed_y *= -1
# Ball collision with paddles
if ball.colliderect(left_paddle) or ball.colliderect(right_paddle):
ball_speed_x *= -1
# Ball out of bounds
if ball.left <= 0:
right_score += 1
ball.x, ball.y = WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2
ball_speed_x *= random.choice((1, -1))
ball_speed_y *= random.choice((1, -1))
if ball.right >= WIDTH:
left_score += 1
ball.x, ball.y = WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2
ball_speed_x *= random.choice((1, -1))
ball_speed_y *= random.choice((1, -1))
# Drawing
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, left_paddle)
pygame.draw.rect(screen, WHITE, right_paddle)
pygame.draw.ellipse(screen, WHITE, ball)
pygame.draw.aaline(screen, WHITE, (WIDTH // 2, 0), (WIDTH // 2, HEIGHT))
# Draw scores
left_text = font.render(str(left_score), True, WHITE)
screen.blit(left_text, (WIDTH // 4, 20))
right_text = font.render(str(right_score), True, WHITE)
screen.blit(right_text, (WIDTH * 3 // 4, 20))
pygame.display.flip()
clock.tick(60)
pygame.quit()
This code sets up a basic Pong game where two players can control paddles using the W/S keys for the left paddle and the UP/DOWN arrow keys for the right paddle. The ball bounces off the paddles and the top and bottom of the screen, and the game tracks the score for each player. The game runs in a loop until the window is closed.
Enhanced Version
I’ll enhance the Pong game by adding features such as a scoring system, a winning condition, and some additional visual elements. Here’s an improved version of the Pong game with these enhancements:
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Pong Game')
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Paddle settings
PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100
paddle_speed = 7
# Ball settings
BALL_SIZE = 20
ball_speed_x = 5 * random.choice((1, -1))
ball_speed_y = 5 * random.choice((1, -1))
# Paddle positions
left_paddle = pygame.Rect(10, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
right_paddle = pygame.Rect(WIDTH - 20, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
# Ball position
ball = pygame.Rect(WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2, BALL_SIZE, BALL_SIZE)
# Score
left_score = 0
right_score = 0
winning_score = 10
font = pygame.font.Font(None, 74)
winning_font = pygame.font.Font(None, 100)
# Sounds
hit_sound = pygame.mixer.Sound("hit.wav")
score_sound = pygame.mixer.Sound("score.wav")
# Game loop
running = True
clock = pygame.time.Clock()
def draw_board():
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, left_paddle)
pygame.draw.rect(screen, WHITE, right_paddle)
pygame.draw.ellipse(screen, WHITE, ball)
pygame.draw.aaline(screen, WHITE, (WIDTH // 2, 0), (WIDTH // 2, HEIGHT))
left_text = font.render(str(left_score), True, WHITE)
screen.blit(left_text, (WIDTH // 4, 20))
right_text = font.render(str(right_score), True, WHITE)
screen.blit(right_text, (WIDTH * 3 // 4, 20))
def reset_ball():
ball.x, ball.y = WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2
ball_speed_x *= random.choice((1, -1))
ball_speed_y *= random.choice((1, -1))
def check_winner():
if left_score >= winning_score:
return "Left Player Wins!"
elif right_score >= winning_score:
return "Right Player Wins!"
return None
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Paddle movement
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
# Ball movement
ball.x += ball_speed_x
ball.y += ball_speed_y
# Ball collision with top and bottom
if ball.top <= 0 or ball.bottom >= HEIGHT:
ball_speed_y *= -1
# Ball collision with paddles
if ball.colliderect(left_paddle) or ball.colliderect(right_paddle):
ball_speed_x *= -1
hit_sound.play()
# Ball out of bounds
if ball.left <= 0:
right_score += 1
score_sound.play()
reset_ball()
if ball.right >= WIDTH:
left_score += 1
score_sound.play()
reset_ball()
# Drawing
draw_board()
# Check for winner
winner = check_winner()
if winner:
winner_text = winning_font.render(winner, True, RED if winner.startswith("Left") else BLUE)
screen.blit(winner_text, (WIDTH // 4, HEIGHT // 3))
pygame.display.flip()
pygame.time.wait(3000)
left_score = 0
right_score = 0
reset_ball()
pygame.display.flip()
clock.tick(60)
pygame.quit()
New Features Added:
- Scoring System: Players score points when the ball goes out on the opponent’s side.
- Winning Condition: The game ends when a player reaches a specified score (
winning_score
), and a winning message is displayed. - Sounds: Added sound effects for paddle hits and scoring (ensure you have
hit.wav
andscore.wav
sound files in the same directory as the script). - Visual Enhancements: Added color-coded winning messages.
Instructions:
- Save the script to a
.py
file. - Ensure you have Pygame installed (
pip install pygame
). - Run the script.
- Control the left paddle using
W
(up) andS
(down), and the right paddle using theUP
andDOWN
arrow keys.
This code provides a more engaging and complete Pong game experience. Enjoy!