Fire Lasers
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 31 of 39.
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
MediumFire a laser with each tap of Space.
- Load
assets/images/laser.pngintolaser_image, write theLaserclass above, and makelasers = pygame.sprite.Group(). - On a
KEYDOWNevent for Space, addLaser(player.rect.centerx, player.rect.top)tolasers. - Each frame,
lasers.update(), and drawlasersbefore the ship.
Press Play and tap Space: lasers fly up. 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()
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()
All lessons in Sprites and Images
Practice on your own: Pygame playground