Space Shooter Game Development Using Python and Pygame

Spacer Shooter Game in Python

Space Shooter Game Development Using Python and Pygame

Want to build your own arcade-style space shooting game with Python? In this tutorial, we will create Space Shooter Pro, a complete single-file 2D game made with Python and Pygame. You control a spaceship, shoot incoming enemies, avoid enemy bullets, collect coins, unlock ships and weapons, and fight a powerful boss at the end of each level.

This project is designed as a practical beginner-to-intermediate game development example. It brings together a game loop, keyboard controls, enemy AI, bullets, collision detection, particle effects, sound effects, a shop, level progression, and a JSON save system.

1. Features of Space Shooter Pro

  • Animated space background with moving stars.
  • Keyboard-controlled spaceship movement.
  • Hold Space to fire different weapon types.
  • Three regular enemy designs with health and shooting behaviour.
  • Boss battles with a health bar and multi-bullet attacks.
  • Player health, score, level target, and coin rewards.
  • Ship hangar with four ships to purchase and equip.
  • Weapon shop with four weapon types.
  • Pause, level-complete, game-over, and main-menu screens.
  • Generated sound effects, so no external audio files are required.
  • JSON save file for coins, unlocked items, selected equipment, and best level.

2. Requirements

Install Python on your computer, then install Pygame from Command Prompt:

python -m pip install pygame

The game uses Python's built-in modules for JSON, maths, random values, and sound generation. No image or audio asset folders are required because the ships, enemies, bullets, background, and sound effects are generated by the program.

3. Create the Python File

Create a folder for the project. Inside it, create a file named space_shooter.py. Copy the complete source code from the next section into that file and save it.

4. Complete Space Shooter Python Source Code

The following is the complete single-file game source. Copy all of it, starting from the first line and ending at the last line. Do not remove the indentation.

SPACE SHOOTER
A complete single-file Python/Pygame arcade shooter.
Install: pip install pygame
Run:     python space_shooter.py

Controls:
  WASD / Arrow keys : Move
  SPACE             : Shoot (hold)
  P / ESC           : Pause
  Mouse             : Menus, shop and hangar
  R                 : Restart after game over

import json
import math
import os
import random
import struct
import sys
import wave
from array import array

import pygame

# ------------------------------ Configuration ------------------------------
WIDTH, HEIGHT = 900, 700
FPS = 60
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SAVE_FILE = os.path.join(BASE_DIR, "space_shooter_save.json")
TITLE = "SPACE SHOOTER PRO"

BG = (7, 10, 27)
PANEL = (17, 24, 51)
PANEL_LIGHT = (27, 38, 75)
WHITE = (240, 246, 255)
MUTED = (145, 162, 195)
CYAN = (60, 225, 255)
BLUE = (70, 130, 255)
PURPLE = (174, 100, 255)
GOLD = (255, 207, 75)
RED = (255, 82, 105)
GREEN = (92, 242, 166)

pygame.init()
try:
    pygame.mixer.init()
except pygame.error:
    pass
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()

FONT = pygame.font.SysFont("arial", 22)
SMALL = pygame.font.SysFont("arial", 16)
MED = pygame.font.SysFont("arial", 28, bold=True)
BIG = pygame.font.SysFont("arial", 52, bold=True)
HUGE = pygame.font.SysFont("arial", 66, bold=True)


# ------------------------------ Tiny generated sounds ----------------------
def make_tone(frequency=440, duration=0.09, volume=0.18, sweep=0):
    """Create a short WAV sound in memory. Works without external audio files."""
    if not pygame.mixer.get_init():
        return None
    sample_rate = 22050
    count = int(sample_rate * duration)
    samples = array("h")
    for i in range(count):
        t = i / sample_rate
        freq = frequency + sweep * (i / max(1, count))
        envelope = (1 - i / count) ** 2
        value = int(32767 * volume * envelope * math.sin(2 * math.pi * freq * t))
        samples.append(value)
    if sys.byteorder == "big":
        samples.byteswap()
    raw = samples.tobytes()
    # pygame Sound accepts a WAV byte buffer
    header = (
        b"RIFF" + struct.pack("<I", 36 + len(raw)) + b"WAVE"
        + b"fmt " + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate,
                                 sample_rate * 2, 2, 16)
        + b"data" + struct.pack("<I", len(raw))
    )
    try:
        return pygame.mixer.Sound(buffer=header + raw)
    except pygame.error:
        return None


SOUNDS = {
    "shoot": make_tone(780, 0.045, 0.10, -220),
    "hit": make_tone(170, 0.11, 0.16, -80),
    "coin": make_tone(900, 0.12, 0.13, 500),
    "buy": make_tone(520, 0.18, 0.14, 420),
    "boss": make_tone(100, 0.35, 0.18, -55),
}


def play_sound(name):
    snd = SOUNDS.get(name)
    if snd:
        try:
            snd.play()
        except pygame.error:
            pass


