Sure! Here's a simple implementation of the classic game Pong using Python and the pygame library:
import pygame
import random
# Initialize Pygame
pygame.init()
# Set up the game window
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pong")
# Set up colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
# Set up game objects
ball_pos = [screen_width // 2, screen_height // 2]
ball_radius = 10
ball_direction = [random.choice([-1, 1]), random.choice([-1, 1])]
ball_speed = 5
paddle_width, paddle_height = 10, 80
left_paddle_pos = [50, screen_height // 2 - paddle_height // 2]
right_paddle_pos = [screen_width - 50 - paddle_width, screen_height // 2 - paddle_height // 2]
paddle_speed = 5
# Game loop
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move paddles
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and right_paddle_pos[1] > 0:
right_paddle_pos[1] -= paddle_speed
if keys[pygame.K_DOWN] and right_paddle_pos[1] < screen_height - paddle_height:
right_paddle_pos[1] += paddle_speed
if keys[pygame.K_w] and left_paddle_pos[1] > 0:
left_paddle_pos[1] -= paddle_speed
if keys[pygame.K_s] and left_paddle_pos[1] < screen_height - paddle_height:
left_paddle_pos[1] += paddle_speed
# Move ball
ball_pos[0] += ball_direction[0] * ball_speed
ball_pos[1] += ball_direction[1] * ball_speed
# Ball collision with paddles
if ball_pos[0] <= left_paddle_pos[0] + paddle_width and left_paddle_pos[1] <= ball_pos[1] <= left_paddle_pos[1] + paddle_height:
ball_direction[0] = 1
if ball_pos[0] >= right_paddle_pos[0] - ball_radius and right_paddle_pos[1] <= ball_pos[1] <= right_paddle_pos[1] + paddle_height:
ball_direction[0] = -1
if ball_pos[1] <= 0 or ball_pos[1] >= screen_height - ball_radius:
ball_direction[1] *= -1
# Update screen
screen.fill(WHITE)
pygame.draw.line(screen, GREEN, (screen_width // 2, 0), (screen_width // 2, screen_height), 1)
pygame.draw.circle(screen, GREEN, ball_pos, ball_radius)
pygame.draw.rect(screen, GREEN, pygame.Rect(left_paddle_pos, (paddle_width, paddle_height)))
pygame.draw.rect(screen, GREEN, pygame.Rect(right_paddle_pos, (paddle_width, paddle_height)))
pygame.display.flip()
# Set frames per second
clock.tick(60)
# Quit the game
pygame.quit()
To run the code, make sure you have Pygame installed and execute the script. The game window will open, and you can control the left paddle with the 'W' and 'S' keys and the right paddle with the Up and Down arrow keys. The game ends when you close the window.
Feel free to modify and enhance the code to add features such as keeping score or adding sound effects!