Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a single-file Pong game #9

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions pong_game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import pygame
from pygame.locals import *

# Initialize Pygame
pygame.init()

# Set up screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# Define game paddles and ball
LEFT_PADDLE = pygame.Rect(20, 20, 10, 100)
RIGHT_PADDLE = pygame.Rect(SCREEN_WIDTH - 30, 20, 10, 100)
BALL = pygame.Rect(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, 15, 15)

# Game window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# Colors
WHITE = (255, 255, 255)

# Game loop
running = True
while running:
# Handle user events
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.key == K_r:
reset_game()

# Update game logic
# Paddle movement
keys = pygame.key.get_pressed()
if keys[K_w]:
LEFT_PADDLE.move_ip(0, -5)
if keys[K_s]:
LEFT_PADDLE.move_ip(0, 5)
if keys[K_UP]:
RIGHT_PADDLE.move_ip(0, -5)
if keys[K_DOWN]:
RIGHT_PADDLE.move_ip(0, 5)

# Collision detection
LEFT_PADDLE.clamp_ip(screen.get_rect())
RIGHT_PADDLE.clamp_ip(screen.get_rect())

# Ball movement and scoring
BALL.move_ip(2, 2)
if BALL.colliderect(LEFT_PADDLE) or BALL.colliderect(RIGHT_PADDLE):
BALL.x *= -1
elif BALL.x <= 0 or BALL.x >= SCREEN_WIDTH - 15:
update_score()
reset_ball()
check_end_game_conditions()
screen.fill(0)
pygame.draw.rect(screen, WHITE, LEFT_PADDLE)
pygame.draw.rect(screen, WHITE, RIGHT_PADDLE)
pygame.draw.rect(screen, WHITE, BALL)
display_score()
pygame.display.flip()

# Clean up
pygame.quit()