# ------------------------------ Save data -----------------------------------
SHIP_DATA = [
    {"name": "Rookie", "price": 0, "hp": 100, "speed": 5.2, "damage": 10,
     "color": (65, 220, 255), "description": "Balanced starter fighter"},
    {"name": "Viper", "price": 250, "hp": 115, "speed": 6.0, "damage": 13,
     "color": (100, 255, 170), "description": "Fast and agile"},
    {"name": "Phantom", "price": 500, "hp": 145, "speed": 5.4, "damage": 17,
     "color": (190, 120, 255), "description": "Heavy plasma power"},
    {"name": "Titan", "price": 900, "hp": 200, "speed": 4.7, "damage": 22,
     "color": (255, 170, 75), "description": "Armored battle ship"},
]
WEAPON_DATA = [
    {"name": "Single Laser", "price": 0, "damage": 1.0, "level": 1,
     "description": "One focused energy bolt"},
    {"name": "Double Laser", "price": 300, "damage": 1.45, "level": 2,
     "description": "Two parallel laser bolts"},
    {"name": "Spread Shot", "price": 650, "damage": 1.25, "level": 3,
     "description": "Three-way energy spread"},
    {"name": "Plasma Cannon", "price": 1100, "damage": 2.0, "level": 4,
     "description": "High damage plasma blast"},
]


def default_save():
    return {
        "coins": 150,
        "best_level": 1,
        "selected_ship": 0,
        "selected_weapon": 0,
        "owned_ships": [0],
        "owned_weapons": [0],
        "sound": True,
    }


def load_save():
    data = default_save()
    try:
        if os.path.exists(SAVE_FILE):
            with open(SAVE_FILE, "r", encoding="utf-8") as f:
                loaded = json.load(f)
            if isinstance(loaded, dict):
                data.update(loaded)
    except (OSError, ValueError, TypeError):
        pass
    # Repair invalid or old save values safely.
    data["coins"] = max(0, int(data.get("coins", 0)))
    data["owned_ships"] = sorted(set([0] + [
        int(x) for x in data.get("owned_ships", [0])
        if str(x).isdigit() and 0 <= int(x) < len(SHIP_DATA)
    ]))
    data["owned_weapons"] = sorted(set([0] + [
        int(x) for x in data.get("owned_weapons", [0])
        if str(x).isdigit() and 0 <= int(x) < len(WEAPON_DATA)
    ]))
    if data.get("selected_ship") not in data["owned_ships"]:
        data["selected_ship"] = 0
    if data.get("selected_weapon") not in data["owned_weapons"]:
        data["selected_weapon"] = 0
    data["best_level"] = max(1, int(data.get("best_level", 1)))
    return data


save_data = load_save()


def save_game():
    try:
        with open(SAVE_FILE, "w", encoding="utf-8") as f:
            json.dump(save_data, f, indent=4)
    except OSError:
        pass


# ------------------------------ Drawing helpers ----------------------------
def draw_text(surface, text, font, color, x, y, center=False):
    image = font.render(str(text), True, color)
    rect = image.get_rect()
    if center:
        rect.center = (int(x), int(y))
    else:
        rect.topleft = (int(x), int(y))
    surface.blit(image, rect)
    return rect


def rounded_panel(surface, rect, color=PANEL, border=(48, 72, 125), radius=18, width=2):
    pygame.draw.rect(surface, color, rect, border_radius=radius)
    if width:
        pygame.draw.rect(surface, border, rect, width, border_radius=radius)


def button(surface, rect, label, color=BLUE, enabled=True, font=FONT):
    mouse = pygame.mouse.get_pos()
    hovered = rect.collidepoint(mouse)
    base = color if enabled else (65, 72, 91)
    if hovered and enabled:
        base = tuple(min(255, c + 28) for c in base)
    pygame.draw.rect(surface, base, rect, border_radius=12)
    pygame.draw.rect(surface, (130, 190, 255) if enabled else (95, 102, 120),
                     rect, 2, border_radius=12)
    draw_text(surface, label, font, WHITE if enabled else MUTED,
              rect.centerx, rect.centery, True)
    return enabled and hovered


def draw_ship(surface, x, y, scale, color, flame=True):
    """Draw a stylized player spaceship with vector shapes."""
    s = scale
    if flame:
        flicker = random.randint(-3, 5)
        pygame.draw.polygon(surface, (255, 130, 55), [
            (x - 8*s, y + 17*s), (x, y + (32+flicker)*s), (x + 8*s, y + 17*s)
        ])
        pygame.draw.polygon(surface, (255, 230, 110), [
            (x - 4*s, y + 17*s), (x, y + (26+flicker)*s), (x + 4*s, y + 17*s)
        ])
    points = [
        (x, y - 27*s), (x + 20*s, y + 17*s), (x + 7*s, y + 12*s),
        (x, y + 18*s), (x - 7*s, y + 12*s), (x - 20*s, y + 17*s)
    ]
    pygame.draw.polygon(surface, color, points)
    pygame.draw.polygon(surface, WHITE, points, max(1, int(1.5*s)))
    pygame.draw.polygon(surface, (20, 55, 100), [
        (x, y - 13*s), (x + 6*s, y + 6*s), (x, y + 10*s), (x - 6*s, y + 6*s)
    ])
    pygame.draw.line(surface, CYAN, (x - 15*s, y + 12*s),
                     (x - 5*s, y + 15*s), max(1, int(2*s)))
    pygame.draw.line(surface, CYAN, (x + 15*s, y + 12*s),
                     (x + 5*s, y + 15*s), max(1, int(2*s)))


