Okay, let's create a simple top-down shooter using Pygame with minimal setup – no external assets needed, just shapes and colors!
This game will feature:
A player that can move with WASD/Arrow keys.
The player can shoot bullets.
Enemies that spawn randomly and move towards the player.
Collision detection for bullets hitting enemies, and enemies hitting the player.
A basic score system.
A "Game Over" screen.
How to run:
Make sure you have Pygame installed (pip install pygame).
Save the code below as a .py file (e.g., shooter.py).
Run it from your terminal: python shooter.py
python
import pygame
import sys
import random
import math
# --- Constants ---
WIDTH, HEIGHT = 800, 600
FPS = 60
# Colors (R, G, B)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GREY = (100, 100, 100)
# Game settings
PLAYER_SPEED = 5
BULLET_SPEED = 10
ENEMY_SPEED = 2
ENEMY_SPAWN_RATE = 1000 # milliseconds between enemy spawns
BULLET_FIRE_RATE = 200 # milliseconds between bullet shots
# --- Initialize Pygame ---
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Minimal Top-Down Shooter")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 40) # Default font, size 40
# --- Game Classes ---
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([30, 30]) # A simple square
self.image.fill(BLUE)
self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2))
self.speed = PLAYER_SPEED
self.last_shot_time = 0
def update(self):
keys = pygame.key.get_pressed()
dx, dy = 0, 0
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
dx = -self.speed
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
dx = self.speed
if keys[pygame.K_UP] or keys[pygame.K_w]:
dy = -self.speed
if keys[pygame.K_DOWN] or keys[pygame.K_s]:
dy = self.speed
# Normalize diagonal movement (optional, but makes diagonal speed same as cardinal)
if dx != 0 and dy != 0:
factor = self.speed / math.sqrt(dx**2 + dy**2)
dx *= factor
dy *= factor
self.rect.x += dx
self.rect.y += dy
# 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, current_time):
if current_time - self.last_shot_time > BULLET_FIRE_RATE:
self.last_shot_time = current_time
# Bullet fires from player's center upwards (can be changed to mouse pos later)
return Bullet(self.rect.centerx, self.rect.top)
return None
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([8, 15]) # A small rectangle
self.image.fill(YELLOW)
self.rect = self.image.get_rect(center=(x, y))
self.speed = BULLET_SPEED
def update(self):
self.rect.y -= self.speed # Move upwards
# Remove bullet if it goes off screen
if self.rect.bottom < 0:
self.kill() # Removes sprite from all groups
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([25, 25]) # A simple square enemy
self.image.fill(RED)
# Spawn enemies randomly at the edges of the screen
side = random.choice(['top', 'bottom', 'left', 'right'])
if side == 'top':
x = random.randint(0, WIDTH)
y = -self.image.get_height()
elif side == 'bottom':
x = random.randint(0, WIDTH)
y = HEIGHT + self.image.get_height()
elif side == 'left':
x = -self.image.get_width()
y = random.randint(0, HEIGHT)
else: # right
x = WIDTH + self.image.get_width()
y = random.randint(0, HEIGHT)
self.rect = self.image.get_rect(center=(x, y))
self.speed = ENEMY_SPEED
def update(self, player_pos):
# Move towards the player
dx = player_pos[0] - self.rect.centerx
dy = player_pos[1] - self.rect.centery
dist = math.sqrt(dx**2 + dy**2)
if dist > 0:
self.rect.x += (dx / dist) * self.speed
self.rect.y += (dy / dist) * self.speed
# Optionally, remove enemies that somehow go off screen
if not screen.get_rect().colliderect(self.rect) and self.rect.top > HEIGHT: # If it went past bottom
self.kill() # Remove if it went entirely off the bottom, adjust for other sides if needed
# --- Game Initialization ---
def reset_game():
global player, all_sprites, bullets, enemies, score, game_over, last_enemy_spawn_time
player = Player()
all_sprites = pygame.sprite.Group()
bullets = pygame.sprite.Group()
enemies = pygame.sprite.Group()
all_sprites.add(player)
score = 0
game_over = False
last_enemy_spawn_time = pygame.time.get_ticks()
reset_game() # Initial setup
# --- Game Loop ---
running = True
while running:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if game_over: # Restart game if game over
reset_game()
else: # Shoot if game is active
new_bullet = player.shoot(current_time)
if new_bullet:
all_sprites.add(new_bullet)
bullets.add(new_bullet)
if not game_over:
# Spawn enemies
if current_time - last_enemy_spawn_time > ENEMY_SPAWN_RATE:
new_enemy = Enemy()
all_sprites.add(new_enemy)
enemies.add(new_enemy)
last_enemy_spawn_time = current_time
# Update all sprites
all_sprites.update(player.rect.center) # Pass player position for enemy targeting
# Collision: Bullets vs. Enemies
# pygame.sprite.groupcollide(group1, group2, dokill1, dokill2)
# dokill1, dokill2: True means sprites will be removed from their groups after collision
hits = pygame.sprite.groupcollide(bullets, enemies, True, True)
for bullet, enemy_list in hits.items():
for enemy in enemy_list:
score += 10 # Increase score for each enemy hit
# Collision: Player vs. Enemies
# pygame.sprite.spritecollide(sprite, group, dokill)
player_hits_enemies = pygame.sprite.spritecollide(player, enemies, True) # Enemies disappear on hit
if player_hits_enemies:
game_over = True # End game if player is hit
# --- Drawing ---
screen.fill(BLACK) # Clear screen with black background
all_sprites.draw(screen) # Draw all sprites in their groups
# Display Score
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
# Game Over screen
if game_over:
game_over_text = font.render("GAME OVER!", True, RED)
restart_text = font.render("Press SPACE to restart", True, WHITE)
# Center the text
game_over_rect = game_over_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 30))
restart_rect = restart_text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 30))
screen.blit(game_over_text, game_over_rect)
screen.blit(restart_text, restart_rect)
# --- Update Display ---
pygame.display.flip()
# --- Cap FPS ---
clock.tick(FPS)
# --- Quit Pygame ---
pygame.quit()
sys.exit()
Explanation of Key Parts:
Constants & Initialization: Sets up screen dimensions, colors, speeds, and initializes Pygame.
Player Class:
__init__: Creates a blue square (pygame.Surface) for the player.
update: Handles movement based on WASD/arrow keys. It also clamps the player's position to keep it within the screen. Diagonal movement is normalized so it's not faster.
shoot: Creates a Bullet object. Includes a BULLET_FIRE_RATE to prevent constant firing by holding down space.
Bullet Class:
__init__: Creates a small yellow rectangle.
update: Moves the bullet upwards. self.kill() removes it from all sprite groups if it goes off-screen, making it eligible for garbage collection.
Enemy Class:
__init__: Creates a red square. It randomly decides which edge of the screen to spawn from.
update: Calculates the direction vector from the enemy to the player (dx, dy), normalizes it, and then moves the enemy self.speed units in that direction. This makes enemies chase the player.
Sprite Groups:
all_sprites: Contains every active game object for easy drawing and updating.
bullets: Contains only bullet objects for collision detection with enemies.
enemies: Contains only enemy objects for collision detection with bullets and the player.
reset_game() Function: Encapsulates the logic for setting up a fresh game state (player position, empty lists for bullets/enemies, score reset). This is called at the start and when restarting.
Game Loop (while running):
Event Handling: Checks for quitting the game (pygame.QUIT) or key presses (WASD/arrows for movement, SPACE for shooting/restarting).
Game Logic (if not game_over):
Enemy Spawning: Uses pygame.time.get_ticks() to spawn enemies at regular intervals.
Sprite Updates: Calls update() on all sprites in the group.
This provides a solid foundation for a top-down shooter. You can expand it by adding:
pygame.sprite.groupcollide(bullets, enemies, True, True): Checks for collisions between every bullet and every enemy. True, True means both the bullet and the enemy involved in a collision are automatically removed from their groups (and thus from all_sprites since they are part of it).
pygame.sprite.spritecollide(player, enemies, True): Checks if the player sprite collides with any enemies. True means the enemy hit will be removed. If any collision occurs, game_over is set to True.
Drawing: Fills the background, then draws all sprites. Displays the score and the "GAME OVER" message if game_over is True.
Display Update:pygame.display.flip() updates the entire screen.
FPS Cap:clock.tick(FPS) limits the game to the specified frames per second, ensuring consistent speed across different computers.