import pygame import sys import random # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 800, 600 FPS = 60 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Player player_width, player_height = 50, 50 player_x = WIDTH // 2 - player_width // 2 player_y = HEIGHT - player_height - 20 player_speed = 8 # Bullet bullet_width, bullet_height = 5, 15 bullet_speed = 10 bullet_state = "ready" # "ready" or "fire" bullet_x, bullet_y = 0, 0 # Enemy enemy_width, enemy_height = 50, 50 enemy_speed = 2 num_enemies = 5 enemies = [] for _ in range(num_enemies): enemy_x = random.randint(0, WIDTH - enemy_width) enemy_y = random.randint(50, 200) enemies.append([enemy_x, enemy_y]) # Set up the display screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Space Invaders") clock = pygame.time.Clock() def draw_player(x, y): pygame.draw.rect(screen, WHITE, [x, y, player_width, player_height]) def draw_bullet(x, y): pygame.draw.rect(screen, WHITE, [x, y, bullet_width, bullet_height]) def draw_enemy(x, y): pygame.draw.rect(screen, WHITE, [x, y, enemy_width, enemy_height]) def is_collision(enemy_x, enemy_y, bullet_x, bullet_y): distance = ((enemy_x - bullet_x)**2 + (enemy_y - bullet_y)**2)**0.5 return distance < 27 def main(): global player_x, bullet_x, bullet_y, bullet_state, bullet_speed, enemies while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and player_x > 0: player_x -= player_speed if keys[pygame.K_RIGHT] and player_x < WIDTH - player_width: player_x += player_speed if keys[pygame.K_SPACE] and bullet_state == "ready": bullet_state = "fire" bullet_x = player_x + player_width // 2 - bullet_width // 2 bullet_y = player_y # Move the bullet if bullet_state == "fire": bullet_y -= bullet_speed if bullet_y < 0: bullet_state = "ready" # Move the enemies for enemy in enemies: enemy[1] += enemy_speed if enemy[1] > HEIGHT: enemy[0] = random.randint(0, WIDTH - enemy_width) enemy[1] = random.randint(50, 200) # Check for collisions with bullet if is_collision(enemy[0], enemy[1], bullet_x, bullet_y): bullet_state = "ready" bullet_y = player_y enemy[0] = random.randint(0, WIDTH - enemy_width) enemy[1] = random.randint(50, 200) # Draw everything screen.fill(BLACK) draw_player(player_x, player_y) draw_bullet(bullet_x, bullet_y) for enemy in enemies: draw_enemy(enemy[0], enemy[1]) # Update the display pygame.display.update() # Control the frame rate clock.tick(FPS) if __name__ == "__main__": main()