To add a main menu with options to play the game, select difficulty, and exit, we need to create a simple menu system. We'll use Pygame's event handling and rendering capabilities to display and navigate the menu. Here's how you can implement it:
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2D Shooter Game")
# Colors
PLAYER_COLOR = (0, 255, 0) # Green
ENEMY_COLOR = (255, 0, 0) # Red
BULLET_COLOR = (255, 255, 0) # Yellow
BACKGROUND_COLOR = (0, 0, 0) # Black
TEXT_COLOR = (255, 255, 255) # White
# Player variables
player_width, player_height = 50, 10
player_x = WIDTH // 2 - player_width // 2
player_y = HEIGHT - player_height - 10
player_speed = 5
lives = 3
# Bullet variables
bullet_width, bullet_height = 5, 10
bullet_speed = 7
bullets = []
# Enemy variables
enemy_width, enemy_height = 50, 50
enemy_speed = 2
enemies = []
# Game variables
score = 0
game_over = False
paused = False
high_score = 0
difficulty = 'Easy'
# Font
font = pygame.font.SysFont(None, 36)
# Frame rate
clock = pygame.time.Clock()
FPS = 60
def draw_player():
pygame.draw.rect(screen, PLAYER_COLOR, (player_x, player_y, player_width, player_height))
def draw_bullets():
for bullet in bullets:
pygame.draw.rect(screen, BULLET_COLOR, bullet)
def draw_enemies():
for enemy in enemies:
pygame.draw.rect(screen, ENEMY_COLOR, enemy)
def draw_score():
score_text = font.render(f"Score: {score} Lives: {lives} High Score: {high_score}", True, TEXT_COLOR)
screen.blit(score_text, (10, 10))
def spawn_enemy():
x = random.randint(0, WIDTH - enemy_width)
enemy = pygame.Rect(x, 0, enemy_width, enemy_height)
enemies.append(enemy)
def main_menu():
global difficulty
menu = True
selected_option = 0
options = ["Play", "Difficulty: Easy", "Exit"]
while menu:
screen.fill(BACKGROUND_COLOR)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
selected_option = (selected_option - 1) % len(options)
if event.key == pygame.K_DOWN:
selected_option = (selected_option + 1) % len(options)
if event.key == pygame.K_RETURN:
if selected_option == 0: # Play
menu = False
elif selected_option == 1: # Difficulty
if difficulty == 'Easy':
difficulty = 'Hard'
options[1] = "Difficulty: Hard"
else:
difficulty = 'Easy'
options[1] = "Difficulty: Easy"
elif selected_option == 2: # Exit
pygame.quit()
exit()
for i, option in enumerate(options):
color = TEXT_COLOR if i != selected_option else (255, 255, 0)
text = font.render(option, True, color)
screen.blit(text, (WIDTH // 2 - text.get_width() // 2, HEIGHT // 2 + i * 40))
pygame.display.flip()
clock.tick(FPS)
def main():
global player_x, score, game_over, lives, high_score, paused, enemy_speed
if difficulty == 'Hard':
enemy_speed = 4
else:
enemy_speed = 2
spawn_event = pygame.USEREVENT + 1
pygame.time.set_timer(spawn_event, 1000)
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == spawn_event and not paused:
spawn_enemy()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not paused:
bullet = pygame.Rect(player_x + player_width // 2 - bullet_width // 2, player_y, bullet_width, bullet_height)
bullets.append(bullet)
if event.key == pygame.K_p:
paused = not paused
if event.key == pygame.K_r and game_over:
main()
if not paused:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
player_x -= player_speed
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
player_x += player_speed
player_x = max(0, min(WIDTH - player_width, player_x))
for bullet in bullets[:]:
bullet.y -= bullet_speed
if bullet.y < 0:
bullets.remove(bullet)
for enemy in enemies[:]:
enemy.y += enemy_speed
if enemy.y > HEIGHT:
enemies.remove(enemy)
lives -= 1
if lives <= 0:
game_over = True
for bullet in bullets[:]:
if enemy.colliderect(bullet):
enemies.remove(enemy)
bullets.remove(bullet)
score += 1
if score > high_score:
high_score = score
screen.fill(BACKGROUND_COLOR)
draw_player()
draw_bullets()
draw_enemies()
draw_score()
pygame.display.flip()
clock.tick(FPS)
print(f"Game Over! Your final score was: {score}")
pygame.quit()
if __name__ == "__main__":
main_menu()
main()
Key Features:
- Main Menu: A simple menu with options to play the game, change difficulty, and exit.
- Difficulty Setting: Toggle between "Easy" and "Hard" difficulty, which affects the speed of the enemies.
- Navigation: Use the up and down arrow keys to navigate the menu and the Enter key to select an option.
This script provides a basic menu system and allows you to adjust the difficulty of the game. The game starts after selecting "Play" from the menu, and you can exit the game from the menu as well.