Project: "Space Invader Clone" – A Simple 2D Shooter Game in Python
Overview: The project is a basic 2D space shooter game inspired by the classic Space Invaders. Using Python and the Pygame library, the game will allow players to control a spaceship at the bottom of the screen, shooting at alien invaders falling from the top. The goal is to eliminate all the aliens while avoiding their projectiles. The game will feature simple mechanics, including shooting, moving left and right, and dodging enemy attacks.
Key Features: Player Movement:
The player controls a spaceship at the bottom of the screen that can move left and right using the keyboard (e.g., arrow keys or 'A' and 'D'). Shooting Mechanism:
The player can shoot bullets upwards to destroy enemies by pressing a key (e.g., spacebar). The bullets travel vertically until they hit an alien or move off the screen. Enemy Movement:
Aliens move horizontally across the screen. When they reach the edge, they drop down and reverse direction, gradually getting closer to the player's spaceship. Collisions:
The game detects collisions between player bullets and aliens as well as between alien bullets and the player's spaceship. Game Over and Scoring:
The game ends when the player’s spaceship is hit by an alien's projectile or if the aliens reach the bottom of the screen. The player earns points by destroying aliens, and the score is displayed at the top of the screen. Levels of Difficulty:
def update(self): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.rect.x -= self.speed if keys[pygame.K_RIGHT]: self.rect.x += self.speed if self.rect.left screen_width or self.rect.left < 0: self.rect.y += 20 self.rect.x *= -1
class Bullet(pygame.sprite.Sprite): def __init__(self, x, y, direction): super().__init__() self.image = pygame.Surface((5, 10)) self.image.fill(WHITE) self.rect = self.image.get_rect() self.rect.center = (x, y) self.direction = direction
def update(self): if self.direction == "up": self.rect.y -= 10 elif self.direction == "down": self.rect.y += 10 if self.rect.bottom screen_height: self.kill()
# Initialize game objects player = Player() all_sprites = pygame.sprite.Group() all_sprites.add(player)
aliens = pygame.sprite.Group() for i in range(5): for j in range(5): alien = Alien(100 + i*60, 50 + j*50) aliens.add(alien) all_sprites.add(alien)
# Main Game Loop running = True while running: clock.tick(60) # 60 FPS for event in pygame.event.get(): if event.type == pygame.QUIT: running = False
# Update game objects all_sprites.update()
# Check for bullet-alien collisions for bullet in all_sprites: if isinstance(bullet, Bullet): if pygame.sprite.spritecollide(bullet, aliens, True): bullet.kill() # Destroy bullet and alien score += 10