def draw_enemy(surface, x, y, size, color, kind=0):
    s = size
    if kind == 0:
        points = [(x, y + 19*s), (x + 22*s, y - 10*s), (x + 7*s, y - 5*s),
                  (x, y - 18*s), (x - 7*s, y - 5*s), (x - 22*s, y - 10*s)]
    elif kind == 1:
        points = [(x - 22*s, y - 14*s), (x, y - 20*s), (x + 22*s, y - 14*s),
                  (x + 15*s, y + 15*s), (x, y + 20*s), (x - 15*s, y + 15*s)]
    else:
        points = [(x, y + 20*s), (x + 25*s, y - 8*s), (x + 8*s, y - 17*s),
                  (x, y - 8*s), (x - 8*s, y - 17*s), (x - 25*s, y - 8*s)]
    pygame.draw.polygon(surface, color, points)
    pygame.draw.polygon(surface, (255, 220, 230), points, 2)
    pygame.draw.circle(surface, (30, 20, 45), (int(x), int(y)), max(3, int(5*s)))
    pygame.draw.circle(surface, GOLD, (int(x), int(y)), max(2, int(2*s)))


def draw_boss_ship(surface, x, y, phase=0):
    body = [(x, y + 62), (x + 95, y + 20), (x + 125, y - 35),
            (x + 55, y - 25), (x, y - 65), (x - 55, y - 25),
            (x - 125, y - 35), (x - 95, y + 20)]
    pygame.draw.polygon(surface, (100, 35, 75), body)
    pygame.draw.polygon(surface, (255, 90, 140), body, 4)
    pygame.draw.polygon(surface, (35, 30, 75), [
        (x, y - 42), (x + 30, y + 20), (x, y + 42), (x - 30, y + 20)
    ])
    pygame.draw.circle(surface, (255, 65, 100), (int(x), int(y + 3)), 16 + int(3*math.sin(phase)))
    for side in (-1, 1):
        pygame.draw.circle(surface, CYAN, (int(x + side*75), int(y - 8)), 9)


def draw_health_bar(surface, x, y, width, height, value, maximum, color=GREEN):
    pygame.draw.rect(surface, (45, 50, 72), (x, y, width, height), border_radius=5)
    ratio = max(0, min(1, value / max(1, maximum)))
    if ratio:
        pygame.draw.rect(surface, color, (x, y, int(width*ratio), height), border_radius=5)


# ------------------------------ Background ----------------------------------
stars = []
for _ in range(100):
    stars.append([random.randrange(WIDTH), random.randrange(HEIGHT),
                  random.choice([1, 1, 2, 3]), random.uniform(35, 115)])


def draw_background(dt, offset=1):
    screen.fill(BG)
    # Subtle nebula glow
    for i in range(4):
        cx = (i * 270 + 100) % WIDTH
        pygame.draw.circle(screen, (12, 17, 43), (cx, 250 + i*95), 145)
    for star in stars:
        star[1] += star[3] * dt * offset
        if star[1] > HEIGHT:
            star[0] = random.randrange(WIDTH)
            star[1] = -5
        shade = random.randint(115, 210)
        pygame.draw.circle(screen, (shade, shade, min(255, shade+35)),
                           (int(star[0]), int(star[1])), star[2])


# ------------------------------ Game objects --------------------------------
class Bullet:
    def __init__(self, x, y, vx, vy, damage, friendly=True, color=CYAN, radius=5):
        self.x, self.y = float(x), float(y)
        self.vx, self.vy = vx, vy
        self.damage = damage
        self.friendly = friendly
        self.color = color
        self.radius = radius
        self.alive = True

    def update(self, dt):
        self.x += self.vx * dt
        self.y += self.vy * dt
        if self.y < -40 or self.y > HEIGHT+40 or self.x < -40 or self.x > WIDTH+40:
            self.alive = False

    def draw(self, surface):
        if self.friendly:
            pygame.draw.line(surface, self.color, (int(self.x), int(self.y+10)),
                             (int(self.x), int(self.y-10)), 4)
            pygame.draw.circle(surface, WHITE, (int(self.x), int(self.y-9)), 2)
        else:
            pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), self.radius)
            pygame.draw.circle(surface, WHITE, (int(self.x), int(self.y)), 2)


class Enemy:
    def __init__(self, level):
        self.x = random.randint(55, WIDTH-55)
        self.y = random.randint(-180, -45)
        self.kind = random.randrange(3)
        self.size = random.uniform(0.8, 1.15)
        self.hp = (22 + level*7) * (1.5 if self.kind == 2 else 1)
        self.max_hp = self.hp
        self.speed = random.uniform(95, 145) + level*8
        self.color = [(255, 90, 115), (180, 105, 255), (255, 160, 65)][self.kind]
        self.shoot_timer = random.uniform(0.8, 2.2)
        self.phase = random.random() * 6
        self.alive = True

    def update(self, dt, level, bullets):
        self.phase += dt * 2
        self.y += self.speed * dt
        self.x += math.sin(self.phase) * 45 * dt
        self.shoot_timer -= dt
        if self.shoot_timer <= 0 and self.y > 30:
            self.shoot_timer = random.uniform(1.5, 2.5) / min(2.2, 1 + level*0.04)
            bullets.append(Bullet(self.x, self.y+15, 0, 270+level*7,
                                  9+level, False, self.color, 6))
        if self.y > HEIGHT + 50:
            self.alive = False

    def draw(self, surface):
        draw_enemy(surface, self.x, self.y, self.size, self.color, self.kind)
        if self.hp < self.max_hp:
            draw_health_bar(surface, self.x-22, self.y+24, 44, 5,
                            self.hp, self.max_hp, RED)


class Boss:
    def __init__(self, level):
        self.x = WIDTH/2
        self.y = 115
        self.max_hp = 850 + level*260
        self.hp = self.max_hp
        self.phase = 0
        self.shoot_timer = 1.0
        self.alive = True

    def update(self, dt, bullets):
        self.phase += dt
        self.x = WIDTH/2 + math.sin(self.phase*0.75) * 245
        self.shoot_timer -= dt
        if self.shoot_timer <= 0:
            self.shoot_timer = max(0.38, 0.95 - self.phase*0.008)
            for dx in (-75, -38, 0, 38, 75):
                bullets.append(Bullet(self.x+dx, self.y+38, dx*0.48, 280,
                                      14, False, (255, 70, 125), 7))
        if self.hp <= 0:
            self.alive = False

    def draw(self, surface):
        draw_boss_ship(surface, self.x, self.y, self.phase)
        draw_text(surface, "BOSS", MED, RED, WIDTH/2, 24, True)
        draw_health_bar(surface, 185, 53, 530, 15, self.hp, self.max_hp, RED)


class Particle:
    def __init__(self, x, y, color):
        self.x, self.y = x, y
        angle = random.random()*math.tau
        speed = random.uniform(50, 230)
        self.vx, self.vy = math.cos(angle)*speed, math.sin(angle)*speed
        self.life = random.uniform(0.25, 0.65)
        self.max_life = self.life
        self.color = color

    def update(self, dt):
        self.x += self.vx*dt
        self.y += self.vy*dt
        self.life -= dt

    def draw(self, surface):
        r = max(1, int(4*self.life/self.max_life))
        pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), r)


# ------------------------------ Game state ----------------------------------
state = "menu"  # menu, game, shop, pause, gameover, victory
shop_tab = "ships"
shop_message = ""
shop_message_timer = 0
player_x, player_y = WIDTH/2, HEIGHT-95
player_hp = 100
player_max_hp = 100
player_invulnerable = 0
player_bullets = []
enemy_bullets = []
enemies = []
particles = []
boss = None
level = 1
score = 0
level_kills = 0
level_target = 8
shoot_timer = 0
enemy_spawn_timer = 0
coin_pickups = []
run_reward = 0
game_time = 0


def current_ship():
    return SHIP_DATA[save_data["selected_ship"]]


def current_weapon():
    return WEAPON_DATA[save_data["selected_weapon"]]


def start_level(new_level=1):
    global state, player_x, player_y, player_hp, player_max_hp
    global player_bullets, enemy_bullets, enemies, particles, boss
    global level, score, level_kills, level_target, shoot_timer
    global enemy_spawn_timer, coin_pickups, run_reward, game_time
    level = new_level
    ship = current_ship()
    player_max_hp = ship["hp"]
    player_hp = player_max_hp
    player_x, player_y = WIDTH/2, HEIGHT-95
    player_bullets, enemy_bullets, enemies, particles = [], [], [], []
    boss = None
    score = 0
    level_kills = 0
    level_target = 7 + level*2
    shoot_timer = 0
    enemy_spawn_timer = 0.7
    coin_pickups = []
    run_reward = 0
    game_time = 0
    state = "game"


def add_explosion(x, y, color, amount=14):
    for _ in range(amount):
        particles.append(Particle(x, y, color))


def spawn_enemy():
    enemies.append(Enemy(level))


def fire_player():
    ship = current_ship()
    weapon = current_weapon()
    damage = ship["damage"] * weapon["damage"]
    color = ship["color"]
    if save_data["selected_weapon"] == 0:
        player_bullets.append(Bullet(player_x, player_y-25, 0, -620, damage, True, color))
    elif save_data["selected_weapon"] == 1:
        player_bullets.append(Bullet(player_x-12, player_y-18, 0, -620, damage, True, color))
        player_bullets.append(Bullet(player_x+12, player_y-18, 0, -620, damage, True, color))
    elif save_data["selected_weapon"] == 2:
        for vx in (-190, 0, 190):
            player_bullets.append(Bullet(player_x, player_y-20, vx, -590, damage, True, PURPLE, 5))
    else:
        player_bullets.append(Bullet(player_x, player_y-25, 0, -760, damage, True, GOLD, 8))
    if save_data.get("sound", True):
        play_sound("shoot")


def reward_enemy(x, y, amount):
    global run_reward
    run_reward += amount
    coin_pickups.append([float(x), float(y), amount, 0.0])


def finish_level():
    global state
    reward = 100 + level*35
    save_data["coins"] += reward
    save_data["best_level"] = max(save_data["best_level"], level+1)
    save_game()
    state = "victory"


def end_game():
    global state
    save_data["best_level"] = max(save_data["best_level"], level)
    save_game()
    state = "gameover"


def update_game(dt):
    global player_x, player_y, player_hp, player_invulnerable
    global shoot_timer, enemy_spawn_timer, boss, level_kills, score, game_time
    global state
    # These lists are reassigned below, so they must be declared global.
    global player_bullets, enemy_bullets, enemies, particles

    game_time += dt
    keys = pygame.key.get_pressed()
    ship = current_ship()
    speed = ship["speed"] * 60
    dx = (keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or keys[pygame.K_a])
    dy = (keys[pygame.K_DOWN] or keys[pygame.K_s]) - (keys[pygame.K_UP] or keys[pygame.K_w])
    length = math.hypot(dx, dy)
    if length:
        player_x += dx/length * speed*dt
        player_y += dy/length * speed*dt
    player_x = max(30, min(WIDTH-30, player_x))
    player_y = max(90, min(HEIGHT-35, player_y))

    player_invulnerable = max(0, player_invulnerable-dt)
    shoot_timer -= dt
    if keys[pygame.K_SPACE] and shoot_timer <= 0:
        fire_player()
        shoot_timer = 0.19 if save_data["selected_weapon"] != 3 else 0.28

    # Spawn regular enemies until the level target is reached.
    if boss is None and level_kills < level_target:
        enemy_spawn_timer -= dt
        if enemy_spawn_timer <= 0 and len(enemies) < 7:
            spawn_enemy()
            enemy_spawn_timer = max(0.42, 1.15 - level*0.035)

    for b in player_bullets:
        b.update(dt)
    for b in enemy_bullets:
        b.update(dt)
    player_bullets = [b for b in player_bullets if b.alive]
    enemy_bullets = [b for b in enemy_bullets if b.alive]

    for e in enemies:
        e.update(dt, level, enemy_bullets)
    for p in particles:
        p.update(dt)
    particles = [p for p in particles if p.life > 0]

    # Player bullets hit enemies.
    for b in player_bullets:
        if not b.alive:
            continue
        for e in enemies:
            if e.alive and math.hypot(b.x-e.x, b.y-e.y) < 27*e.size:
                e.hp -= b.damage
                b.alive = False
                add_explosion(b.x, b.y, e.color, 3)
                if e.hp <= 0:
                    e.alive = False
                    level_kills += 1
                    score += 100
                    reward_enemy(e.x, e.y, 10 + level*2)
                    add_explosion(e.x, e.y, e.color, 20)
                    if save_data.get("sound", True):
                        play_sound("hit")
                break

    # Boss appears after all regular enemies are defeated.
    enemies = [e for e in enemies if e.alive]
    if level_kills >= level_target and not enemies and boss is None:
        boss = Boss(level)
        if save_data.get("sound", True):
            play_sound("boss")

    if boss:
        boss.update(dt, enemy_bullets)
        for b in player_bullets:
            if b.alive and math.hypot(b.x-boss.x, b.y-boss.y) < 112:
                boss.hp -= b.damage
                b.alive = False
                add_explosion(b.x, b.y, CYAN, 2)
        if not boss.alive:
            add_explosion(boss.x, boss.y, PURPLE, 65)
            reward_enemy(boss.x, boss.y, 100 + level*20)
            finish_level()
            return

    # Enemy bullets damage player.
    if player_invulnerable <= 0:
        for b in enemy_bullets:
            if math.hypot(b.x-player_x, b.y-player_y) < 23:
                b.alive = False
                player_hp -= b.damage
                player_invulnerable = 0.65
                add_explosion(player_x, player_y, RED, 9)
                if player_hp <= 0:
                    player_hp = 0
                    end_game()
                break

    # Pick up coins dropped by destroyed enemies.
    for coin in coin_pickups[:]:
        coin[1] += 125*dt
        coin[3] += dt
        if math.hypot(coin[0]-player_x, coin[1]-player_y) < 31:
            save_data["coins"] += coin[2]
            coin_pickups.remove(coin)
            if save_data.get("sound", True):
                play_sound("coin")
        elif coin[1] > HEIGHT+15 or coin[3] > 8:
            coin_pickups.remove(coin)


