消灭后外星人不会出现在外星人入侵中

问题描述 投票:0回答:1

我正在开发一款玩家可以消灭外星人的游戏,但我遇到了障碍。当我设法消灭所有外星人后,新的外星人不会再出现,这确实影响了游戏玩法。

我尝试自己解决这个问题,甚至向 ChatGPT 寻求帮助,但我仍然陷入困境。如果有人经历过类似的事情或对如何解决此问题有任何建议,我将非常感谢您的见解!

预先感谢您的帮助!

`-alien_invasion.py

     import sys
     from time import sleep
     import pygame
     from settings import Settings
     from game_stats import GameStats
     from button import Button
     from ship import Ship
     from bullet import Bullet
     from alien import Alien

class AlienInvasion:

    def __init__(self):
        pygame.init()

        # Start AI in active
        self.game_active = False
        self.clock = pygame.time.Clock()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        
        # Make play button
        self.play_button = Button(self, "Play")
        
        pygame.display.set_caption("Alien Invasion")
        # Create an instance to store game stats
        self.stats = GameStats(self)

        self.ship = Ship(self)
        self.ship.rect.y = self.settings.screen_height - self.ship.rect.height  # Set ship's vertical position

        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()
    
    def _create_fleet(self):
        # Make alien
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size

        current_x, current_y = alien_width, alien_height
        while current_y < (self.settings.screen_height - 3 * alien_height):
            while current_x < (self.settings.screen_width - 2 * alien_width):
                self._create_alien(current_x, current_y)
                print(f"Creating alien at ({current_x}, {current_y})")
                current_x += 2 * alien_width
            # Finished a row
            current_x = alien_width
            current_y += 2 * alien_height

    def _create_alien(self, x_position, y_position):
        # Create an alien            
        new_alien = Alien(self)
        new_alien.x = x_position
        new_alien.rect.x = x_position
        new_alien.rect.y = y_position
        self.aliens.add(new_alien)
    
    def _check_fleet_edges(self):
        # Respond appropriately to aliens that reach edge
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break
    
    def _change_fleet_direction(self):
        # Drop entire fleet and change direction
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1    

    def run_game(self):
        while True:
            self._check_events()

            if self.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()


            self._update_screen()
            self.clock.tick(60)

    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
    
    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.game_active:
            # Reset game settings
            self.settings.initialize_dynamic_settings()
            
            # Hide mouse cursor
            pygame.mouse.set_visible(False)

            # Reset the game stats:
            self.stats.reset_stats()
            self.game_active = True

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

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

    def _check_keydown_events(self, event):
        # Respond to keypress
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        if event.key == pygame.K_UP:
            self.ship.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.ship.moving_down = True
        elif event.key == pygame.K_q:
            sys.exit() 
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    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
        if event.key == pygame.K_UP:
            self.ship.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.ship.moving_down = False

    def _update_aliens(self):
        self.aliens.update()
        self._check_fleet_edges()

        # Look for alien-ship collisions
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # Look for aliens hitting the bottom
        self._check_aliens_bottom()

    def _fire_bullet(self):
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)
    
    def _update_bullets(self):
        """Update position of bullets and get rid of old bullets."""
        # Update bullet positions.
        self.bullets.update()
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()
    
    def _check_bullet_alien_collisions(self):
        # Check for any bullets hitting aliens
        collisions = pygame.sprite.groupcollide(
                self.bullets, self.aliens, True, True) 

    def _update_screen(self):
        self.screen.fill(self.settings.bg_color)
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.ship.blitme()
        self.aliens.draw(self.screen)

        # Draw the play button if the game is inactive
        if not self.game_active:
            self.play_button.draw_button()

        pygame.display.flip()

    def _ship_hit(self):
        # Respond to the ship being hit
        if self.stats.ships_left > 0:
            # Decrement ships left
            self.stats.ships_left -= 1

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

            # Create a new fleet
            self._create_fleet()

            self.ship.rect.y = self.settings.screen_height - self.ship.rect.height  # Keep the ship at the bottom

            # Pause
            sleep(0.5)
        else:
            self.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        # Check if any aliens have reached the bottom
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= self.settings.screen_height:
                # Treat this as if the ship got hit
                self._ship_hit()
                break

if __name__ == "__main__":
    ai = AlienInvasion()
    ai.run_game()`

alien.py

输入 import Any 导入pygame 从 pygame.sprite 导入 Sprite

class Alien(Sprite):

    def __init__(self, ai_game):
        #initialize the alien
        super().__init__()
        self.screen = ai_game.screen
        self.settings =ai_game.settings

        #load image of alien
        try:

            self.image = pygame.image.load(r'C:\Users\ianwo\OneDrive\Documentos\Vscode\alien_invasion\images\alien.png')
            self.rect = self.image.get_rect(50,50)
        except pygame.error as e:
            print(f" failed to load {e}")

        #start each new alien
        self.rect.x =self.rect.width
        self.rect.y =self.rect.height

        #store the alien exact position
        self.x =float(self.rect.x)

    def check_edges(self):
        #return true if alien is at edge
        screen_rect = self.screen.get_rect()
        return (self.rect.right >= screen_rect.right) or (self.rect.left <= 0)

    def update(self):
        #move alient to the right
        self.x += self.settings.alien_speed *self.settings.fleet_direction
        self.rect.x = self.x`
python
1个回答
0
投票

我没有在任何地方看到你在跟踪(或计算)仍然活着的外星人数量,也没有在任何地方看到你在检查外星人数量达到 0。

如果你想在所有外星人都消失后生成一支新舰队,你需要检查该条件。

© www.soinside.com 2019 - 2024. All rights reserved.