im blitting a health bar onto the screen and seems like blitting the images on screen is causing the problem, i removed the for loop and whenever im making the player jump it seems like the performance is very very bad and when i remove the entire function the player was moving fast and jumping fast rather than being very very slow. What could be causing this issue? /(pls forget about the screens[0].blit that has nothing to do with the problem)
code:
def lives(lives_image1, lives_image2, x,y,lives_amount,lives_amount2, draw_lives):
if len(screens) >= 1:
if draw_lives:
for i in range(lives_amount2):
screens[0].blit(pygame.image.load(lives_image2),(x + pygame.image.load(lives_image2).get_width() * i,y))
for i in range(lives_amount):
screens[0].blit(pygame.image.load(lives_image1), (x + pygame.image.load(lives_image1).get_width() * i,y))
if lives_amount <= 0:
lives_amount = 0
return lives_amount
pass
>Solution :
Your application is slow because you are loading the images from the file every frame. Load the images once before the application loop, but blit them every frame:
def load_lives(lives_image)
return pygame.image.load(lives_image);
def lives(lives1_surf, lives2_surf, x, y, lives_amount, lives_amount2, draw_lives):
if len(screens) >= 1:
if draw_lives:
for i in range(lives_amount2):
screens[0].blit(lives2_surf,(x + lives2_surf.get_width() * i, y))
for i in range(lives_amount):
screens[0].blit(lives1_surf, (x + lives1_surf.get_width() * i, y))
if lives_amount <= 0:
lives_amount = 0
return lives_amount
lives1_surf = load_lives(lives_image1);
lives2_surf = load_lives(lives_image2);
while run:
# [...]
lives(lives1_surf, lives2_surf, ......)
# [...]
Note that pygame.image.load is a very expensive operation. This function needs to load the image file from disk and finally needs to the decode the image.