Write a Python program to create a Space Invaders game using the Pygame library.
- User
Write a Python program to create a Space Invaders game using the Pygame library.
- Assistant
Creating a full Space Invaders game involves several components, including setting up the game window, loading graphics, handling player input, controlling enemy movement, and detecting collisions. Below is a simplified version of a Space Invaders game using the Pygame library. Make sure to install Pygame first if you haven't already:
bashpip install pygameHere's a basic implementation:
pythonimport pygame import sys import random # Initialize Pygame pygame.init() # Screen dimensions SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600 BACKGROUND_COLOR = (0, 0, 0) # Player settings player_speed = 5 laser_speed = 10 # Enemy settings enemy_speed = 2 num_enemies = 10 # Load images player_image = pygame.image.load("player.png").convert_alpha() enemy_image = pygame.image.load("enemy.png").convert_alpha() laser_image = pygame.image.load("laser.png").convert_alpha() # Set player and enemy starting positions player_pos = [SCREEN_WIDTH // 2, SCREEN_HEIGHT - 50] enemies_pos = [[random.randint(0, SCREEN_WIDTH - enemy_image.get_width()), 50] for _ in range(num_enemies)] # Game loop running = True clock = pygame.time.Clock() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player_pos[0] -= player_speed elif event.key == pygame.K_RIGHT: player_pos[0] += player_speed elif event.key == pygame.K_SPACE: # Shoot laser laser_pos = [player_pos[0], player_pos[1] - 30] lasers.append(laser_pos) # Move player keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and player_pos[0] > 0: player_pos[0] -= player_speed if keys[pygame.K_RIGHT] and player_pos[0] < SCREEN_WIDTH - player_image.get_width(): player_pos[0] += player_speed # Move enemies for i in range(num_enemies): enemies_pos[i][1] += enemy_speed if enemies_pos[i][1] > SCREEN_HEIGHT: running = False # Game over if enemies reach the bottom # Draw background screen.fill(BACKGROUND_COLOR) # Draw player screen.blit(player_image, player_pos) # Draw enemies for pos in enemies_pos: screen.blit(enemy_image, pos) # Draw lasers for laser_pos in lasers: screen.blit(laser_image, laser_pos) # Update display pygame.display.flip() clock.tick(60) pygame.quit() sys.exit() - User
Here are the filenames of all the necessary images: laser.png, Feindliches Raumschiff.png and Raumschiff V.3.png
- Assistant
Great! With the filenames you've provided, you can adjust the code I gave earlier to load the correct images for the player, enemies, and lasers. Here's how you can do it:
python