Menu
CoddyTech

The Patrol Ship

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 30 of 39.

Time to build a whole game: Star Patrol. Waves of enemy ships fly down from the top. Your ship patrols the bottom of the window, moving left and right and firing lasers up. Destroy every wave to win; let three enemies through or crash into them and the game is over.

Every object in the game will be a sprite: the player, its lasers, the enemies and their explosions. The player comes first, as in chapter 4:

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = ship_image
        self.rect = self.image.get_rect(midbottom=(320, 470))

Load ship_image once, after the window. Its update moves the Rect with the arrows and keeps it inside the window. The main loop calls player.update() and draws the ship.

This chapter grows the same program lesson by lesson, so keep the names the tasks give: the checks find the game's parts by them.

challenge icon

Challenge

Medium

Start Star Patrol with the player's ship.

  1. Load assets/images/ship.png into ship_image.
  2. Write class Player(pygame.sprite.Sprite): image ship_image, Rect with its bottom middle at (320, 470), and an update that moves it 6 pixels a frame with Left and Right and clamps it to the window.
  3. Make player = Player(); call player.update() and blit it each frame.

Press Play and hold the arrows: the ship patrols the bottom. Then Check.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Star Patrol")
clock = pygame.time.Clock()

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

    screen.fill((12, 14, 30))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground