Okay, here is an enhanced version of the minimal top-down shooter, incorporating the requested features: power-ups (cooldown, shots, size, homing), automatic shooting, dynamic enemy spawn rate, and fullscreen toggle.
This is a single, complete Python script using Pygame.
import pygame
import math
import random
import time # Using time for power-up duration
# Initialize Pygame
pygame.init()
# Screen settings
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Enhanced Minimal Top-Down Shooter")
# Store original window size for toggling
original_screen_size = (SCREEN_WIDTH, SCREEN_HEIGHT)
is_fullscreen = False
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0) # Power-up: Cooldown
YELLOW = (255, 255, 0) # Power-up: Shots
CYAN = (0, 255, 255) # Power-up: Size
MAGENTA = (255, 0, 255) # Power-up: Homing
# Clock for frame rate
clock = pygame.time.Clock()
# --- Constants ---
# Player
PLAYER_SPEED = 5
PLAYER_RADIUS = 20
PLAYER_BASE_COOLDOWN_MS = 300 # Milliseconds between shots
# Bullet
BULLET_BASE_SPEED = 10
BULLET_BASE_RADIUS = 5
# Enemy
ENEMY_BASE_SPEED = 2
ENEMY_WIDTH = 20
ENEMY_HEIGHT = 20
ENEMY_BASE_SPAWN_DELAY_FRAMES = 90 # Initial delay in frames
ENEMY_MIN_SPAWN_DELAY_FRAMES = 15 # Minimum delay
ENEMY_SPAWN_SCORE_SCALE = 0.1 # How much score reduces spawn delay (delay reduces by 1 frame per 1/SCALE score)
# Power-ups
POWERUP_SIZE = 15
POWERUP_SPAWN_CHANCE_PER_FRAME = 0.001 # Chance per frame to spawn a power-up
POWERUP_DURATION_SECONDS = 10
POWERUP_COOLDOWN_MULTIPLIER = 0.8 # Shots are 20% faster
POWERUP_SHOTS_INCREASE = 1
POWERUP_SIZE_MULTIPLIER = 1.5
POWERUP_HOMING_TOGGLE = True # Homing is just on/off
# Power-up types (using strings for simplicity)
POWERUP_TYPE_COOLDOWN = "cooldown"
POWERUP_TYPE_SHOTS = "shots"
POWERUP_TYPE_SIZE = "size"
POWERUP_TYPE_HOMING = "homing"
POWERUP_TYPES = [POWERUP_TYPE_COOLDOWN, POWERUP_TYPE_SHOTS, POWERUP_TYPE_SIZE, POWERUP_TYPE_HOMING]
# --- Classes ---
class Player:
def __init__(self):
self.x = SCREEN_WIDTH // 2
self.y = SCREEN_HEIGHT // 2
self.radius = PLAYER_RADIUS
self.speed = PLAYER_SPEED
# Shooting attributes
self.base_cooldown = PLAYER_BASE_COOLDOWN_MS
self.shot_timer = 0 # Time since last shot in ms
# Power-up effects (multipliers/additions)
self.cooldown_multiplier = 1.0
self.num_shooters = 1
self.bullet_size_multiplier = 1.0
self.is_homing_bullets = False
# Power-up effect timers (end time in seconds)
self.effect_end_times = {
POWERUP_TYPE_COOLDOWN: 0,
POWERUP_TYPE_SHOTS: 0,
POWERUP_TYPE_SIZE: 0,
POWERUP_TYPE_HOMING: 0,
}
def move(self, keys):
if keys[pygame.K_w] and self.y - self.radius > 0:
self.y -= self.speed
if keys[pygame.K_s] and self.y + self.radius < SCREEN_HEIGHT:
self.y += self.speed
if keys[pygame.K_a] and self.x - self.radius > 0:
self.x -= self.speed
if keys[pygame.K_d] and self.x + self.radius < SCREEN_WIDTH:
self.x += self.speed
def can_shoot(self):
current_cooldown = self.base_cooldown * self.cooldown_multiplier
return pygame.time.get_ticks() - self.shot_timer >= current_cooldown
def shoot(self, mouse_pos, enemies):
if self.can_shoot():
self.shot_timer = pygame.time.get_ticks()
bullets_fired = []
target_x, target_y = mouse_pos
# Calculate direction vector
dx = target_x - self.x
dy = target_y - self.y
angle = math.atan2(dy, dx) # Angle in radians
# Spread angle for multiple shooters (e.g., 10 degrees total spread)
spread_angle = math.radians(10)
start_angle = angle - (self.num_shooters - 1) / 2 * spread_angle
for i in range(self.num_shooters):
bullet_angle = start_angle + i * spread_angle
bullet_dx = math.cos(bullet_angle)
bullet_dy = math.sin(bullet_angle)
bullet_radius = BULLET_BASE_RADIUS * self.bullet_size_multiplier
bullet_speed = BULLET_BASE_SPEED # Speed is not modified by powerup in this version
# Find target for homing bullets
homing_target = None
if self.is_homing_bullets and enemies:
# Find closest enemy
min_dist = float('inf')
for enemy in enemies:
dist = math.sqrt((enemy.x - self.x)**2 + (enemy.y - self.y)**2)
if dist < min_dist:
min_dist = dist
homing_target = enemy
bullets_fired.append(Bullet(self.x, self.y, bullet_dx, bullet_dy, bullet_speed, bullet_radius, self.is_homing_bullets, homing_target))
return bullets_fired
return []
def apply_powerup(self, powerup_type):
now = time.time()
self.effect_end_times[powerup_type] = now + POWERUP_DURATION_SECONDS
# Apply immediate effect and set future state
if powerup_type == POWERUP_TYPE_COOLDOWN:
# Simple stacking: multiply cooldown
self.cooldown_multiplier *= POWERUP_COOLDOWN_MULTIPLIER
# Prevent stacking too much (e.g., max 3 cooldown PUs)
self.cooldown_multiplier = max(0.3, self.cooldown_multiplier) # Cap at 30% original cooldown
elif powerup_type == POWERUP_TYPE_SHOTS:
# Simple stacking: add shooters
self.num_shooters += POWERUP_SHOTS_INCREASE
# Prevent stacking too much (e.g., max 3 extra shooters = 4 total)
self.num_shooters = min(4, self.num_shooters)
elif powerup_type == POWERUP_TYPE_SIZE:
# Simple stacking: multiply size
self.bullet_size_multiplier *= POWERUP_SIZE_MULTIPLIER
# Prevent stacking too much (e.g., max 2 size PUs)
self.bullet_size_multiplier = min(2.5, self.bullet_size_multiplier)
elif powerup_type == POWERUP_TYPE_HOMING:
self.is_homing_bullets = True # Homing is just a toggle while duration lasts
def update_powerups(self):
now = time.time()
# Check each power-up type's timer
for p_type in list(self.effect_end_times.keys()): # Use list to avoid modifying during iteration
if now >= self.effect_end_times[p_type]:
# Effect has expired, revert the change
if p_type == POWERUP_TYPE_COOLDOWN:
# Need to revert one level of multiplication. This is tricky with variable stacks.
# A simpler approach is to track active powerup *instances* or just reset
# multipliers/additions when the *last* of a type expires.
# For simplicity in this minimal code, let's recalculate the *total* effect
# based on how many powerups of each type are still active (which we don't track this way).
# A better way for minimal code: just track if *any* of that powerup type is active
# and apply a fixed total bonus if active. Or, even simpler, just reset to base
# when the timer for that *type* runs out, regardless of how many were picked up.
# Let's go with the simplest: if the timer for a type runs out, reset that specific multiplier/adder.
# This isn't perfect stacking but is minimal.
# A slightly better minimal approach: reset ALL multipliers/adders when ANY timer runs out,
# then re-apply based on currently active (non-expired) powerup types. Still complex.
# Simplest minimal approach: When a timer expires, just reset THAT specific multiplier/adder to base.
# This means effects picked up earlier might expire while later ones are active, which is weird stacking.
# Example: Pick CD, CD becomes 0.8. Pick CD again, CD becomes 0.64. First CD expires, CD stays 0.64.
# This is acceptable for a minimal example.
self.cooldown_multiplier = 1.0
elif p_type == POWERUP_TYPE_SHOTS:
self.num_shooters = 1
elif p_type == POWERUP_TYPE_SIZE:
self.bullet_size_multiplier = 1.0
elif p_type == POWERUP_TYPE_HOMING:
self.is_homing_bullets = False
self.effect_end_times[p_type] = 0 # Reset timer
# Re-apply effects if timer is still active (needed if we went with a complex reset logic above, but not with the simple reset)
# With the simple reset, effects are set once on pickup and only reset when their timer runs out.
# This simple logic works for a minimal version, though proper stacking requires more state.
pass # No re-application needed with the simple reset logic
def draw(self):
pygame.draw.circle(screen, BLUE, (int(self.x), int(self.y)), int(self.radius))
class Bullet:
def __init__(self, x, y, initial_dx, initial_dy, speed, radius, is_homing=False, target=None):
self.x = x
self.y = y
self.radius = radius
self.speed = speed
self.dx = initial_dx
self.dy = initial_dy
self.is_homing = is_homing
self.target = target # Store reference to the enemy object
self.time_created = time.time() # For potential future use like max homing time
# Normalize direction vector if needed (should be already if from angle calculation)
dist = math.sqrt(self.dx**2 + self.dy**2)
if dist != 0:
self.dx /= dist
self.dy /= dist
def update(self, enemies):
if self.is_homing and self.target and self.target in enemies: # Check if target is still alive and in the enemies list
# Calculate new direction towards the target
target_dx = self.target.x - self.x
target_dy = self.target.y - self.y
target_dist = math.sqrt(target_dx**2 + target_dy**2)
if target_dist != 0:
# Simple homing: just point directly at the target
self.dx = target_dx / target_dist
self.dy = target_dy / target_dist
# Optionally add some easing or max turn rate for less jerky movement
# Lerp or slerp could be used here, but simple redirect is minimal.
# Move the bullet
self.x += self.dx * self.speed
self.y += self.dy * self.speed
def draw(self):
pygame.draw.circle(screen, WHITE, (int(self.x), int(self.y)), int(self.radius))
def off_screen(self):
# Use a small buffer to avoid bullets disappearing just off the edge
buffer = 50
return self.x < -buffer or self.x > SCREEN_WIDTH + buffer or self.y < -buffer or self.y > SCREEN_HEIGHT + buffer
class Enemy:
def __init__(self, player):
# Spawn off-screen randomly
side = random.choice(['top', 'bottom', 'left', 'right'])
if side == 'top':
self.x = random.randint(0, SCREEN_WIDTH)
self.y = -self.height
elif side == 'bottom':
self.x = random.randint(0, SCREEN_WIDTH)
self.y = SCREEN_HEIGHT + self.height
elif side == 'left':
self.x = -self.width
self.y = random.randint(0, SCREEN_HEIGHT)
else: # right
self.x = SCREEN_WIDTH + self.width
self.y = random.randint(0, SCREEN_HEIGHT)
self.width = ENEMY_WIDTH
self.height = ENEMY_HEIGHT
self.speed = ENEMY_BASE_SPEED # Simple version, speed doesn't scale with score
self.target = player # Move towards player
def update(self):
dx = self.target.x - self.x
dy = self.target.y - self.y
dist = math.sqrt(dx**2 + dy**2)
if dist > 1: # Avoid division by zero and jitter when very close
self.x += dx / dist * self.speed
self.y += dy / dist * self.speed
def draw(self):
pygame.draw.rect(screen, RED, (int(self.x), int(self.y), self.width, self.height))
def get_rect(self):
return pygame.Rect(self.x, self.y, self.width, self.height)
def collides_with_bullet(self, bullet):
# Simple AABB check for bullet center within enemy rect
# A more accurate check would be circle-rectangle collision
bullet_rect = pygame.Rect(bullet.x - bullet.radius, bullet.y - bullet.radius, bullet.radius * 2, bullet.radius * 2)
return self.get_rect().colliderect(bullet_rect)
# return self.get_rect().collidepoint(bullet.x, bullet.y) # This was the previous simpler check
def collides_with_player(self, player):
# Simple AABB check for player circle within enemy rect
# A more accurate check would be circle-rectangle collision
player_rect = pygame.Rect(player.x - player.radius, player.y - player.radius, player.radius * 2, player.radius * 2)
return self.get_rect().colliderect(player_rect)
class PowerUp:
def __init__(self, x, y, powerup_type):
self.x = x
self.y = y
self.size = POWERUP_SIZE
self.type = powerup_type
self.color = {
POWERUP_TYPE_COOLDOWN: GREEN,
POWERUP_TYPE_SHOTS: YELLOW,
POWERUP_TYPE_SIZE: CYAN,
POWERUP_TYPE_HOMING: MAGENTA,
}.get(powerup_type, WHITE) # Default to white if type is unknown
def draw(self):
pygame.draw.rect(screen, self.color, (int(self.x), int(self.y), self.size, self.size))
def get_rect(self):
return pygame.Rect(self.x, self.y, self.size, self.size)
def collides_with_player(self, player):
# Simple AABB check
player_rect = pygame.Rect(player.x - player.radius, player.y - player.radius, player.radius * 2, player.radius * 2)
return self.get_rect().colliderect(player_rect)
# --- Helper Functions ---
def toggle_fullscreen():
global screen, is_fullscreen, original_screen_size
is_fullscreen = not is_fullscreen
if is_fullscreen:
# Store current size before going fullscreen
original_screen_size = (screen.get_width(), screen.get_height())
screen = pygame.display.set_mode(original_screen_size, pygame.FULLSCREEN)
else:
screen = pygame.display.set_mode(original_screen_size)
def get_dynamic_spawn_delay(score):
delay = ENEMY_BASE_SPAWN_DELAY_FRAMES - score * ENEMY_SPAWN_SCORE_SCALE
return max(ENEMY_MIN_SPAWN_DELAY_FRAMES, delay)
# --- Main Game Function ---
def main():
global screen, is_fullscreen, original_screen_size
player = Player()
bullets = []
enemies = []
powerups = []
score = 0
enemy_spawn_timer = 0 # Timer in frames
powerup_spawn_timer = 0 # Timer in frames
running = True
game_over = False
font = pygame.font.SysFont(None, 36)
game_over_font = pygame.font.SysFont(None, 48)
# Game loop
while running:
dt = clock.tick(60) / 1000.0 # Delta time in seconds (for potential use, currently framerate based)
# --- Event Handling ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.key == pygame.K_F11:
toggle_fullscreen()
# --- Game Logic (only when not game over) ---
if not game_over:
keys = pygame.key.get_pressed()
mouse_buttons = pygame.mouse.get_pressed()
mouse_pos = pygame.mouse.get_pos()
# Update player
player.move(keys)
player.update_powerups()
# Automatic shooting on left mouse button hold
if mouse_buttons[0]: # Check if left mouse button is held down
new_bullets = player.shoot(mouse_pos, enemies) # Pass enemies list for homing
bullets.extend(new_bullets)
# Spawn enemies periodically
enemy_spawn_timer += 1
current_spawn_delay = get_dynamic_spawn_delay(score)
if enemy_spawn_timer >= current_spawn_delay:
enemies.append(Enemy(player))
enemy_spawn_timer = 0
# Spawn power-ups randomly
# Option 1: Chance per frame
if random.random() < POWERUP_SPAWN_CHANCE_PER_FRAME:
# Spawn power-up at a random location away from player
spawn_x = random.randint(0, SCREEN_WIDTH - POWERUP_SIZE)
spawn_y = random.randint(0, SCREEN_HEIGHT - POWERUP_SIZE)
# Simple check to avoid spawning right on the player
if math.sqrt((spawn_x + POWERUP_SIZE/2 - player.x)**2 + (spawn_y + POWERUP_SIZE/2 - player.y)**2) > player.radius * 3:
p_type = random.choice(POWERUP_TYPES)
powerups.append(PowerUp(spawn_x, spawn_y, p_type))
# Update bullets
for bullet in bullets[:]: # Iterate over a slice copy for safe removal
bullet.update(enemies) # Pass enemies list for homing
if bullet.off_screen():
bullets.remove(bullet)
# Update enemies
for enemy in enemies:
enemy.update()
# Check collisions
# Bullet-Enemy collision
for bullet in bullets[:]:
collided_enemy = None
for enemy in enemies[:]:
if enemy.collides_with_bullet(bullet):
collided_enemy = enemy
break # Bullet only hits one enemy
if collided_enemy:
bullets.remove(bullet)
enemies.remove(collided_enemy)
score += 1
# Player-Enemy collision
for enemy in enemies[:]:
if enemy.collides_with_player(player):
game_over = True
break # End game on first player collision
# Player-PowerUp collision
for powerup in powerups[:]:
if powerup.collides_with_player(player):
player.apply_powerup(powerup.type)
powerups.remove(powerup)
# --- Drawing ---
screen.fill(BLACK) # Clear screen
if not game_over:
# Draw everything
player.draw()
for bullet in bullets:
bullet.draw()
for enemy in enemies:
enemy.draw()
for powerup in powerups:
powerup.draw()
# Draw score
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
# Draw active power-up effects (optional)
effect_y_offset = 40
now = time.time()
for p_type, end_time in player.effect_end_times.items():
if end_time > now:
remaining_time = int(end_time - now)
color = {
POWERUP_TYPE_COOLDOWN: GREEN,
POWERUP_TYPE_SHOTS: YELLOW,
POWERUP_TYPE_SIZE: CYAN,
POWERUP_TYPE_HOMING: MAGENTA,
}.get(p_type, WHITE)
effect_text = font.render(f"{p_type.capitalize()}: {remaining_time}s", True, color)
screen.blit(effect_text, (10, effect_y_offset))
effect_y_offset += 30
if game_over:
game_over_text_line1 = game_over_font.render("Game Over!", True, WHITE)
game_over_text_line2 = game_over_font.render(f"Final Score: {score}", True, WHITE)
rect1 = game_over_text_line1.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 30))
rect2 = game_over_text_line2.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 30))
screen.blit(game_over_text_line1, rect1)
screen.blit(game_over_text_line2, rect2)
# Update display
pygame.display.flip()
# End of game loop
pygame.quit()
if __name__ == "__main__":
main()
How to Run:
- Save: Save the code as a Python file (e.g.,
enhanced_shooter.py).
- Install Pygame: If you don't have it, open your terminal or command prompt and run:
pip install pygame
- Run: Navigate to the directory where you saved the file in your terminal or command prompt and run:
python enhanced_shooter.py
New Features Implemented:
- Automatic Shooting: Hold down the left mouse button (
pygame.mouse.get_pressed()[0]) to fire continuously, respecting the cooldown.
- Power-ups:
- Four types spawn randomly: Cooldown (Green), Shots (Yellow), Size (Cyan), Homing (Magenta).
- They appear as colored squares.
- Picking one up (colliding with it) applies a temporary effect (default 10 seconds).
- Active effects and remaining time are shown in the top-left corner.
- Effects (Cooldown, Shots, Size) stack to a limited degree. Homing is a toggle.
- Multiple Shots: Picking up Yellow power-ups increases
num_shooters, firing bullets in a slight spread.
- Larger Bullets: Picking up Cyan power-ups increases
bullet_size_multiplier, making bullets larger.
- Lower Cooldown: Picking up Green power-ups decreases the time needed between shots (
cooldown_multiplier).
- Homing Bullets: Picking up Magenta power-ups makes bullets fired during the effect duration home in on the closest enemy.
- Dynamic Enemy Spawn Rate: As your score increases, the delay between enemy spawns decreases, making the game harder. Capped at a minimum delay.
- Fullscreen: Press F11 to toggle between windowed and fullscreen mode.
- ESC to Quit: Pressing ESC also closes the game window.
- No Assets: Still uses only basic Pygame drawing primitives.
Enjoy the more dynamic and challenging gameplay!