且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在pygame中执行for循环后图像未保留在屏幕上

更新时间:2022-12-06 17:45:03

问题是由 draw_reaction()函数仅在绝对时间内绘制 player_image 引起的子弹与障碍物碰撞.因此它只显示一帧图像(每秒60分之一秒),但是在下一个循环中不再发生碰撞(将子弹移除),因此永远不会绘制图像.

The problem is caused by the draw_reaction() function only drawing the player_image during the absolute-time the bullet is colliding with a block. So it shows the image for a single frame (One 60th of a second), but then on the next loop the collision is no longer occurring (the bullet is removed), so it is never drawn.

有很多方法可以解决此问题,但是我不确定显示此位图的目的,因此它们可能没有应有的帮助.

There are a number of ways around this, but I'm not sure of the purpose of showing this bitmap, so maybe they're not as helpful as they should be.

最简单的解决方法是将播放器图像转换为精灵,然后在击中子弹时将其简单地添加到现有的 all_sprites_list 中,然后再将其删除(或如何删除)一切正常).

The easiest fix is to probably turn the player image into a sprite, and simply add it to the existing all_sprites_list when the bullet-hit triggers, and then take it away some time later (or how ever it should work).

class PlayerShip( pygame.sprite.Sprite ):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load( "player.png" ) #.convert() 
        self.rect  = self.image.get_rect()
        self.rect.topleft = ( 60, 48 ) 

然后稍后:

player_sprite = PlayerShip()

def draw_reaction():
    for bullet in bullet_list:
        block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
        for block in block_hit_list:
            # TODO: ensure it's not showing already
            all_sprites_list.add( player_sprite )      # add the player sprite 
            break                                      # only add once

基于注释更新的代码段