import pygame import sys import random # Constants WIDTH = 800 HEIGHT = 600 BALL_RADIUS = 10 PADDLE_WIDTH = 10 PADDLE_HEIGHT = 100 PADDLE_SPEED = 7 BALL_SPEED_X = 7 BALL_SPEED_Y = 7 WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Initialize Pygame pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Pong") # Paddle 1 paddle1 = pygame.Rect(50, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT) # Paddle 2 paddle2 = pygame.Rect(WIDTH - 50 - PADDLE_WIDTH, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT) # Ball ball = pygame.Rect(WIDTH // 2 - BALL_RADIUS // 2, HEIGHT // 2 - BALL_RADIUS // 2, BALL_RADIUS, BALL_RADIUS) # Ball movement ball_speed_x = BALL_SPEED_X ball_speed_y = BALL_SPEED_Y # Scores score_paddle1 = 0 score_paddle2 = 0 # Fonts font = pygame.font.Font(None, 36) def update_ball(): global ball_speed_x, ball_speed_y, score_paddle1, score_paddle2 # Collision with paddles if ball.colliderect(paddle1) or ball.colliderect(paddle2): ball_speed_x *= -1 # Collision with top and bottom boundaries if ball.top <= 0 or ball.bottom >= HEIGHT: ball_speed_y *= -1 # Collision with left and right boundaries (scores) if ball.left <= 0: score_paddle2 += 1 if score_paddle2 >= 3: game_over("Player 2") ball_restart() elif ball.right >= WIDTH: score_paddle1 += 1 if score_paddle1 >= 3: game_over("Player 1") ball_restart() # Update ball position ball.x += ball_speed_x ball.y += ball_speed_y def ball_restart(): global ball_speed_x, ball_speed_y ball.center = (WIDTH // 2, HEIGHT // 2) ball_speed_x *= random.choice((1, -1)) ball_speed_y *= random.choice((1, -1)) def draw(): screen.fill(BLACK) pygame.draw.rect(screen, WHITE, paddle1) pygame.draw.rect(screen, WHITE, paddle2) pygame.draw.ellipse(screen, WHITE, ball) # Draw scores score_text = font.render(f"{score_paddle1} - {score_paddle2}", True, WHITE) screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, 20)) pygame.display.flip() def move_paddle(paddle, direction): if direction == "up" and paddle.top > 0: paddle.y -= PADDLE_SPEED elif direction == "down" and paddle.bottom < HEIGHT: paddle.y += PADDLE_SPEED def game_over(winner): print(f"Game Over! {winner} wins!") pygame.quit() sys.exit() # Main game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False keys = pygame.key.get_pressed() if keys[pygame.K_w]: move_paddle(paddle1, "up") if keys[pygame.K_s]: move_paddle(paddle1, "down") if keys[pygame.K_UP]: move_paddle(paddle2, "up") if keys[pygame.K_DOWN]: move_paddle(paddle2, "down") update_ball() draw() pygame.time.Clock().tick(60) pygame.quit() sys.exit()