Lesson 11: Firing Bullets + Sprite Groups (Matthes Ch 12 ยง8 pt 2)
Learning Intentions
- Manage many bullets using a Sprite Group.
- fire a bullet when the player presses Space.
Success Criteria
- Spacebar fires a bullet from my ship.
- Multiple bullets can fly up the screen at once.
- I can explain what a Sprite Group gives me for free.
๐ Do Now โ Error of the Day
What would go wrong if we used a plain Python list for bullets instead of pygame.sprite.Group? (Hint: think about draw + update calls.)
๐ I Do โ Teacher Demo
Live-code: self.bullets = pygame.sprite.Group(). Spacebar KEYDOWN โ self._fire_bullet(). Call self.bullets.update() and loop draws in _update_screen.
๐ค We Do โ Build Together
Class wires up the spacebar event together. Holding spacebar โ stream of bullets flies up the screen. Check: raise hand when yours works.
๐ You Do โ Your Turn
Tune bullet_speed + bullet_color. Watch what happens when bullets fly off the top (next lesson will fix this). Arcade quests cover Sprite Groups.
- In Game.__init__: self.bullets = pygame.sprite.Group()
- Extend _check_keydown_events: on K_SPACE, call self._fire_bullet()
- Write _fire_bullet(self) that creates a Bullet and adds it to self.bullets
- In _update_screen: self.bullets.update() + for bullet in self.bullets.sprites(): bullet.draw_bullet()
๐ฎ Practice Quests โ work through these
Loading practice quests for this lesson...
Three tiers โ pick yours
Support
_fire_bullet pre-written
Core
implement from scratch
Extension
custom bullet visuals
Extensions
- Customise bullet_color from settings (grey โ red โ whatever).
- Faster bullets: increase settings.bullet_speed.
๐ Exit Ticket โ Coding Journal
Journal: what's one thing pygame.sprite.Group gives you for free that a plain list wouldn't?
Evidence of Learning
Student can fire multiple bullets on spacebar โ they all fly up the screen.