import pygame import random # Initialize Pygame pygame.init() # Constants SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 PLAYER_WIDTH = 50 PLAYER_HEIGHT = 50 ENEMY_WIDTH = 50 ENEMY_HEIGHT = 50 BULLET_WIDTH = 5 BULLET_HEIGHT = 10 WHITE = (255, 255, 255) BLACK = (0, 0, 0) PLAYER_SPEED = 5 ENEMY_SPEED = 3 BULLET_SPEED = 7 # Create the game window screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Shooting Game") clock = pygame.time.Clock() # Define the Player class class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface([PLAYER_WIDTH, PLAYER_HEIGHT]) self.image.fill(WHITE) self.rect = self.image.get_rect() self.rect.centerx = SCREEN_WIDTH // 2 self.rect.centery = SCREEN_HEIGHT - 50 def update(self): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.rect.x -= PLAYER_SPEED if keys[pygame.K_RIGHT]: self.rect.x += PLAYER_SPEED # Keep the player inside the screen if self.rect.left < 0: self.rect.left = 0 elif self.rect.right > SCREEN_WIDTH: self.rect.right = SCREEN_WIDTH # Define the Enemy class class Enemy(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface([ENEMY_WIDTH, ENEMY_HEIGHT]) self.image.fill(WHITE) self.rect = self.image.get_rect() self.rect.x = random.randint(0, SCREEN_WIDTH - ENEMY_WIDTH) self.rect.y = -ENEMY_HEIGHT def update(self): self.rect.y += ENEMY_SPEED if self.rect.top > SCREEN_HEIGHT: self.kill() # Define the Bullet class class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() self.image = pygame.Surface([BULLET_WIDTH, BULLET_HEIGHT]) self.image.fill(WHITE) self.rect = self.image.get_rect() self.rect.centerx = x self.rect.centery = y def update(self): self.rect.y -= BULLET_SPEED if self.rect.bottom < 0: self.kill() # Create sprite groups all_sprites = pygame.sprite.Group() enemies = pygame.sprite.Group() bullets = pygame.sprite.Group() # Create player player = Player() all_sprites.add(player) # Main game loop running = True 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_SPACE: bullet = Bullet(player.rect.centerx, player.rect.top) all_sprites.add(bullet) bullets.add(bullet) # Spawn enemies if random.randint(1, 100) == 1: enemy = Enemy() all_sprites.add(enemy) enemies.add(enemy) all_sprites.update() # Check for collisions for bullet in bullets: hit_enemies = pygame.sprite.spritecollide(bullet, enemies, True) for enemy in hit_enemies: bullet.kill() for enemy in enemies: if pygame.sprite.collide_rect(enemy, player): running = False screen.fill(BLACK) all_sprites.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit()