- 19th Nov 2023
- 12:44 pm
Creating a Pong game in Python using the Pygame library is a great way to learn game development fundamentals. Below is a basic implementation of a Pong game:
Ensure you have Pygame installed. If you haven't installed it yet, you can do so using pip:
pip install pygame
Here's an example code for a simple Pong game:
import pygame
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100
BALL_SIZE = 20
FPS = 60
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Create the game window
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")
# Paddle and ball variables
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)
ball = pygame.Rect(WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2, BALL_SIZE, BALL_SIZE)
ball_speed_x = 7 * random.choice((1, -1))
ball_speed_y = 7 * random.choice((1, -1))
# Game loop
clock = pygame.time.Clock()
running = True
while running:
win.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
# Move paddles
if keys[pygame.K_w] and left_paddle.top > 0:
left_paddle.y -= 5
if keys[pygame.K_s] and left_paddle.bottom < HEIGHT:
left_paddle.y += 5
if keys[pygame.K_UP] and right_paddle.top > 0:
right_paddle.y -= 5
if keys[pygame.K_DOWN] and right_paddle.bottom < HEIGHT:
right_paddle.y += 5
# Move the ball
ball.x += ball_speed_x
ball.y += ball_speed_y
# Ball collision with paddles
if ball.colliderect(left_paddle) or ball.colliderect(right_paddle):
ball_speed_x *= -1
# Ball collision with walls
if ball.top <= 0 or ball.bottom >= HEIGHT:
ball_speed_y *= -1
# Ball out of bounds
if ball.left <= 0 or ball.right >= WIDTH:
ball.center = (WIDTH // 2, HEIGHT // 2)
ball_speed_x *= random.choice((1, -1))
ball_speed_y *= random.choice((1, -1))
# Draw paddles and ball
pygame.draw.rect(win, WHITE, left_paddle)
pygame.draw.rect(win, WHITE, right_paddle)
pygame.draw.ellipse(win, WHITE, ball)
# Update display
pygame.display.flip()
clock.tick(FPS)
# Quit Pygame
pygame.quit()
This code creates a basic Pong game with two paddles controlled by the 'W', 'S' keys and arrow keys. The ball moves and bounces off the paddles and walls. This is a starting point; you can further enhance it by adding scoring, sound effects, or improving the game mechanics.
About The Author - Janhavi Gupta
Seasoned programmer with 6 years of experience in designing, developing, and deploying software solutions. Strong problem-solving skills coupled with the ability to collaborate effectively in multidisciplinary teams. Continuously learning and adapting to new technologies and methodologies to drive innovation and deliver high-quality, user-centric solutions.