python pong.py
import pygame
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
FPS = 60
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Paddle properties
PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100
PADDLE_SPEED = 7
# Ball properties
BALL_SIZE = 15
BALL_SPEED_X, BALL_SPEED_Y = 7, 7
# Set up display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong Game")
# Clock to control the frame rate
clock = pygame.time.Clock()
def draw_paddle(x, y):
pygame.draw.rect(screen, WHITE, (x, y, PADDLE_WIDTH, PADDLE_HEIGHT))
def draw_ball(x, y):
pygame.draw.ellipse(screen, WHITE, (x, y, BALL_SIZE, BALL_SIZE))
def main():
# Paddle positions
player_x, player_y = 20, HEIGHT // 2 - PADDLE_HEIGHT // 2
opponent_x, opponent_y = WIDTH - 30, HEIGHT // 2 - PADDLE_HEIGHT // 2
# Ball position and movement
ball_x, ball_y = WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2
ball_dx, ball_dy = BALL_SPEED_X, BALL_SPEED_Y
# Score
player_score, opponent_score = 0, 0
while True:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Get keys
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and player_y > 0:
player_y -= PADDLE_SPEED
if keys[pygame.K_s] and player_y < HEIGHT - PADDLE_HEIGHT:
player_y += PADDLE_SPEED
if keys[pygame.K_UP] and opponent_y > 0:
opponent_y -= PADDLE_SPEED
if keys[pygame.K_DOWN] and opponent_y < HEIGHT - PADDLE_HEIGHT:
opponent_y += PADDLE_SPEED
# Move ball
ball_x += ball_dx
ball_y += ball_dy
# Ball collision with top and bottom
if ball_y <= 0 or ball_y >= HEIGHT - BALL_SIZE:
ball_dy *= -1
# Ball collision with paddles
if (ball_x <= player_x + PADDLE_WIDTH and
player_y <= ball_y + BALL_SIZE and
ball_y <= player_y + PADDLE_HEIGHT):
ball_dx *= -1
if (ball_x >= opponent_x - BALL_SIZE and
opponent_y <= ball_y + BALL_SIZE and
ball_y <= opponent_y + PADDLE_HEIGHT):
ball_dx *= -1
# Scoring
if ball_x < 0:
opponent_score += 1
ball_x, ball_y = WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2
ball_dx *= -1
if ball_x > WIDTH:
player_score += 1
ball_x, ball_y = WIDTH // 2 - BALL_SIZE // 2, HEIGHT // 2 - BALL_SIZE // 2
ball_dx *= -1
# Clear screen
screen.fill(BLACK)
# Draw paddles and ball
draw_paddle(player_x, player_y)
draw_paddle(opponent_x, opponent_y)
draw_ball(ball_x, ball_y)
# Display score
font = pygame.font.SysFont(None, 36)
text = font.render(f'{player_score} - {opponent_score}', True, WHITE)
screen.blit(text, (WIDTH // 2 - text.get_width() // 2, 20))
# Update display
pygame.display.flip()
# Cap the frame rate
clock.tick(FPS)
if __name__ == "__main__":
main()