微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pygame努力使物体出现

如何解决Pygame努力使物体出现

我试图使自己熟悉Python,并尝试使用Pygame制作“外星入侵者”风格的游戏。我能够导入船的图像并左右移动。

现在我正试图在每当按下空格键时向船上发射子弹,但是当我按下时却什么也没发生。

这是我的主程序,可以在按键时触发行为:

while run:
  
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        
    keys = pygame.key.get_pressed()
    
    #calls a function that increments the x coordinate of the ship
    if keys[pygame.K_RIGHT]:
        ship.updateRight()
    #calls a function that decrements the x coordinate of the ship    
    if keys[pygame.K_LEFT]:
        ship.updateLeft()
    #calls a function that updates the screen to create a bullet  
    if keys[pygame.K_SPACE]:
        new_bullet = Bullet(ai_settings,screen,ship)
        bullets.add(new_bullet)
    
    bullets.update()                
    gf.update_screen(ai_settings,ship,bullets)

pygame.quit()
sys.exit()

当按下空格键时,将调用Bullet类中的以下功能

class Bullet(Sprite):
    
    def __init__ (self,ai_settings,ship):
        """Create a bullet object at the ship's current position"""
        super().__init__()
        self.screen = screen
        
        #create bullet rect (0,0) and then set the correct position
        self.rect = pygame.Rect(0,ai_settings.bullet_width,ai_settings.bullet_height)
        self.rect.centerx = ship.rect.centerx
        self.rect.top = ship.rect.top
        
        #store the bullet's position as a decimal value
        self.y = float(self.rect.y)
        
        self.color = ai_settings.bullet_color
        self.speed_factor = ai_settings.bullet_speed_factor
        
    def update(self):
        """Move the bullet up the screen"""
        #update the decimal position of the bullet 
        self.y -= self.speed_factor
        self.rect.y = self.y
        
    def draw_bullet(self):
        """Draw the bullet to the screen."""
        pygame.draw.rect(self.screen,self.color,self.rect)'''

最后是在主循环中调用的“ update_screen”功能(它包括飞船的其他一些更新):

def update_screen(ai_settings,bullets):
   screen.fill(ai_settings.bg_color)
   #ship.blitme()
   pygame.display.flip()
   for bullet in bullets.sprites():
       bullet.draw_bullet()

如果有人对为什么没有显示项目符号有任何想法,请提供帮助!由于我对Python还是很陌生,所以还无法弄清楚这一点。

非常感谢您!

解决方法

正如@Rabbid76所说,X0 = [0,0]必须在之后pygame.display.flip()

原因是,当您“更新”屏幕时,到目前为止绘制的所有内容都会放到屏幕上。简单吧? 在for bullet in bullets.sprites(): bullet.draw_bullet之后放置某些内容时,它不会在运行时绘制它。另外,当您用pygame.display.flip()重新填充屏幕时,在绘制项目符号后,新的屏幕将它们全部覆盖。因此,它永远不会出现。

因此,ai_settings.bg_color必须为:

update_screen()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。