trying to get sprite to disappear from screen after certain amount of time

橙三吉。 提交于 2021-01-28 19:51:59

问题


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


回答1:


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)

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

Do not forget to invoke self.explosions.update() in AlienInvasion._update_bullets:

class AlienInvasion:
    # [...]

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

        self.explosions.update()


来源:https://stackoverflow.com/questions/62614228/trying-to-get-sprite-to-disappear-from-screen-after-certain-amount-of-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!