Skip to content

Commit

Permalink
"storing bullets in a group" s248
Browse files Browse the repository at this point in the history
  • Loading branch information
ntkfi committed Feb 19, 2024
1 parent a171763 commit 035abf6
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 11 deletions.
28 changes: 18 additions & 10 deletions alien_invasion.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,26 @@ def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()

elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True

self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
self._check_keyup_events(event)

def _check_keydown_events(self, event):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_q:
sys.exit()

def _check_keyup_events(self, event):
"""Respond to key releases."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False

def _update_screen(self):
"""Update images on the screen, and flip to the new screen."""
Expand Down
32 changes: 32 additions & 0 deletions bullet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
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.
self.rect = pygame.Rect(0, 0, self.settings.bullet_width,
self.settings.bullet_height)
self.rect.midtop = ai_game.ship.rect.midtop

# Store the bullet's position as a float.
self.y = float(self.rect.y)

def update(self):
"""Move the bullet up the screen."""
# Update the exact position of the bullet.
self.y -= self.settings.bullet_speed
# Update the rect position.
self.rect.y = self.y

def draw_bullet(self):
"""Draw the bullet to the screen."""
pygame.draw.rect(self.screen, self.color, self.rect)
8 changes: 7 additions & 1 deletion settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,10 @@ def __init__(self):
self.bg_color = (230, 230, 230)

# Ship settings
self.ship_speed = 5
self.ship_speed = 5

# Bullet settings
self.bullet_speed = 2.0
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60, 60)

0 comments on commit 035abf6

Please sign in to comment.