Here's a Python code for a simple top-down shooter game using Pygame. This version focuses on core mechanics and uses basic shapes for graphics, requiring no external assets.
Features:
- Player movement using WASD or arrow keys.
- Player shooting using the left mouse button.
- Bullets travel towards the mouse cursor's position.
- Enemies spawn at the screen edges and move towards the player.
- Collision detection: Bullets destroy enemies, and enemies hitting the player ends the game.
- Score tracking.
- Game over screen with a restart option.
Setup and How to Run:
- Install Pygame: If you don't have it installed, open your terminal or command prompt and run:
pip install pygame
- Save the Code: Copy the code below and save it in a file named
top_down_shooter.py (or any other .py name).
- Run from Terminal: Navigate to the directory where you saved the file in your terminal and run:
python top_down_shooter.py
The Code:
import pygame
import sys
import random
import math
# --- Pygame Initialization ---
pygame.init()
# --- Constants ---
WIDTH, HEIGHT = 800, 600
SCREEN_CENTER_X, SCREEN_CENTER_Y = WIDTH // 2, HEIGHT // 2
FPS = 60
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
GRAY = (128, 128, 128)
# Player settings
PLAYER_SIZE = 30
PLAYER_SPEED = 4
PLAYER_COLOR = WHITE
# Bullet settings
BULLET_SIZE = 8
BULLET_SPEED = 10
BULLET_COLOR = YELLOW
BULLET_COOLDOWN = 250 # milliseconds between shots
# Enemy settings
ENEMY_SIZE = 30
ENEMY_SPEED = 2
ENEMY_COLOR = RED
ENEMY_SPAWN_RATE = 700 # milliseconds between new enemies
ENEMY_MAX_ON_SCREEN = 5 # Maximum number of enemies allowed at once
# --- Game Objects ---
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
# Create a simple square surface for the player
self.image = pygame.Surface([PLAYER_SIZE, PLAYER_SIZE])
self.image.fill(PLAYER_COLOR)
# Get the rectangle for positioning and collision
self.rect = self.image.get_rect()
# Start the player in the center of the screen
self.rect.center = (SCREEN_CENTER_X, SCREEN_CENTER_Y)
self.speed = PLAYER_SPEED
self.score = 0
self.last_shot_time = 0 # To manage bullet cooldown
def move(self, dx, dy):
# Normalize movement vector to prevent faster diagonal movement
if dx != 0 and dy != 0:
distance = math.sqrt(dx**2 + dy**2)
dx /= distance
dy /= distance
# Update player position
self.rect.x += dx * self.speed
self.rect.y += dy * self.speed
# Keep player within screen bounds
self.rect.left = max(0, self.rect.left)
self.rect.right = min(WIDTH, self.rect.right)
self.rect.top = max(0, self.rect.top)
self.rect.bottom = min(HEIGHT, self.rect.bottom)
def shoot(self, mouse_pos, all_sprites_group, bullets_group):
current_time = pygame.time.get_ticks()
# Check if cooldown has passed
if current_time - self.last_shot_time > BULLET_COOLDOWN:
self.last_shot_time = current_time
# Create a new bullet instance
bullet = Bullet(self.rect.centerx, self.rect.centery, mouse_pos)
all_sprites_group.add(bullet)
bullets_group.add(bullet)
def update(self):
# Player movement is controlled by key presses, not automatic updates
pass
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, target_pos):
super().__init__()
# Create a small circle for the bullet
self.image = pygame.Surface([BULLET_SIZE, BULLET_SIZE], pygame.SRCALPHA) # SRCALPHA for transparency
pygame.draw.circle(self.image, BULLET_COLOR, (BULLET_SIZE // 2, BULLET_SIZE // 2), BULLET_SIZE // 2)
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.speed = BULLET_SPEED
# Calculate direction vector towards the target (mouse click position)
dx = target_pos[0] - x
dy = target_pos[1] - y
distance = math.sqrt(dx**2 + dy**2)
# Avoid division by zero if clicking exactly on the player
if distance == 0:
distance = 1
self.direction = (dx / distance, dy / distance)
def update(self):
# Move the bullet
self.rect.x += self.direction[0] * self.speed
self.rect.y += self.direction[1] * self.speed
# Remove the bullet if it goes off-screen
if (self.rect.bottom < 0 or self.rect.top > HEIGHT or
self.rect.right < 0 or self.rect.left > WIDTH):
self.kill() # This removes the sprite from all groups it belongs to
class Enemy(pygame.sprite.Sprite):
def __init__(self, player_rect):
super().__init__()
# Create a simple square surface for the enemy
self.image = pygame.Surface([ENEMY_SIZE, ENEMY_SIZE])
self.image.fill(ENEMY_COLOR)
self.rect = self.image.get_rect()
self.speed = ENEMY_SPEED
self.player_rect = player_rect # Reference to player's rect for targeting
# Spawn the enemy at a random edge of the screen
side = random.choice(["top", "bottom", "left", "right"])
if side == "top":
self.rect.x = random.randrange(0, WIDTH - ENEMY_SIZE)
self.rect.y = -ENEMY_SIZE # Start just above the screen
elif side == "bottom":
self.rect.x = random.randrange(0, WIDTH - ENEMY_SIZE)
self.rect.y = HEIGHT # Start just below the screen
elif side == "left":
self.rect.x = -ENEMY_SIZE # Start just left of the screen
self.rect.y = random.randrange(0, HEIGHT - ENEMY_SIZE)
elif side == "right":
self.rect.x = WIDTH # Start just right of the screen
self.rect.y = random.randrange(0, HEIGHT - ENEMY_SIZE)
def update(self):
# Calculate direction vector towards the player
dx = self.player_rect.centerx - self.rect.centerx
dy = self.player_rect.centery - self.rect.centery
distance = math.sqrt(dx**2 + dy**2)
# Avoid division by zero if player is exactly at enemy's center
if distance > 0:
dx /= distance
dy /= distance
else: # If player is at enemy's center, stop movement for this frame
dx, dy = 0, 0
# Move the enemy towards the player
self.rect.x += dx * self.speed
self.rect.y += dy * self.speed
# Optionally remove enemies if they go far off-screen (helps clean up if player dies)
if (self.rect.bottom < -ENEMY_SIZE or self.rect.top > HEIGHT + ENEMY_SIZE or
self.rect.right < -ENEMY_SIZE or self.rect.left > WIDTH + ENEMY_SIZE):
self.kill()
# --- Game Setup ---
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Top-Down Shooter")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36) # Default font, size 36
large_font = pygame.font.Font(None, 72) # Font for Game Over
# Sprite groups for efficient management
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
bullets = pygame.sprite.Group()
# Create the player instance
player = Player()
all_sprites.add(player) # Add player to the group for updating and drawing
# Game state variables
running = True
game_active = True # Game is active by default
last_enemy_spawn_time = 0 # To track when the last enemy was spawned
# --- Game Loop ---
while running:
# --- Event Handling ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False # Exit the main loop
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False # Exit on ESC key press
# If game is over, allow restarting
if not game_active:
if event.key == pygame.K_r:
# Reset game state
player.score = 0
player.rect.center = (SCREEN_CENTER_X, SCREEN_CENTER_Y)
player.last_shot_time = 0
# Clear all existing sprites and groups
all_sprites.empty()
enemies.empty()
bullets.empty()
# Re-add the player
all_sprites.add(player)
# Reset timers and activate game
last_enemy_spawn_time = 0
game_active = True
# Handle mouse clicks for shooting
elif event.type == pygame.MOUSEBUTTONDOWN:
if game_active and event.button == 1: # Check for left mouse button click
player.shoot(event.pos, all_sprites, bullets)
# --- Game Logic (only runs if game is active) ---
if game_active:
# Player Movement Control
keys = pygame.key.get_pressed()
dx, dy = 0, 0
if keys[pygame.K_w] or keys[pygame.K_UP]:
dy = -1
if keys[pygame.K_s] or keys[pygame.K_DOWN]:
dy = 1
if keys[pygame.K_a] or keys[pygame.K_LEFT]:
dx = -1
if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
dx = 1
player.move(dx, dy)
# Enemy Spawning
current_time = pygame.time.get_ticks()
if (current_time - last_enemy_spawn_time > ENEMY_SPAWN_RATE and
len(enemies) < ENEMY_MAX_ON_SCREEN):
new_enemy = Enemy(player.rect) # Pass player's rect for targeting
all_sprites.add(new_enemy)
enemies.add(new_enemy)
last_enemy_spawn_time = current_time
# Update all game objects (player, bullets, enemies)
all_sprites.update()
# --- Collision Detection ---
# Check for bullets hitting enemies
# groupcollide(group1, group2, dokill1, dokill2)
# dokill1=True means sprites in group1 that collide are removed.
# dokill2=True means sprites in group2 that collide are removed.
enemy_bullet_collisions = pygame.sprite.groupcollide(enemies, bullets, True, True)
# Increment score for each enemy destroyed
for enemy in enemy_bullet_collisions:
player.score += 1
# Check for player hitting enemies
if pygame.sprite.spritecollideany(player, enemies):
game_active = False # Player is hit, end the game
# --- Drawing ---
screen.fill(BLACK) # Fill the background with black
# Draw all sprites (this calls the .draw() method of each sprite)
all_sprites.draw(screen)
# Draw the score
score_text = font.render(f"Score: {player.score}", True, WHITE)
screen.blit(score_text, (10, 10)) # Position score at top-left
# Display Game Over screen if game is not active
if not game_active:
game_over_text = large_font.render("GAME OVER", True, WHITE)
restart_text = font.render("Press 'R' to Restart", True, WHITE)
# Center the text
game_over_rect = game_over_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 50))
restart_rect = restart_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 20))
screen.blit(game_over_text, game_over_rect)
screen.blit(restart_text, restart_rect)
# --- Update the Display ---
pygame.display.flip() # Make everything drawn visible
# --- Frame Rate Control ---
clock.tick(FPS) # Limit the loop to run at `FPS` frames per second
# --- Quit Pygame ---
pygame.quit()
sys.exit()
Explanation:
- Initialization & Constants: Sets up Pygame, defines screen dimensions, frame rate, colors, and properties like speeds and sizes for the player, bullets, and enemies.
Player Class:
- Inherits from
pygame.sprite.Sprite for easier management.
image: A pygame.Surface representing the player's appearance (a white square).
rect: A pygame.Rect object that holds the player's position and dimensions. Used for collision detection and drawing.
move(): Updates the player's rect based on input dx, dy and speed. It also clamps the player's position to stay within the screen bounds.
shoot(): Creates a Bullet instance when the mouse is clicked, calculating the direction from the player to the mouse position. It includes a cooldown mechanism.
Bullet Class:
- Also a
Sprite.
image: A small transparent surface with a yellow circle drawn on it.
rect: Position and dimensions.
direction: A normalized vector indicating the bullet's travel path.
update(): Moves the bullet based on its direction and speed. It automatically removes itself (self.kill()) if it moves off-screen.
Enemy Class:
- A
Sprite.
image: A red square.
rect: Position and dimensions.
- Spawns randomly at one of the screen's edges.
update(): Calculates a vector pointing towards the player's center and moves the enemy along that path.
- Sprite Groups:
all_sprites: A pygame.sprite.Group that holds all game objects. Calling all_sprites.update() calls the update() method for every sprite in it. Calling all_sprites.draw(screen) draws every sprite onto the screen.
enemies and bullets: Specific groups used for more targeted operations, especially collision detection.
- Game Loop: