简体   繁体   中英

PYGAME : Why does calling a function inside the game loop inside Game loop make my game lag?

I am making a simple game where enemies move around on the screen and we need to shoot them.I wanted to modularize my code so I wanted to replace the game loop logic with a function.But as soon as I do that, there's a drop in fps. Does calling a function inside while loop reduces the fps?

Without using functions,my game loop is:

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)

With the function:

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

But the moment I add this function,my game starts to lag due to reduction in FPS.Why does this happen?

It looks like you messed up your indentation. pygame.display.update() and everything after that should not be part of the for event... loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM