Star Patrol: a space shooter
Pilot your ship, blast waves of drones and dodge their shots. A template for any game with lots of moving objects.
- Difficulty
- Intermediate
- Source size
- 249 lines, 1 file
- Requires
- Python 3.10+, pygame-ce or pygame
- Assets
- None (drawn in code)
Controls
- Arrow keys WASD Fly
- Space (hold) Fire
- R Restart
On this page
What you'll learn#
- Organising many objects with
pygame.sprite.SpriteandGroup - Fire rate limits with a cooldown
groupcollideand pixel-perfectcollide_mask- Simple particle explosions
- Invincibility frames after being hit
Run it on your computer#
- Install Python 3.10 or newer and Pygame:
python -m pip install pygame-ce(orpygame). See the installation guides. - Download space_shooter.py into any folder.
- Open a terminal in that folder and run
python space_shooter.py.
No images or sounds are needed: everything is drawn in code. The game also runs unchanged in Pygame Online, because its loop uses asyncio to hand control to the browser each frame.
How it works#
Sprites and groups#
Every object (player, bullets, drones, sparks) is a Sprite subclass with an image, a rect and an update() method. Separate groups for each kind of object make collisions easy: pygame.sprite.groupcollide(self.drones, self.bullets, True, True) removes every drone that touched a bullet, and every bullet that hit something, in one call.
Procedural art#
The ship and drones are drawn with pygame.draw onto transparent Surfaces when the game starts, so there are no image files to manage. Swap in your own images by replacing make_ship() and make_drone().
Fire rate and enemy fire#
Holding Space fires only when cooldown has reached zero, which limits the player to about four shots per second. Each drone fires randomly, using its average fire_rate multiplied by dt, so behaviour is the same at any frame rate.
Fair hits#
Collisions between the ship and drones use pygame.sprite.collide_mask, which tests actual pixels rather than rectangles. After a hit the ship blinks and can't be hit again for two seconds.
Complete source code#
"""Star Patrol - a Pygame.net game project (a vertical space shooter).
Fly your ship, shoot the incoming drones and survive the waves.
Built with pygame.sprite.Sprite and Group, so it is a good template for
games with many moving objects.
Run it: pip install pygame-ce (or: pip install pygame)
python space_shooter.py
Controls: Arrow keys or WASD to move, Space to fire, R to restart.
License: MIT - https://pygame.net/licenses/
"""
import asyncio
import math
import random
import pygame
WIDTH, HEIGHT = 640, 480
FPS = 60
BG = (8, 12, 28)
WHITE = (230, 236, 247)
YELLOW = (244, 197, 49)
def make_ship():
img = pygame.Surface((36, 40), pygame.SRCALPHA)
pygame.draw.polygon(img, (157, 194, 255), [(18, 0), (34, 34), (18, 27), (2, 34)])
pygame.draw.polygon(img, (91, 147, 230), [(18, 8), (26, 30), (18, 25), (10, 30)])
pygame.draw.rect(img, YELLOW, (14, 33, 8, 6))
return img
def make_drone(color):
img = pygame.Surface((34, 26), pygame.SRCALPHA)
pygame.draw.ellipse(img, color, (0, 6, 34, 16))
pygame.draw.ellipse(img, (255, 255, 255), (10, 0, 14, 14))
pygame.draw.circle(img, (20, 20, 40), (17, 8), 4)
return img
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = make_ship()
self.rect = self.image.get_rect(midbottom=(WIDTH // 2, HEIGHT - 20))
self.pos = pygame.Vector2(self.rect.center)
self.cooldown = 0.0
self.invincible = 0.0
def update(self, dt, keys):
move = pygame.Vector2(
(keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or keys[pygame.K_a]),
(keys[pygame.K_DOWN] or keys[pygame.K_s]) - (keys[pygame.K_UP] or keys[pygame.K_w]),
)
if move.length_squared():
move.scale_to_length(300 * dt)
self.pos += move
self.pos.x = max(20, min(WIDTH - 20, self.pos.x))
self.pos.y = max(HEIGHT // 2, min(HEIGHT - 24, self.pos.y))
self.rect.center = (round(self.pos.x), round(self.pos.y))
self.cooldown = max(0.0, self.cooldown - dt)
self.invincible = max(0.0, self.invincible - dt)
class Bullet(pygame.sprite.Sprite):
def __init__(self, pos, vy, color):
super().__init__()
self.image = pygame.Surface((4, 12))
self.image.fill(color)
self.rect = self.image.get_rect(center=pos)
self.y = float(self.rect.y)
self.vy = vy
def update(self, dt, *_):
self.y += self.vy * dt
self.rect.y = round(self.y)
if self.rect.bottom < 0 or self.rect.top > HEIGHT:
self.kill()
class Drone(pygame.sprite.Sprite):
COLORS = [(232, 93, 82), (240, 140, 64), (170, 120, 230)]
def __init__(self, x, y, wave, rng):
super().__init__()
self.image = make_drone(self.COLORS[wave % 3])
self.rect = self.image.get_rect(center=(x, y))
self.base_x = x
self.y = float(y)
self.t = rng.uniform(0, math.tau)
self.speed = 40 + wave * 8
self.rng = rng
self.fire_rate = 0.25 + wave * 0.05 # shots per second, on average
def update(self, dt, *_):
self.t += dt * 2
self.y += self.speed * dt
self.rect.center = (round(self.base_x + math.sin(self.t) * 40), round(self.y))
class Spark(pygame.sprite.Sprite):
"""A short-lived particle used for explosions."""
def __init__(self, pos, rng):
super().__init__()
self.image = pygame.Surface((3, 3))
self.image.fill(rng.choice([YELLOW, (240, 140, 64), WHITE]))
self.rect = self.image.get_rect(center=pos)
self.pos = pygame.Vector2(pos)
self.vel = pygame.Vector2(rng.uniform(-1, 1), rng.uniform(-1, 1)) * rng.uniform(60, 220)
self.life = rng.uniform(0.3, 0.7)
def update(self, dt, *_):
self.life -= dt
self.pos += self.vel * dt
self.rect.center = (round(self.pos.x), round(self.pos.y))
if self.life <= 0:
self.kill()
class Game:
def __init__(self, seed=None):
self.rng = random.Random(seed)
self.font = pygame.font.Font(None, 30)
self.big = pygame.font.Font(None, 64)
self.stars = [[self.rng.randrange(WIDTH), self.rng.randrange(HEIGHT), self.rng.choice((20, 40, 70))] for _ in range(70)]
self.reset()
def reset(self):
self.player = Player()
self.players = pygame.sprite.GroupSingle(self.player)
self.bullets = pygame.sprite.Group()
self.enemy_bullets = pygame.sprite.Group()
self.drones = pygame.sprite.Group()
self.sparks = pygame.sprite.Group()
self.score = 0
self.lives = 3
self.wave = 0
self.state = "playing"
self.spawn_wave()
def spawn_wave(self):
self.wave += 1
count = min(5 + self.wave, 12)
for i in range(count):
x = 60 + (i % 6) * 100
y = -40 - (i // 6) * 60
self.drones.add(Drone(x, y, self.wave, self.rng))
def explode(self, pos, n=18):
for _ in range(n):
self.sparks.add(Spark(pos, self.rng))
def handle_event(self, event):
if event.type == pygame.KEYDOWN and event.key == pygame.K_r:
self.reset()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.state == "over":
self.reset()
def fire(self):
if self.player.cooldown == 0:
self.player.cooldown = 0.22
self.bullets.add(Bullet(self.player.rect.midtop, -520, YELLOW))
def update(self, dt, keys=None):
if keys is None:
keys = pygame.key.get_pressed()
for s in self.stars:
s[1] = (s[1] + s[2] * dt) % HEIGHT
self.sparks.update(dt)
if self.state != "playing":
return
self.players.update(dt, keys)
if keys[pygame.K_SPACE]:
self.fire()
self.bullets.update(dt)
self.enemy_bullets.update(dt)
self.drones.update(dt)
for drone in self.drones:
if self.rng.random() < drone.fire_rate * dt and drone.rect.top > 0:
self.enemy_bullets.add(Bullet(drone.rect.midbottom, 260, (232, 93, 82)))
if drone.rect.top > HEIGHT:
drone.kill()
hits = pygame.sprite.groupcollide(self.drones, self.bullets, True, True)
for drone in hits:
self.score += 10 * self.wave
self.explode(drone.rect.center)
if self.player.invincible == 0:
hit = pygame.sprite.spritecollideany(self.player, self.enemy_bullets) or \
pygame.sprite.spritecollideany(self.player, self.drones, pygame.sprite.collide_mask)
if hit:
hit.kill()
self.lives -= 1
self.explode(self.player.rect.center, 30)
self.player.invincible = 2.0
if self.lives <= 0:
self.state = "over"
self.player.kill()
if not self.drones:
self.spawn_wave()
def draw(self, surface):
surface.fill(BG)
for x, y, speed in self.stars:
shade = 90 + speed * 2
surface.fill((shade, shade, min(255, shade + 30)), (x, int(y), 2, 2))
self.drones.draw(surface)
self.bullets.draw(surface)
self.enemy_bullets.draw(surface)
if self.state == "playing" and (self.player.invincible == 0 or int(self.player.invincible * 10) % 2 == 0):
self.players.draw(surface)
self.sparks.draw(surface)
surface.blit(self.font.render(f"Score {self.score}", True, WHITE), (14, 12))
info = self.font.render(f"Wave {self.wave} Lives {self.lives}", True, WHITE)
surface.blit(info, (WIDTH - info.get_width() - 14, 12))
if self.state == "over":
t = self.big.render("Game over", True, YELLOW)
surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 20)))
h = self.font.render("Press Space or R to fly again", True, WHITE)
surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 30)))
async def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Star Patrol - Pygame.net")
clock = pygame.time.Clock()
game = Game()
running = True
while running:
dt = min(clock.tick(FPS) / 1000, 0.05)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
game.handle_event(event)
game.update(dt)
game.draw(screen)
pygame.display.flip()
await asyncio.sleep(0)
pygame.quit()
if __name__ == "__main__":
asyncio.run(main())The code is released under the MIT license: use it, change it and build on it. See licenses.
Ideas to extend it#
- Add a boss with a health bar every fifth wave.
- Add power-ups for triple shot and shields.
- Play sounds for shooting and explosions (sound and music).
- Make drones dive towards the player in formation.
- Add a title screen and a high score (menus).