Menu
CoddyTech

Fire Lasers

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

The ship fires lasers straight up. A laser is a sprite that starts at the ship's nose, flies 10 pixels a frame, and removes itself once it is out of the window:

class Laser(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = laser_image
        self.rect = self.image.get_rect(midbottom=(x, y))

    def update(self):
        self.rect.y -= 10
        if self.rect.bottom < 0:
            self.kill()

The ship's nose is the middle of its top edge, so a new laser is Laser(player.rect.centerx, player.rect.top): its bottom middle sits on that point.

All lasers live in one group, lasers. Pressing Space adds one to it, in the event loop, so each press fires once. The group updates and draws them all; draw them before the ship, so they come out from under its nose.

challenge icon

Challenge

Medium
  1. Load assets/images/laser.png into laser_image and write the Laser class above.
  2. Make lasers = pygame.sprite.Group().
  3. On a KEYDOWN event for Space, add Laser(player.rect.centerx, player.rect.top) to lasers.
  4. Each frame, lasers.update(), and draw lasers before the ship.

Try it yourself

import pygame

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

ship_image = pygame.image.load("assets/images/ship.png").convert_alpha()


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

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.rect.x -= 6
        if keys[pygame.K_RIGHT]:
            self.rect.x += 6
        self.rect.clamp_ip(screen.get_rect())


player = Player()

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

    player.update()

    screen.fill((12, 14, 30))
    screen.blit(player.image, player.rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Sprites and Images

Practice on your own: Pygame playground