def draw_hud():
    rounded_panel(screen, (16, 14, 240, 66), (12, 19, 43), (43, 69, 115), 13, 1)
    draw_text(screen, f"LEVEL {level}", MED, WHITE, 30, 21)
    draw_text(screen, f"SCORE {score}", SMALL, MUTED, 32, 52)
    rounded_panel(screen, (WIDTH-245, 14, 228, 66), (12, 19, 43), (43, 69, 115), 13, 1)
    draw_text(screen, f"COINS  {save_data['coins']}", MED, GOLD, WIDTH-228, 22)
    draw_text(screen, f"SHIPS DOWN  {level_kills}/{level_target}", SMALL, MUTED, WIDTH-228, 52)
    rounded_panel(screen, (16, HEIGHT-45, 250, 29), (12, 19, 43), (43, 69, 115), 10, 1)
    draw_text(screen, "HULL", SMALL, WHITE, 25, HEIGHT-42)
    draw_health_bar(screen, 82, HEIGHT-36, 170, 12, player_hp, player_max_hp,
                    GREEN if player_hp > player_max_hp*0.3 else RED)
    draw_text(screen, "WASD / ARROWS  MOVE     SPACE  FIRE     P  PAUSE",
              SMALL, MUTED, WIDTH/2, HEIGHT-23, True)


def draw_game():
    draw_background(1/FPS, 0.35)
    for coin in coin_pickups:
        pygame.draw.circle(screen, GOLD, (int(coin[0]), int(coin[1])), 9)
        pygame.draw.circle(screen, WHITE, (int(coin[0]), int(coin[1])), 4)
    for b in player_bullets + enemy_bullets:
        b.draw(screen)
    for e in enemies:
        e.draw(screen)
    if boss:
        boss.draw(screen)
    for p in particles:
        p.draw(screen)
    if player_invulnerable <= 0 or int(game_time*15) % 2 == 0:
        draw_ship(screen, player_x, player_y, 1.25, current_ship()["color"])
    draw_hud()


# ------------------------------ Screens -------------------------------------
def draw_title():
    draw_background(1/FPS, 0.18)
    # Decorative ships
    for i in range(5):
        draw_enemy(screen, 115+i*165, 145+math.sin(pygame.time.get_ticks()/600+i)*18,
                   0.8, [(255, 90, 115), PURPLE, CYAN, GOLD, GREEN][i], i % 3)
    draw_text(screen, "SPACE SHOOTER", HUGE, WHITE, WIDTH/2, 265, True)
    draw_text(screen, "PRO", BIG, CYAN, WIDTH/2, 325, True)
    draw_text(screen, "FIGHT  •  UPGRADE  •  CONQUER", FONT, MUTED, WIDTH/2, 375, True)
    draw_text(screen, f"COINS  {save_data['coins']}     BEST LEVEL  {save_data['best_level']}",
              FONT, GOLD, WIDTH/2, 430, True)
    button(screen, pygame.Rect(320, 485, 260, 55), "▶  PLAY GAME", (30, 135, 210))
    button(screen, pygame.Rect(320, 550, 260, 48), "🚀  HANGAR & SHOP", (100, 75, 185))
    draw_text(screen, "Pygame Edition  •  Use keyboard to fly", SMALL, MUTED,
              WIDTH/2, 650, True)


def draw_shop():
    draw_background(1/FPS, 0.12)
    draw_text(screen, "HANGAR & ARMORY", BIG, WHITE, WIDTH/2, 58, True)
    draw_text(screen, f"YOUR COINS: {save_data['coins']}", MED, GOLD, WIDTH/2, 112, True)
    ships_active = shop_tab == "ships"
    button(screen, pygame.Rect(210, 150, 220, 48), "SHIP SHOP",
           (35, 125, 190) if ships_active else (45, 55, 90))
    button(screen, pygame.Rect(470, 150, 220, 48), "WEAPON SHOP",
           (115, 75, 190) if not ships_active else (45, 55, 90))
    data = SHIP_DATA if ships_active else WEAPON_DATA
    owned = save_data["owned_ships"] if ships_active else save_data["owned_weapons"]
    selected = save_data["selected_ship"] if ships_active else save_data["selected_weapon"]
    for i, item in enumerate(data):
        col = i % 2
        row = i // 2
        rect = pygame.Rect(95 + col*365, 220 + row*175, 330, 150)
        rounded_panel(screen, rect, (17, 25, 54), (57, 82, 135), 16, 2)
        if ships_active:
            draw_ship(screen, rect.x+58, rect.y+72, 0.85, item["color"])
            draw_text(screen, item["name"], MED, WHITE, rect.x+112, rect.y+17)
            draw_text(screen, item["description"], SMALL, MUTED, rect.x+112, rect.y+49)
            draw_text(screen, f"HP {item['hp']}   SPEED {item['speed']:.1f}",
                      SMALL, CYAN, rect.x+112, rect.y+76)
            draw_text(screen, f"POWER {item['damage']}", SMALL, GOLD, rect.x+112, rect.y+98)
        else:
            draw_text(screen, ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ"][i], BIG,
                      [CYAN, GREEN, PURPLE, GOLD][i], rect.x+58, rect.y+66, True)
            draw_text(screen, item["name"], MED, WHITE, rect.x+112, rect.y+17)
            draw_text(screen, item["description"], SMALL, MUTED, rect.x+112, rect.y+49)
            draw_text(screen, f"DAMAGE x{item['damage']:.2f}", SMALL, CYAN,
                      rect.x+112, rect.y+79)
        if i in owned:
            label = "EQUIPPED" if i == selected else "EQUIP"
            color = GREEN if i == selected else BLUE
        else:
            label = f"BUY  {item['price']} COINS"
            color = GOLD if save_data["coins"] >= item["price"] else (70, 75, 92)
        button(screen, pygame.Rect(rect.x+112, rect.y+112, 190, 29), label, color,
               i in owned or save_data["coins"] >= item["price"], SMALL)
    button(screen, pygame.Rect(30, 25, 110, 42), "← BACK", (55, 65, 95), True, SMALL)
    if shop_message_timer > 0:
        draw_text(screen, shop_message, FONT, GREEN, WIDTH/2, 650, True)


