【问题标题】:trying to get sprite to disappear from screen after certain amount of time试图让精灵在一定时间后从屏幕上消失
【发布时间】:2020-06-27 18:51:06
【问题描述】:

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

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()

【问题讨论】:

    标签: python pygame


    【解决方案1】:

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

    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)
    

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

    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()
    

    【讨论】:

    • 非常感谢,这很棒,而且效果很好。我只是想知道我自己的澄清为什么必须为爆炸添加第二组以及为什么 kill() 方法不能只在 all_sprites() 组上工作?
    • @SarabSingh 1. 您必须添加组self.explosions,因为您想为爆炸而不是所有精灵调用updateself.explosions 仅包含 Explosion 对象。请注意,并非所有精灵都有update 方法。 2.kill()从所有组中删除精灵。
    • 我明白了,这对我来说很有意义。非常感谢您的所有帮助。非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 2019-08-31
    相关资源
    最近更新 更多