Låne Book
Låne Book

Reputation: 83

Lag when win.blit() background pygame

I'm having trouble with the framerate in my game. I've set it to 60 but it only goes to ~25fps. This was not an issue before displaying the background (was fine with only win.fill(WHITE)). Here is enough of the code to reproduce:

import os, pygame
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50, 50)
pygame.init()

bg = pygame.image.load('images/bg.jpg')

FPS = pygame.time.Clock()
fps = 60

WHITE = (255, 255, 255)
BLUE = (0, 0, 255)

winW = 1227
winH = 700
win = pygame.display.set_mode((winW, winH))
win.fill(WHITE)
pygame.display.set_icon(win)


def redraw_window():

    #win.fill(WHITE)
    win.blit(bg, (0, 0))

    win.blit(text_to_screen('FPS: {}'.format(FPS.get_fps()), BLUE), (25, 50))

    pygame.display.update()


def text_to_screen(txt, col):
    font = pygame.font.SysFont('Comic Sans MS', 25, True)
    text = font.render(str(txt), True, col)
    return text


run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    redraw_window()

    FPS.tick(fps)

pygame.quit()

Upvotes: 2

Views: 813

Answers (2)

ThuanCD
ThuanCD

Reputation: 1

Instead use screen.blit(pygame.image.load(picture.png)) Just image = pygame.image.load(picture.png) then screen.blit(image)

( if you keep loading your pictures continuously it will get lag )

Upvotes: 0

Rabbid76
Rabbid76

Reputation: 210878

Ensure that the background Surface has the same format as the display Surface. Use convert() to create a Surface that has the same pixel format. That should improve the performance, when the background is blit to the display, because the formats are compatible and blit do not have to do an implicit transformation.

bg = pygame.image.load('images/bg.jpg').convert()

Furthermore, it is sufficient to create the font once, rather than every time when a text is drawn. Move font = pygame.font.SysFont('Comic Sans MS', 25, True) to the begin of the application (somewhere after pygame.init() and before the main application loop)

Upvotes: 3

Related Questions