1

I saw that when you wanna blit a .png image to your pygame display, the FPS drop from 60 to 20, is there a way to get around this, or maybe I did something wrong in my code ?

EDIT : I just tried .convert_alpha(), and it's going around 40 FPS now

menu = pygame.image.load("Ecran titre\\principal\\menu.png")
clock = pygame.time.Clock()

gameExit = False

while not gameExit :

    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            gameExit = True

    #gameDisplay.fill(0)

    gameDisplay.blit(background,(0,0)) # background is a jpeg image with .convert()

    gameDisplay.blit(menu,(0,0))
    pygame.display.update()
    clock.tick(60)
    pygame.display.set_caption("fps: " + str(clock.get_fps()))
Val_
  • 331
  • 1
  • 3
  • 13

2 Answers2

3

convert_alpha() is a good first step in managing images within pygame. It is also important to know that blitting an image to the surface is much slower than blitting a surface to a surface. I would pre-draw all images you plan on using onto their own surfaces. Then I would blit those surfaces to the screen. for example, the below code happens outside the game loop:

img_rect = get_image("my_image.png").get_rect()
img_surface = pygame.Surface((img_rect.width, img_rect.height), pygame.SRCALPHA)
img_surface.fill((0, 0, 0, 0))
img_surface.blit(get_image("my_image.png"), img_rect)

Then in the game loop:

gameDisplay.blit(img_surface, (x, y))

In general, you want to take as much as you possibly can out of the game loop. In this case, you are pre-processing the image and doing a faster surface-to-surface blit.

In the future, consider using cProfile for python. It will really help you nail down what exactly is making you code sluggish. Here is some good info on it:

Python getting meaningful results from cProfile

Community
  • 1
  • 1
The4thIceman
  • 3,709
  • 2
  • 29
  • 36
0

First of all, you should use .convert_alpha(), like "The4thIceman" stated in a previous answer. That can really speed up your code, and it should be used on all loaded images.

Second of all, you should use multithreading. Multithreading is the art of making your programs run multiple things at the same time. Python has a built in "thread" library (though I think it is "_thread" in Python 3) that allows you to do this easily.

Refer to https://docs.python.org/3/library/_thread.html

Douglas
  • 1,304
  • 10
  • 26