Reputation: 657
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?
Upvotes: 2
Views: 455
Reputation: 101072
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()
Upvotes: 2