【问题标题】:PYGAME : Why does calling a function inside the game loop inside Game loop make my game lag?PYGAME:为什么在游戏循环内调用游戏循环内的函数会使我的游戏滞后?
【发布时间】:2021-01-12 10:38:46
【问题描述】:

我正在制作一个简单的游戏,其中敌人在屏幕上四处移动,我们需要射击他们。我想模块化我的代码,所以我想用一个函数替换游戏循环逻辑。但是一旦我这样做了, fps下降了。在while循环中调用函数会降低fps吗?

不使用函数,我的游戏循环是:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            crosshair.shoot()
    
        pygame.display.update()
        #blit bg
        displaysurf.blit(background,(0,0))
        #render group of sprites
        target_group.draw(displaysurf)
        crosshair_group.draw(displaysurf)
        #call the update methods
        crosshair_group.update()
        target_group.update()
        #display fps
        #print(clock.get_fps())
        #restrict to 60frames drawing per second
        clock.tick(60)

附带功能:

def first_level():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            crosshair.shoot()
    
        pygame.display.update()
        #blit bg
        displaysurf.blit(background,(0,0))
        #render group of sprites
        target_group.draw(displaysurf)
        crosshair_group.draw(displaysurf)
        #call the update methods
        crosshair_group.update()
        target_group.update()
        #display fps
        #print(clock.get_fps())
        #restrict to 60frames drawing per second
        clock.tick(60)
while True: 
        first_level()

但是在我添加这个功能的那一刻,我的游戏由于FPS降低而开始延迟。为什么会发生这种情况?

【问题讨论】:

    标签: python python-3.x pygame pygame-surface pygame-tick


    【解决方案1】:

    看起来你搞砸了你的缩进。 pygame.display.update() 以及之后的所有内容都不应成为 for event ... 循环的一部分。

    def first_level():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                crosshair.shoot()
        
        pygame.display.update()
        #blit bg
        displaysurf.blit(background,(0,0))
        #render group of sprites
        target_group.draw(displaysurf)
        crosshair_group.draw(displaysurf)
        #call the update methods
        crosshair_group.update()
        target_group.update()
        #display fps
        #print(clock.get_fps())
        #restrict to 60frames drawing per second
        clock.tick(60)
    
    while True: 
        first_level()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多