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
Medium- Load
assets/images/laser.pngintolaser_imageand write theLaserclass above. - Make
lasers = pygame.sprite.Group(). - On a
KEYDOWNevent for Space, addLaser(player.rect.centerx, player.rect.top)tolasers. - Each frame,
lasers.update(), and drawlasersbefore 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()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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