def shop_click(pos):
    global shop_message, shop_message_timer
    if pygame.Rect(30, 25, 110, 42).collidepoint(pos):
        return "menu"
    if pygame.Rect(210, 150, 220, 48).collidepoint(pos):
        global shop_tab
        shop_tab = "ships"
        return "shop"
    if pygame.Rect(470, 150, 220, 48).collidepoint(pos):
        shop_tab = "weapons"
        return "shop"
    data = SHIP_DATA if shop_tab == "ships" else WEAPON_DATA
    owned_key = "owned_ships" if shop_tab == "ships" else "owned_weapons"
    selected_key = "selected_ship" if shop_tab == "ships" else "selected_weapon"
    for i, item in enumerate(data):
        col, row = i % 2, i // 2
        rect = pygame.Rect(95 + col*365, 220 + row*175, 330, 150)
        action_rect = pygame.Rect(rect.x+112, rect.y+112, 190, 29)
        if action_rect.collidepoint(pos):
            if i in save_data[owned_key]:
                save_data[selected_key] = i
                shop_message = item["name"] + " equipped!"
                play_sound("buy")
            elif save_data["coins"] >= item["price"]:
                save_data["coins"] -= item["price"]
                save_data[owned_key].append(i)
                save_data[selected_key] = i
                shop_message = item["name"] + " purchased and equipped!"
                play_sound("buy")
            else:
                shop_message = "Not enough coins!"
            shop_message_timer = 2.2
            save_game()
            return "shop"
    return "shop"


def draw_overlay(title, subtitle, buttons):
    shade = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
    shade.fill((2, 5, 18, 190))
    screen.blit(shade, (0, 0))
    panel = pygame.Rect(235, 190, 430, 330)
    rounded_panel(screen, panel, (16, 24, 52), (70, 110, 175), 22, 2)
    draw_text(screen, title, BIG, WHITE, WIDTH/2, 245, True)
    draw_text(screen, subtitle, FONT, MUTED, WIDTH/2, 300, True)
    for i, (label, color) in enumerate(buttons):
        button(screen, pygame.Rect(315, 350+i*58, 270, 46), label, color)


def draw_victory():
    draw_background(1/FPS, 0.08)
    draw_overlay("LEVEL CLEARED!", f"Level {level} complete  •  Bonus +{100+level*35} coins",
                 [("NEXT LEVEL  ▶", (35, 145, 110)),
                  ("HANGAR & SHOP", (105, 75, 185)),
                  ("MAIN MENU", (55, 75, 115))])


def draw_gameover():
    draw_background(1/FPS, 0.08)
    draw_overlay("SHIP DESTROYED", f"Level {level}  •  Score {score}  •  Dropped coins collected: {run_reward}",
                 [("TRY AGAIN  ↻", (35, 130, 190)),
                  ("HANGAR & SHOP", (105, 75, 185)),
                  ("MAIN MENU", (55, 75, 115))])


