Here's an enhanced version with your requested features. You'll need to add image/sound files or modify paths:
```python
import pygame
import math
import random
from pygame import mixer
# Initialize Pygame
pygame.init()
mixer.init()
# Game constants
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
GRAVITY = 0.5
LAUNCH_SPEED_MULTIPLIER = 0.15
MAX_LEVEL = 3
# Load assets
try:
bg_image = pygame.image.load("space_bg.jpg").convert()
ufo_image = pygame.image.load("ufo.png").convert_alpha()
player_image = pygame.image.load("cannon.png").convert_alpha()
powerup_images = {
"triple": pygame.image.load("powerup_triple.png").convert_alpha(),
"explosive": pygame.image.load("powerup_explosive.png").convert_alpha()
}
# Sound effects
shoot_sound = mixer.Sound("shoot.wav")
explode_sound = mixer.Sound("explosion.wav")
powerup_sound = mixer.Sound("powerup.wav")
mixer.music.load("background_music.mp3")
except Exception as e:
print("Missing assets:", e)
exit()
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# ... (other colors remain)
class Particle:
def __init__(self, x, y):
self.x = x
self.y = y
self.vx = random.uniform(-3, 3)
self.vy = random.uniform(-5, 0)
self.lifetime = 30
self.color = random.choice([(255, 50, 50), (255, 150, 0), (255, 255, 0)])
def update(self):
self.x += self.vx
self.y += self.vy
self.vy += GRAVITY * 0.5
self.lifetime -= 2
def draw(self):
if self.lifetime > 0:
alpha = min(255, self.lifetime * 8)
size = random.randint(2, 5)
pygame.draw.circle(screen, self.color + (alpha,),
(int(self.x), int(self.y)), size)
class PowerUp:
def __init__(self, x, y, type):
self.x = x
self.y = y
self.type = type
self.radius = 15
self.timer = 600 # 10 seconds at 60 FPS
def draw(self):
screen.blit(powerup_images[self.type], (self.x - 15, self.y - 15))
class Level:
def __init__(self, number):
self.number = number
self.ufos = []
self.structures = []
self.powerups = []
self.load_level()
def load_level(self):
# Level design configurations
if self.number == 1:
self.ufos = [UFO(900, 300, "shooter"), UFO(1000, 500, "shooter")]
self.structures = [Structure(600, 500, 80, 200), Structure(400, 600, 100, 150)]
elif self.number == 2:
self.ufos = [UFO(950, 200, "charger"), UFO(850, 400, "bomber")]
self.structures = [Structure(500, 400, 120, 250), Structure(700, 500, 100, 150)]
elif self.number == 3:
self.ufos = [UFO(900, 300, "mothership")]
self.structures = [Structure(600, 400, 200, 300)]
class Projectile:
# ... previous code ...
def __init__(self, x, y, radius, color, velocity, damage, type="normal"):
self.type = type # normal, explosive, split
# Add particle trail
self.particles = []
def update(self):
# Add particle trail
if self.active and random.random() < 0.5:
self.particles.append(Particle(self.x, self.y))
# Update particles
for p in self.particles[:]:
p.update()
if p.lifetime <= 0:
self.particles.remove(p)
def draw(self):
# Draw particles first
for p in self.particles:
p.draw()
if self.active:
# Different visuals for different types
if self.type == "explosive":
pygame.draw.circle(screen, ORANGE, (int(self.x), int(self.y)), self.radius)
elif self.type == "split":
pygame.draw.polygon(screen, BLUE, [(self.x, self.y),
(self.x+10, self.y+5), (self.x+5, self.y+10)])
else:
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
class UFO:
def __init__(self, x, y, type="shooter"):
self.type = type
self.image = pygame.transform.scale(ufo_image, (60, 60))
self.original_image = self.image
# Different behaviors based on type
if type == "charger":
self.speed = 5
self.health = 150
self.attack_cooldown = 120
elif type == "mothership":
self.health = 500
self.speed = 1
self.spawn_timer = 180
def update(self, target_x, target_y):
# Complex AI based on type
if self.type == "charger":
if random.random() < 0.02:
self.direction = 1 if target_x > self.x else -1
self.speed = 8
# Charging behavior
elif self.type == "mothership":
if self.spawn_timer <= 0:
self.spawn_minions()
self.spawn_timer = 180
else:
self.spawn_timer -= 1
def spawn_minions(self):
current_level.ufos.append(UFO(self.x + 50, self.y + 50, "shooter"))
current_level.ufos.append(UFO(self.x - 50, self.y + 50, "shooter"))
class GameState:
def __init__(self):
self.lives = 3
self.score = 0
self.current_level = 1
self.active_powerups = {}
self.player_health = 100
def next_level(self):
if self.current_level < MAX_LEVEL:
self.current_level += 1
return True
else:
# Game won
return False
# Initialize game state
game_state = GameState()
current_level = Level(game_state.current_level)
def handle_powerups():
for powerup in current_level.powerups[:]:
# Check collision with slingshot area
if math.hypot(powerup.x - slingshot_pos[0], powerup.y - slingshot_pos[1]) < 50:
apply_powerup(powerup.type)
current_level.powerups.remove(powerup)
powerup_sound.play()
def apply_powerup(type):
if type == "triple":
game_state.active_powerups["triple"] = 300 # 5 seconds
elif type == "explosive":
game_state.active_powerups["explosive"] = 450 # 7.5 seconds
# Modified shooting code
def create_projectile(velocity, type="normal"):
base_damage = 50
if "explosive" in game_state.active_powerups:
type = "explosive"
base_damage = 75
projectile = Projectile(..., type=type, damage=base_damage)
if "triple" in game_state.active_powerups:
# Create two additional projectiles at angles
angle = math.radians(15)
for ang in [-angle, angle]:
vx = velocity[0] * math.cos(ang) - velocity[1] * math.sin(ang)
vy = velocity[0] * math.sin(ang) + velocity[1] * math.cos(ang)
projectiles.append(Projectile(..., [vx, vy], type=type))
# In main game loop:
# Handle powerup timers
for powerup in list(game_state.active_powerups.keys()):
game_state.active_powerups[powerup] -= 1
if game_state.active_powerups[powerup] <= 0:
del game_state.active_powerups[powerup]
# Add powerup drops when UFOs are destroyed
if random.random() < 0.2:
current_level.powerups.append(PowerUp(ufo.x, ufo.y, random.choice(["triple", "explosive"])))
# Add health display
font = pygame.font.Font(None, 36)
health_text = font.render(f"Health: {game_state.player_health}", True, WHITE)
screen.blit(health_text, (SCREEN_WIDTH - 150, 10))
# Add level display
level_text = font.render(f"Level: {game_state.current_level}", True, WHITE)
screen.blit(level_text, (SCREEN_WIDTH//2 - 50, 10))
# Add particle effects to explosions
class Explosion:
def __init__(self, x, y):
self.particles = [Particle(x, y) for _ in range(50)]
def draw(self):
for p in self.particles:
p.draw()
# Add sound effects to relevant locations:
# When shooting
shoot_sound.play()
# When exploding
explode_sound.play()
# When collecting powerup
powerup_sound.play()
# Play background music
mixer.music.play(-1)
# Level progression check
if not current_level.ufos:
if game_state.next_level():
current_level = Level(game_state.current_level)
else:
# Show victory screen
pass
# Player health check
if game_state.player_health <= 0:
# Game over logic
pass
```
Key additions:
1. **Level System**: Multiple levels with different configurations
2. **Projectile Types**: Explosive, split, and triple shots
3. **Power-ups**: Temporary boosts with visual indicators
4. **Enhanced UFO AI**: Different behaviors (shooter, charger, bomber, mothership)
5. **Particle System**: Improved visual effects for explosions and trails
6. **Health System**: Player health and lives
7. **Sound System**: Background music and sound effects
8. **Visual Improvements**: Sprites instead of basic shapes
9. **Power-up Drops**: Random chance to drop power-ups when defeating UFOs
To complete this game, you'll need to:
1. Create/find appropriate image assets (UFO, background, power-ups)
2. Add sound files (.wav or .ogg) for sound effects
3. Balance game mechanics (difficulty, power-up durations)
4. Add menu systems and victory/defeat screens
5. Implement proper asset loading with error handling
6. Add particle effect customization
7. Fine-tune UFO AI behaviors
8. Add additional power-up types and projectile variations
The code provides a framework for these features - you can expand each system based on your specific├── assets/
│ ├── nasa_ufo_models/ (CC-BY 3D models)
│ ├── sound_effects/ (WAV files)
├── levels/
│ ├── piglantis.json (Level 2 config):cite[1]
│ └── danger_zone.json (Final level):cite[3]
└── main.py (Pygame core) needs and available assets.class PowerUp:
def apply_effect(self):
if self.type == "gravity_reverse":
global GRAVITY
GRAVITY *= -1
```:cite[3]class SpacePig(UFO):https://chatbot.getmindpal.com/alphworld7
def __init__(self, type):
if type == "vampire":
self.health *= 1.5
self.speed *= 0.8
```:cite[1]class SpacePig(UFO):https://chatbot.getmindpal.com/alphworld7
def __init__(self, type):
if type == "vampire":
self.health *= 1.5
self.speed *= 0.8
```:cite[1]


No comments:
Post a Comment