1

I want to make a (a bit bigger) game in PyGame, but even with this simple code I just get arround 10 fps instead of 60? Here's the code:

import pygame

res = 1280,720
display = pygame.display.set_mode(res, pygame.RESIZABLE)
pygame.display.set_caption("Test")


background = pygame.transform.smoothscale(pygame.image.load("Background.png"), res)
a = 0
while True:
    pygame.time.Clock().tick(60)
    display.fill((0,0,0))
    a += 10

    display.blit(background, (0,0)) #Without this line: arround 20 fps

    pygame.draw.rect(display,(255,0,0), (a,8,339,205))

    pygame.display.update()

pygame.quit()

What am I doing wrong?

Thank you!

Frostie
  • 77
  • 2
  • 10

1 Answers1

2

Try the following optimizations:

  • Use the convert() method on your image pygame.image.load("Background.png").convert()). This makes the animation about 5 times faster.

  • Instead of re-blitting entire background every frame, only update the changed parts of the screen.

  • You don't need to clear the screen before drawing the background.

  • Use the same Clock instance every frame.

Here's the code:

import pygame

pygame.init()
res = (1280, 720)
display = pygame.display.set_mode(res, pygame.RESIZABLE)
pygame.display.set_caption("Test")

background = pygame.transform.smoothscale(pygame.image.load(r"E:\Slike\Bing\63.jpg").convert(), res)
a = 0
clock = pygame.time.Clock()

display.blit(background, (0, 0))
pygame.display.update()
while True:
    clock.tick(60)
    rect = (a,8,339,205)
    display.blit(background, rect, rect) # draw the needed part of the background
    pygame.display.update(rect) # update the changed area
    a += 10
    rect = (a,8,339,205)
    pygame.draw.rect(display, (255,0,0), rect)
    pygame.display.update(rect) # update the changed area
Maximouse
  • 4,170
  • 1
  • 14
  • 28
  • Your first two points are valid for this specific example, but they're impossible to do in more complex games. Pygame should be fast enough to run 60fps in full screen even with multiple sprites and backgrounds with a computer like OP's. While your tips certainly help, they don't solve the root of the problem, they only lessen its effects. – Nearoo Dec 06 '18 at 08:36
  • Original: 20 FPS With convert(): 110 FPS Without clearing the screen: 220 FPS When only updating the changed area: clock.get_fps() returns infinity – Maximouse Dec 06 '18 at 09:43
  • (Now I changed my answer.) – Maximouse Dec 06 '18 at 09:55