【问题标题】:Python Pygame codes running very slow when imported from another file从另一个文件导入时,Python Pygame 代码运行非常慢
【发布时间】:2019-12-27 18:46:15
【问题描述】:

我对 python 比较陌生,所以如果答案很明显,请原谅我。

def create_fleet(ai_settings, screen, aliens):
    """Create the horizontal Alien fleet"""
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    available_x = ai_settings.screen_width - alien_width
    num_aliens_x = int(available_x / ( 2 * alien_width))

    for alien_number_x in range(num_aliens_x):
        alien = Alien(ai_settings, screen)
        # define the starting point of each alien
        alien.x = alien_width + 2 * alien_width * alien_number_x
        alien.rect.x = alien.x
        aliens.add(alien)

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

这是主游戏文件:

def run_game():

ai_settings = Settings()


pygame.init()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("ALIEN INVASION")
bullets = Group()
aliens = Group()



ship = Ship(screen, ai_settings)
while True:
    gf.check_event(ai_settings, screen, ship, bullets)
    ship.update()
    bullets.update()
    gf.remove_old_bullets(bullets) 

    **gf.create_fleet(ai_settings, screen, aliens)
    gf.update_screen(ai_settings, screen, ship, bullets, aliens)**

run_game()

每当我将这些函数导入主游戏文件并运行它会抓取的游戏时,但当代码直接在主游戏文件上运行时,它会正常运行。请就如何在导入时使其正常工作提出建议。

已编辑:我添加了主游戏文件,粗体部分是我使用导入代码的地方,这给我带来了问题。谢谢

【问题讨论】:

  • 您能否添加您的主脚本,以便我们可以重现该问题?
  • 谢谢。我刚做了。

标签: python pygame


【解决方案1】:

我已经能够解决它。函数 gf.create_fleet 不应该在 while 循环中,因为它将不断添加到同一位置的组中,并且 gf update_screen 必须在同一点绘制所有这些,这是一个严重的问题,让我的编程爬行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多