The Patrol Ship
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 29 of 36.
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
Medium- Load
assets/images/ship.pngintoship_image. - Write
class Player(pygame.sprite.Sprite): imageship_image, Rect with its bottom middle at(320, 470), and anupdatethat moves it 6 pixels a frame with Left and Right and clamps it to the window. - Make
player = Player(); each frame callplayer.update()and blitplayer.imageatplayer.rectafter the fill.
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
4Sprites and Groups
The Sprite ClassGroupsRemove with kill()Catch with spritecollideGroup Against Group7Star Patrol
The Patrol ShipFire Lasers3Classes for Game Objects
Your First ClassMethodsSelf Is the ObjectA List of ObjectsObjects with ImagesA SubclassPractice on your own: Pygame playground