ehmatthes / pcc_3e

Online resources for Python Crash Course, 3rd edition, from No Starch Press.
1.19k stars 478 forks source link

chapter_13/ending_the_game : Ship Limit Discrepancy in Alien Invasion Game #14

Open kavenyan opened 3 months ago

kavenyan commented 3 months ago

Hi, I noticed an issue with the self.ship_limit setting in the Alien Invasion game. When setting self.ship_limit = 3, the game only ends after four ship collisions instead of three.

Steps to Reproduce:

  1. Clone the repository and navigate to the chapter_13/ending_the_game directory.
  2. Run the game.
  3. Collide the ship with aliens four times.

Expected Result: The game should end after three collisions, as the self.ship_limit is set to 3.

Actual Result: The game ends after four collisions instead of three.

Analysis: The issue occurs because self.stats.ships_left is decremented after the first collision, meaning the game requires four collisions to reduce ships_left to 0.

Suggested Solution: To fix this issue, the _ship_hit method in alien_invasion.py should be adjusted to end the game after the third collision. Here is the suggested code modification:

def _ship_hit(self):
    """Respond to the ship being hit by an alien."""
    if self.stats.ships_left > 1:  # Adjusted condition
        # Decrement ships_left.
        self.stats.ships_left -= 1

        # Get rid of any remaining bullets and aliens.
        self.bullets.empty()
        self.aliens.empty()

        # Create a new fleet and center the ship.
        self._create_fleet()
        self.ship.center_ship()

        # Pause.
        sleep(0.5)
    else:
        self.stats.ships_left -= 1  # Decrement ships_left for the final collision
        self.game_active = False

I hope this helps to improve the game. Thank you for your great work on the book and the code!

Best regards, Kaven Yan