Shooting Bullets
Now let’s add the ability to shoot bullets. We’ll write code that fires a bullet,
which is represented by a small rectangle, when the player presses the space-
bar. Bullets will then travel straight up the screen until they disappear off
the top of the screen.
Adding the Bullet Settings
At the end of the __init__() method, we’ll update settings.py to include the
values we’ll need for a new Bullet class:
settings.py def __init__(self):
--snip--
# Bullet settings
self.bullet_speed = 2.0
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60, 60)
These settings create dark gray bullets with a width of 3 pixels and a
height of 15 pixels. The bullets will travel slightly faster than the ship.
Creating the Bullet Class
Now create a bullet.py file to store our Bullet class. Here’s the first part of
bullet.py:
bullet.py import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""A class to manage bullets fired from the ship."""
def __init__(self, ai_game):
"""Create a bullet object at the ship's current position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.color = self.settings.bullet_color
# Create a bullet rect at (0, 0) and then set correct position.
1 self.rect = pygame.Rect(0, 0, self.settings.bullet_width,
self.settings.bullet_height)
2 self.rect.midtop = ai_game.ship.rect.midtop
# Store the bullet's position as a float.
3 self.y = float(self.rect.y)
The Bullet class inherits from Sprite, which we import from the pygame
.sprite module. When you use sprites, you can group related elements in
your game and act on all the grouped elements at once. To create a bullet
instance, __init__() needs the current instance of AlienInvasion, and we call
A Ship That Fires Bullets 247