尝试让精灵在一定时间后从屏幕上消失

问题描述:

我试图让我的爆炸图像在与外星人发生子弹碰撞后消失.我能够在碰撞发生时让爆炸出现,但之后似乎无法让它消失.我希望爆炸图像在大约 1 秒后消失.我知道它可能涉及游戏时钟和杀死方法?谢谢.

i am trying to get my explosion image to disappear after a bullet collision with an alien. i am able to get the explosion to appear when the collision happens but can't seem to get it to disappear afterwards. i would like the explosion image to disappear after maybe 1 second or so. i understand that it would possibly involve a game clock and a kill method? thank you.

import sys

import pygame

from settings import Settings
from ship import Ship
from bullet import Bullet
from alien import Alien
from pygame.sprite import Sprite 

class AlienInvasion:
    """overall class to manage game assets and behavior"""

    def __init__(self):
        """initialize that game and create game resources"""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))



        pygame.display.set_caption("Alien Invasion")

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self.all_sprites = pygame.sprite.Group()

        self._create_fleet()
        # set the background color
        

        # set the background color

        


    def run_game(self):
        """start the main loop for the game"""
        while True:
            
            

            self._check_events()
            self.ship.update()
            self._update_bullets()
            self._update_aliens()
            self._update_screen()
            

    
    
    def _check_events(self):
        """respond to keypress and mouse events"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)

            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)


    def _check_keydown_events(self, event):
        """respons to key presses"""

        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_SPACE:
            self._fire_bullet()

        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 _fire_bullet(self):
        """create a new bullet and add it to the bullet group"""
        if len(self.bullets) < self.settings.bullets_allowed:

            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)




    def _update_bullets(self):
        """update positions of the bullets and get rid of old bullets"""
        # update bullet position

        self.bullets.update()

        # get rid of bullets that have disappeared

        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)



        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, 
            True, True)

        for collision in collisions:

        
            expl = Explosion(collision.rect.center)
            self.all_sprites.add(expl)





    def _update_aliens(self):
        """update the positions of all the aliens in the fleet"""

        self._check_fleet_edges()
        self.aliens.update()




    def _create_fleet(self):
        
        alien = Alien(self)
        alien_place = alien.rect.x
        alien_other_place = alien.rect.y

        for row_number in range(4):
            for alien_number in range(9):
                alien = Alien(self)
                alien.rect.x = alien_place + 110 * alien_number
                alien.rect.y =  alien_other_place + 120 * row_number

                self.aliens.add(alien)



    def _check_fleet_edges(self):
        for alien in self.aliens:
           if alien.check_edges():
                self._change_fleet_direction()
                break              


    def _change_fleet_direction(self):
        for alien in self.aliens:
            alien.rect.y += self.settings.fleet_drop_speed    


        self.settings.fleet_direction *= -1

            

                
    


    def _update_screen(self):
        """update images on the screen and flip to the new screen"""
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets:
            bullet.draw_bullet()

        self.aliens.draw(self.screen)
        self.all_sprites.draw(self.screen)
        
        
      



        pygame.display.flip() 

class Explosion(Sprite):

    def __init__(self, center):
        super().__init__()

        
        self.image = pygame.image.load('images/explo.bmp')
        self.rect = self.image.get_rect()
        self.rect.center = center
        




if __name__ == '__main__':
    # make a game instance, and run the game
    ai = AlienInvasion()
    ai.run_game()

您必须为爆炸添加另一个组,并将新的 Explosion 对象也添加到该组:

You have to add another group for the explosions and to add the new Explosion object to this group, too:

class AlienInvasion:
    # [...]

    def __init__(self):
        # [...]

        self.explosions = pygame.sprite.Group()

    # [...]

    def _update_bullets(self):
        # [...]

        for collision in collisions:

            expl = Explosion(collision.rect.center)
            self.explosions.add(expl)
            self.all_sprites.add(expl)

获取当前时间(pygame.time.get_ticks())Explosion 对象被构造并且 kill() 一定时间跨度后更新方法中的对象:

Get the current time (pygame.time.get_ticks()) when the Explosion object is constructed and kill() the object in the update method after a certain time span:

class Explosion(Sprite):

    def __init__(self, center):
        super().__init__()

        self.image = pygame.image.load('images/explo.bmp')
        self.rect = self.image.get_rect()
        self.rect.center = center
        
        self.start_time = pygame.time.get_ticks() 

    def update(self):

        current_time = pygame.time.get_ticks() 
        timespan = 1000 # 1000 milliseconds = 1 second

        if current_time > self.start_time + timespan:
            self.kill()

不要忘记在AlienInvasion._update_bullets中调用self.explosions.update():

class AlienInvasion:
    # [...]

    def _update_bullets(self):
        # [...]

        self.explosions.update()