Creating a simple Pong clone can be done in Python using the Pygame library, which is a popular choice for 2D game development. Below is a basic example of how to create a Pong game.
First, ensure you have Pygame installed:
pip install pygame
Then, you can create a Pong clone using the following code:
import pygame
import sys
# Initialize Pygame
pygame.init()
# Constants
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
BALL_SPEED = 5
PADDLE_SPEED = 7
PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100
BALL_SIZE = 20
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Screen setup
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Pong Clone")
# Paddle setup
left_paddle = pygame.Rect(50, SCREEN_HEIGHT//2 - PADDLE_HEIGHT//2, PADDLE_WIDTH, PADDLE_HEIGHT)
right_paddle = pygame.Rect(SCREEN_WIDTH - 50 - PADDLE_WIDTH, SCREEN_HEIGHT//2 - PADDLE_HEIGHT//2, PADDLE_WIDTH, PADDLE_HEIGHT)
# Ball setup
ball = pygame.Rect(SCREEN_WIDTH//2 - BALL_SIZE//2, SCREEN_HEIGHT//2 - BALL_SIZE//2, BALL_SIZE, BALL_SIZE)
ball_dx, ball_dy = BALL_SPEED, BALL_SPEED
# Game loop
clock = pygame.time.Clock()
def move_paddles(keys):
if keys[pygame.K_w] and left_paddle.top > 0:
left_paddle.y -= PADDLE_SPEED
if keys[pygame.K_s] and left_paddle.bottom < SCREEN_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 < SCREEN_HEIGHT:
right_paddle.y += PADDLE_SPEED
def move_ball():
global ball_dx, ball_dy
ball.x += ball_dx
ball.y += ball_dy
# Ball collision with top and bottom walls
if ball.top <= 0 or ball.bottom >= SCREEN_HEIGHT:
ball_dy = -ball_dy
# Ball collision with paddles
if ball.colliderect(left_paddle) or ball.colliderect(right_paddle):
ball_dx = -ball_dx
# Ball out of bounds
if ball.left <= 0 or ball.right >= SCREEN_WIDTH:
ball.center = (SCREEN_WIDTH//2, SCREEN_HEIGHT//2)
ball_dx = -ball_dx # Reset ball direction
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
move_paddles(keys)
move_ball()
# 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, (SCREEN_WIDTH // 2, 0), (SCREEN_WIDTH // 2, SCREEN_HEIGHT))
pygame.display.flip()
clock.tick(60)
This code sets up a basic Pong game with two paddles controlled by the keyboard:
- W and S keys move the left paddle up and down.
- Up and Down arrow keys move the right paddle up and down.
The ball bounces off the top and bottom edges of the screen, as well as the paddles. The ball resets to the center of the screen when it goes out of bounds, with the direction reversed.
Feel free to expand on this basic template by adding scoring, enhancing graphics, or implementing more advanced features.