Sure! Let's create an Advanced Python Game using Pygame called "Galaxy Defender". In this game, you control a spaceship that must defend the galaxy from incoming asteroids and enemy ships. The game includes multiple levels, increasing difficulty, power-ups, score tracking, and sound effects to enhance the gaming experience.
Features:
- Player Controls: Move the spaceship using arrow keys and shoot using the spacebar.
- Enemies: Asteroids and enemy ships with different behaviors.
- Power-ups: Collect power-ups to gain advantages like rapid fire or shields.
- Levels: Progress through multiple levels with increasing difficulty.
- Scoring System: Earn points by destroying enemies and collecting power-ups.
- Sound Effects: Background music and sound effects for actions.
Prerequisites:
- Python 3.x installed on your system.
- Pygame library installed. You can install it using pip:
pip install pygame
Complete Code:
Below is the complete Python code for "Galaxy Defender". Save this code in a file named galaxy_defender.py and run it using Python.
import pygame
import random
import math
import sys
# Initialize Pygame
pygame.init()
# Game Constants
WIDTH, HEIGHT = 800, 600
FPS = 60
PLAYER_SPEED = 5
BULLET_SPEED = 10
ASTEROID_SPEED_MIN = 2
ASTEROID_SPEED_MAX = 6
ENEMY_SPEED_MIN = 3
ENEMY_SPEED_MAX = 7
POWERUP_DURATION = 5000 # milliseconds
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Setup Display
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Galaxy Defender")
# Load Images
PLAYER_IMG = pygame.image.load("assets/player.png")
ASTEROID_IMG = pygame.image.load("assets/asteroid.png")
ENEMY_IMG = pygame.image.load("assets/enemy.png")
BULLET_IMG = pygame.image.load("assets/bullet.png")
POWERUP_IMG = pygame.image.load("assets/powerup.png")
# Load Sounds
SHOOT_SOUND = pygame.mixer.Sound("assets/shoot.wav")
EXPLOSION_SOUND = pygame.mixer.Sound("assets/explosion.wav")
POWERUP_SOUND = pygame.mixer.Sound("assets/powerup.wav")
pygame.mixer.music.load("assets/background.mp3")
pygame.mixer.music.play(-1)
# Fonts
FONT = pygame.font.SysFont("arial", 20)
BIG_FONT = pygame.font.SysFont("arial", 40)
# Clock
clock = pygame.time.Clock()
# Helper Functions
def draw_text(text, font, color, surface, x, y):
"""Draw text on the given surface."""
textobj = font.render(text, True, color)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# Classes
class Player(pygame.sprite.Sprite):
def __init__(self):
super(Player, self).__init__()
self.image = pygame.transform.scale(PLAYER_IMG, (50, 38))
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.speed = PLAYER_SPEED
self.last_shot = pygame.time.get_ticks()
self.shot_delay = 500
self.powered_up = False
self.powerup_end_time = 0
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
self.rect.x -= self.speed
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
self.rect.x += self.speed
if keys[pygame.K_UP] or keys[pygame.K_w]:
self.rect.y -= self.speed
if keys[pygame.K_DOWN] or keys[pygame.K_s]:
self.rect.y += self.speed
# Keep player on screen
if self.rect.left < 0:
self.rect.left = 0
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.top < 0:
self.rect.top = 0
if self.rect.bottom > HEIGHT:
self.rect.bottom = HEIGHT
# Power-up timer
if self.powered_up and pygame.time.get_ticks() > self.powerup_end_time:
self.powered_up = False
self.shot_delay = 500
def shoot(self):
now = pygame.time.get_ticks()
if now - self.last_shot > self.shot_delay:
self.last_shot = now
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
SHOOT_SOUND.play()
def power_up(self):
self.powered_up = True
self.powerup_end_time = pygame.time.get_ticks() + POWERUP_DURATION
self.shot_delay = 200
POWERUP_SOUND.play()
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
super(Bullet, self).__init__()
self.image = pygame.transform.scale(BULLET_IMG, (10, 20))
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
self.speedy = -BULLET_SPEED
def update(self):
self.rect.y += self.speedy
# Kill the bullet if it moves off the screen
if self.rect.bottom < 0:
self.kill()
class Asteroid(pygame.sprite.Sprite):
def __init__(self):
super(Asteroid, self).__init__()
self.image = pygame.transform.scale(ASTEROID_IMG, (50, 50))
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, WIDTH - self.rect.width)
self.rect.y = random.randint(-100, -40)
self.speedy = random.randint(ASTEROID_SPEED_MIN, ASTEROID_SPEED_MAX)
self.speedx = random.randint(-3, 3)
def update(self):
self.rect.y += self.speedy
self.rect.x += self.speedx
# Reset asteroid to top if it moves off the screen
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 25:
self.rect.x = random.randint(0, WIDTH - self.rect.width)
self.rect.y = random.randint(-100, -40)
self.speedy = random.randint(ASTEROID_SPEED_MIN, ASTEROID_SPEED_MAX)
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super(Enemy, self).__init__()
self.image = pygame.transform.scale(ENEMY_IMG, (40, 30))
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, WIDTH - self.rect.width)
self.rect.y = random.randint(-150, -100)
self.speedy = random.randint(ENEMY_SPEED_MIN, ENEMY_SPEED_MAX)
self.speedx = random.randint(-4, 4)
def update(self):
self.rect.y += self.speedy
self.rect.x += self.speedx
# Change direction if hitting screen borders
if self.rect.left <= 0 or self.rect.right >= WIDTH:
self.speedx *= -1
# Reset enemy to top if it moves off the screen
if self.rect.top > HEIGHT + 10:
self.rect.x = random.randint(0, WIDTH - self.rect.width)
self.rect.y = random.randint(-150, -100)
self.speedy = random.randint(ENEMY_SPEED_MIN, ENEMY_SPEED_MAX)
class PowerUp(pygame.sprite.Sprite):
def __init__(self):
super(PowerUp, self).__init__()
self.image = pygame.transform.scale(POWERUP_IMG, (30, 30))
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, WIDTH - self.rect.width)
self.rect.y = random.randint(-100, -40)
self.speedy = 3
def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT:
self.kill()
class Explosion(pygame.sprite.Sprite):
def __init__(self, center):
super(Explosion, self).__init__()
self.image = pygame.Surface((50, 50))
self.image.fill(WHITE)
pygame.draw.circle(self.image, (255, 0, 0), (25, 25), 25)
self.rect = self.image.get_rect()
self.rect.center = center
self.duration = 300 # milliseconds
self.start_time = pygame.time.get_ticks()
def update(self):
if pygame.time.get_ticks() - self.start_time > self.duration:
self.kill()
# Groups
all_sprites = pygame.sprite.Group()
asteroids = pygame.sprite.Group()
enemies = pygame.sprite.Group()
bullets = pygame.sprite.Group()
powerups = pygame.sprite.Group()
explosions = pygame.sprite.Group()
# Create Player
player = Player()
all_sprites.add(player)
# Spawn Initial Asteroids
for _ in range(8):
asteroid = Asteroid()
all_sprites.add(asteroid)
asteroids.add(asteroid)
# Spawn Initial Enemies
for _ in range(3):
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
# Score and Lives
score = 0
lives = 3
# Level
level = 1
LEVEL_UP_SCORE = 100
def spawn_powerup():
powerup = PowerUp()
all_sprites.add(powerup)
powerups.add(powerup)
# Main Game Loop
running = True
powerup_spawn_time = pygame.time.get_ticks() + random.randint(5000, 10000)
while running:
clock.tick(FPS)
# Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
# Update
all_sprites.update()
# Check for bullet-asteroid collisions
hits = pygame.sprite.groupcollide(asteroids, bullets, True, True)
for hit in hits:
EXPLOSION_SOUND.play()
score += 10
explosion = Explosion(hit.rect.center)
all_sprites.add(explosion)
explosions.add(explosion)
asteroid = Asteroid()
all_sprites.add(asteroid)
asteroids.add(asteroid)
# Check for bullet-enemy collisions
hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
for hit in hits:
EXPLOSION_SOUND.play()
score += 20
explosion = Explosion(hit.rect.center)
all_sprites.add(explosion)
explosions.add(explosion)
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
# Check for player-asteroid collisions
hits = pygame.sprite.spritecollide(player, asteroids, True, pygame.sprite.collide_rect)
for hit in hits:
EXPLOSION_SOUND.play()
explosion = Explosion(hit.rect.center)
all_sprites.add(explosion)
explosions.add(explosion)
asteroid = Asteroid()
all_sprites.add(asteroid)
asteroids.add(asteroid)
lives -= 1
if lives <= 0:
running = False
# Check for player-enemy collisions
hits = pygame.sprite.spritecollide(player, enemies, True, pygame.sprite.collide_rect)
for hit in hits:
EXPLOSION_SOUND.play()
explosion = Explosion(hit.rect.center)
all_sprites.add(explosion)
explosions.add(explosion)
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
lives -= 1
if lives <= 0:
running = False
# Check for player-powerup collisions
hits = pygame.sprite.spritecollide(player, powerups, True)
for hit in hits:
player.power_up()
score += 50
# Level Up
if score >= level * LEVEL_UP_SCORE:
level += 1
for _ in range(2):
asteroid = Asteroid()
all_sprites.add(asteroid)
asteroids.add(asteroid)
for _ in range(1):
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
# Spawn Power-up
if pygame.time.get_ticks() > powerup_spawn_time:
spawn_powerup()
powerup_spawn_time = pygame.time.get_ticks() + random.randint(15000, 25000)
# Draw / Render
WIN.fill(BLACK)
all_sprites.draw(WIN)
draw_text(f"Score: {score}", FONT, WHITE, WIN, 10, 10)
draw_text(f"Lives: {lives}", FONT, WHITE, WIN, 10, 30)
draw_text(f"Level: {level}", FONT, WHITE, WIN, 10, 50)
pygame.display.flip()
# Game Over Screen
WIN.fill(BLACK)
draw_text("GAME OVER", BIG_FONT, WHITE, WIN, WIDTH / 2 - 100, HEIGHT / 2 - 50)
draw_text(f"Final Score: {score}", FONT, WHITE, WIN, WIDTH / 2 - 60, HEIGHT / 2)
pygame.display.flip()
pygame.time.wait(3000)
pygame.quit()
sys.exit()
Asset Requirements:
For the game to run correctly, you'll need to provide the necessary image and sound assets. Create an assets folder in the same directory as your galaxy_defender.py script and include the following files:
-
Images:
player.png: Image of the player's spaceship.
asteroid.png: Image of an asteroid.
enemy.png: Image of an enemy ship.
bullet.png: Image of a bullet.
powerup.png: Image of a power-up item.
-
Sounds:
shoot.wav: Sound effect for shooting.
explosion.wav: Sound effect for explosions.
powerup.wav: Sound effect for collecting power-ups.
background.mp3: Background music for the game.
You can create your own assets or find free assets online. Ensure that the file names match those specified in the code.
How to Run the Game:
- Ensure you have Python 3.x and Pygame installed.
- Save the provided code in a file named
galaxy_defender.py.
- Create an
assets folder in the same directory and add the required images and sounds.
- Open a terminal or command prompt, navigate to the directory containing
galaxy_defender.py, and run:
python galaxy_defender.py
- Control the spaceship using the arrow keys or
W, A, S, D. Press the Spacebar to shoot.
- Defend the galaxy by destroying asteroids and enemy ships, collecting power-ups, and avoiding collisions.
- The game ends when you lose all your lives. Your final score will be displayed.
Notes:
- Customization: Feel free to customize the game by adding more features, improving graphics, or tweaking the game mechanics.
- Error Handling: Ensure that all asset file paths are correct. Missing assets will cause the game to crash.
- Performance: Running the game on lower-end machines might affect performance. Adjust the
FPS or image sizes if necessary.
Enjoy defending the galaxy!