I have this method that manages the Last Bullet game mode in my game.
It keeps track of how many enemies are alive, the number of bullets that every player has available and the number of flying bullets and, if there are no remaining bullets, flying bullets and more than one enemy, the player becomes inactive. But here is the problem, regardless of how many enemies are on the screen, if the player keeps shooting, the remaining bullets are going negative and as long as there are flying bullets on screen, the player stays active, which I don t want to happen. Any ideas of how can I prevent this scenario from happening? I have a variable bullets_allowed
in the game that increases or decreases the number of bullets that the player can have on the screen and I know that setting that to always be 1 would solve my issue but I don't want to be able to shoot only 1 at a time.
def last_bullet(self, thunderbird, phoenix):
"""Starts the Last Bullet game mode in which the players must fight aliens
but they have a limited number of bullets, when a player remains with no bullets
he dies, when both players are out of bullets, the game is over."""
aliens_remaining = len(self.game.aliens.sprites())
flying_thunder_bullets = sum(
bullet.rect.left > 0
and bullet.rect.right < self.settings.screen_width
and bullet.rect.top > 0
and bullet.rect.bottom < self.settings.screen_height
for bullet in self.game.thunderbird_bullets.sprites()
)
flying_phoenix_bullets = sum(
bullet.rect.left > 0
and bullet.rect.right < self.settings.screen_width
and bullet.rect.top > 0
and bullet.rect.bottom < self.settings.screen_height
for bullet in self.game.phoenix_bullets.sprites()
)
if thunderbird.remaining_bullets <= 0 and flying_thunder_bullets <= 0 \
and aliens_remaining > 0:
thunderbird.state.alive = False
if phoenix.remaining_bullets <= 0 and flying_phoenix_bullets <= 0 \
and aliens_remaining > 0:
phoenix.state.alive = False
if all(not player.state.alive for player in [thunderbird, phoenix]):
self.stats.game_active = False
I solved the problem by returning early from the _fire_bullet
method that I have in my game, when a player has no remaining bullets.
def _fire_bullet(self, bullets, bullets_allowed, bullet_class, num_bullets, ship):
"""Create new player bullets."""
# Create the bullets at and position them correctly as the number of bullets increases
if ship.remaining_bullets <= 0:
return
if len(bullets) < bullets_allowed:
offset_amount = 25
for i in range(num_bullets):
new_bullet = bullet_class(self)
bullets.add(new_bullet)
offset_x = offset_amount * (i - (num_bullets - 1) / 2)
offset_y = offset_amount * (i - (num_bullets - 1) / 2)
new_bullet.rect.centerx = ship.rect.centerx + offset_x
new_bullet.rect.centery = ship.rect.centery + offset_y
if self.settings.gm.last_bullet:
ship.remaining_bullets -= 1
self.score_board.render_bullets_num()