Lag when win.blit() background pygame

旧巷老猫 提交于 2021-01-29 22:13:20

问题


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()

回答1:


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)



来源:https://stackoverflow.com/questions/59312019/lag-when-win-blit-background-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!