import pygame import sys # Initialize Pygame pygame.init() # Screen dimensions WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Ping Pong with Main Menu") # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) GRAY = (100, 100, 100) # Fonts font = pygame.font.SysFont(None, 50) # Define paddles and ball paddle_width, paddle_height = 10, 100 ball_size = 20 # Main menu function def main_menu(): while True: screen.fill(BLACK) title_text = font.render("Ping Pong Main Menu", True, WHITE) start_text = font.render("Press ENTER to Start", True, GRAY) quit_text = font.render("Press Q to Quit", True, GRAY) screen.blit(title_text, (WIDTH//2 - title_text.get_width()//2, HEIGHT//3)) screen.blit(start_text, (WIDTH//2 - start_text.get_width()//2, HEIGHT//3 + 60)) screen.blit(quit_text, (WIDTH//2 - quit_text.get_width()//2, HEIGHT//3 + 120)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: game_loop() elif event.key == pygame.K_q: pygame.quit() sys.exit() # Main game loop def game_loop(): # Initial positions left_paddle = pygame.Rect(10, HEIGHT//2 - paddle_height//2, paddle_width, paddle_height) right_paddle = pygame.Rect(WIDTH - 20, HEIGHT//2 - paddle_height//2, paddle_width, paddle_height) ball = pygame.Rect(WIDTH//2 - ball_size//2, HEIGHT//2 - ball_size//2, ball_size, ball_size) ball_speed = [4, 4] paddle_speed = 5 clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Keys pressed keys = pygame.key.get_pressed() # Left paddle controls (W/S) if keys[pygame.K_w] and left_paddle.top > 0: left_paddle.y -= paddle_speed if keys[pygame.K_s] and left_paddle.bottom < HEIGHT: left_paddle.y += paddle_speed # Right paddle controls (UP/DOWN) if keys[pygame.K_UP] and right_paddle.top > 0: right_paddle.y -= paddle_speed if keys[pygame.K_DOWN] and right_paddle.bottom < HEIGHT: right_paddle.y += paddle_speed # Move ball ball.x += ball_speed[0] ball.y += ball_speed[1] # Collisions with top/bottom if ball.top <= 0 or ball.bottom >= HEIGHT: ball_speed[1] = -ball_speed[1] # Collisions with paddles if ball.colliderect(left_paddle) and ball_speed[0] < 0: ball_speed[0] = -ball_speed[0] if ball.colliderect(right_paddle) and ball_speed[0] > 0: ball_speed[0] = -ball_speed[0] # Check for scoring if ball.left <= 0: # Right player scores ball.center = (WIDTH//2, HEIGHT//2) ball_speed = [4, 4] elif ball.right >= WIDTH: # Left player scores ball.center = (WIDTH//2, HEIGHT//2) ball_speed = [-4, 4] # Drawing screen.fill(BLACK) pygame.draw.rect(screen, WHITE, left_paddle) pygame.draw.rect(screen, WHITE, right_paddle) pygame.draw.ellipse(screen, WHITE, ball) pygame.draw.aaline(screen, WHITE, (WIDTH//2, 0), (WIDTH//2, HEIGHT)) pygame.display.flip() clock.tick(60) # Run the main menu main_menu()