# ------------------------------ Main loop -----------------------------------
running = True
while running:
    dt = min(clock.tick(FPS) / 1000.0, 0.035)
    if shop_message_timer > 0:
        shop_message_timer -= dt

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            save_game()
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                if state == "game":
                    state = "pause"
                elif state == "pause":
                    state = "game"
                elif state == "shop":
                    state = "menu"
            if event.key == pygame.K_p:
                if state == "game":
                    state = "pause"
                elif state == "pause":
                    state = "game"
            if state == "gameover" and event.key == pygame.K_r:
                start_level(1)

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = event.pos
            if state == "menu":
                if pygame.Rect(320, 485, 260, 55).collidepoint(pos):
                    start_level(1)
                elif pygame.Rect(320, 550, 260, 48).collidepoint(pos):
                    state = "shop"
                    shop_tab = "ships"
            elif state == "shop":
                state = shop_click(pos)
            elif state == "pause":
                if pygame.Rect(315, 350, 270, 46).collidepoint(pos):
                    state = "game"
                elif pygame.Rect(315, 408, 270, 46).collidepoint(pos):
                    state = "shop"
                    shop_tab = "ships"
                elif pygame.Rect(315, 466, 270, 46).collidepoint(pos):
                    state = "menu"
            elif state == "victory":
                if pygame.Rect(315, 350, 270, 46).collidepoint(pos):
                    start_level(level+1)
                elif pygame.Rect(315, 408, 270, 46).collidepoint(pos):
                    state = "shop"
                    shop_tab = "ships"
                elif pygame.Rect(315, 466, 270, 46).collidepoint(pos):
                    state = "menu"
            elif state == "gameover":
                if pygame.Rect(315, 350, 270, 46).collidepoint(pos):
                    start_level(1)
                elif pygame.Rect(315, 408, 270, 46).collidepoint(pos):
                    state = "shop"
                    shop_tab = "ships"
                elif pygame.Rect(315, 466, 270, 46).collidepoint(pos):
                    state = "menu"

    if state == "game":
        update_game(dt)
        draw_game()
    elif state == "menu":
        draw_title()
    elif state == "shop":
        draw_shop()
    elif state == "pause":
        draw_game()
        draw_overlay("PAUSED", "Take a breath, pilot.",
                     [("▶  RESUME", (35, 135, 190)),
                      ("HANGAR & SHOP", (105, 75, 185)),
                      ("MAIN MENU", (55, 75, 115))])
    elif state == "victory":
        draw_victory()
    elif state == "gameover":
        draw_gameover()

    pygame.display.flip()

save_game()
pygame.quit()

5. Run the Game

Open Command Prompt in the project folder and run:

python space_shooter.py

Space Shooter Game Screenshot 1

Space Shooter Game Screenshot 2
Space Shooter Game Screenshot 3

Space Shooter Game Screenshot 4

The Space Shooter window should open. Click PLAY GAME to begin, or choose HANGAR & SHOP to view ships and weapons before playing.

6. Game Controls

Key / InputAction
W / Up ArrowMove up
S / Down ArrowMove down
A / Left ArrowMove left
D / Right ArrowMove right
Hold SpaceFire continuously
P or ESCPause or resume
MouseUse menu buttons and shop items
RRestart after game over

7. How the Game Works

Player and bullet system

The player position is updated from the keyboard state. Bullets are stored in lists and updated every frame using delta time. Holding Space fires according to the selected weapon's firing interval.

Enemies and boss

Enemies move down the screen with a slight horizontal wave and periodically fire at the player. After the required number of enemies has been defeated, the boss appears. The boss moves horizontally and fires a spread of projectiles.

Coins and upgrades

Defeated enemies drop coin pickups. Collect them by moving the spaceship close to the coins. Spend saved coins in the hangar to purchase and equip ships or weapons. Each ship has its own health, speed, and damage values, while weapons change projectile patterns and damage multipliers.

Save data

The game creates space_shooter_save.json beside the Python script. It stores coins, the best level, purchased ships and weapons, and the currently selected equipment. Keep this file if you want to preserve your progress.

8. Troubleshooting

  • No module named pygame: Run python -m pip install pygame using the same Python installation that runs the game.
  • The game closes immediately: Run it from Command Prompt using python space_shooter.py so any traceback remains visible.
  • Progress does not appear: Keep the JSON save file in the same folder as the Python script and make sure the folder is writable.
  • No sound: Check your computer's audio output. The program attempts to initialise the Pygame mixer; gameplay can still run if audio is unavailable.

9. Ideas for Further Improvements

After understanding this version, you can extend it with new enemy patterns, additional boss phases, power-up drops, a settings screen, more ship designs, a high-score table, or a difficulty selection menu. Add one feature at a time and test it before moving on.

Conclusion

Space Shooter is a hands-on example of how Python and Pygame can be used to build a complete arcade shooter. It combines movement, shooting, enemy behaviour, collision handling, rewards, shops, boss fights, sound, and persistent save data in one project. Run the game, explore the source code, and then experiment with your own ideas to make the game unique.

Frequently Asked Questions

Is Space Shooter made with Python?

Yes. The game is written in Python and uses Pygame for its window, input handling, drawing, timing, and sound playback.

Do I need separate images and sound files?

No. This version draws the spaceships, enemies, bullets, and background using Pygame shapes. It also generates short sound effects in memory.

Where is game progress saved?

Progress is stored in space_shooter_save.json in the same folder as the Python script.

Can I add more ships and weapons?

Yes. Add new entries to SHIP_DATA or WEAPON_DATA, then update the drawing or firing logic if the new item needs a special behaviour.

Suggested labels: Python, Pygame, Python Game Development, Space Shooter, 2D Game Development

Suggested search description: Build Space Shooter, a complete 2D space shooting game using Python and Pygame. Get the full source code and learn about enemies, weapons, coins, upgrades, boss fights, and saving progress.

Previous Post Next Post