Untitled
import pygame import sys # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 800, 600 WHITE = (255, 255, 255) BLACK = (0, 0, 0) PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100 BALL_SIZE = 15 PADDLE_SPEED = 7 BALL_SPEED_X, BALL_SPEED_Y = 5, 5 # Set up the display screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Ping Pong Game") # Paddle and Ball positions paddle_left = pygame.Rect(30, (HEIGHT - PADDLE_HEIGHT) // 2, PADDLE_WIDTH, PADDLE_HEIGHT) paddle_right = pygame.Rect(WIDTH - 40, (HEIGHT - PADDLE_HEIGHT) // 2, PADDLE_WIDTH, PADDLE_HEIGHT) ball = pygame.Rect(WIDTH // 2, HEIGHT // 2, BALL_SIZE, BALL_SIZE) # Game loop clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Get keys pressed keys = pygame.key.get_pressed() if keys[pygame.K_w] and paddle_left.top > 0: paddle_left.y -= PADDLE_SPEED if keys[pygame.K_s] and paddle_left.bottom < HEIGHT: paddle_left.y += PADDLE_SPEED if keys[pygame.K_UP] and paddle_right.top > 0: paddle_right.y -= PADDLE_SPEED if keys[pygame.K_DOWN] and paddle_right.bottom < HEIGHT: paddle_right.y += PADDLE_SPEED # Move the ball ball.x += BALL_SPEED_X ball.y += BALL_SPEED_Y # Ball collision with top and bottom if ball.top <= 0 or ball.bottom >= HEIGHT: BALL_SPEED_Y = -BALL_SPEED_Y # Ball collision with paddles if ball.colliderect(paddle_left) or ball.colliderect(paddle_right): BALL_SPEED_X = -BALL_SPEED_X # Ball reset if it goes out of bounds if ball.left <= 0 or ball.right >= WIDTH: ball.x = WIDTH // 2 ball.y = HEIGHT // 2 BALL_SPEED_X = -BALL_SPEED_X # Change direction # Fill the screen with black screen.fill(BLACK) # Draw paddles and ball pygame.draw.rect(screen, WHITE, paddle_left) pygame.draw.rect(screen, WHITE, paddle_right) pygame.draw.ellipse(screen, WHITE, ball) # Update the display pygame.display.flip() clock.tick(60) # Limit to 60 frames per second
Leave a Comment