win.blit() 后台 pygame 时滞后 [英] Lag when win.blit() background pygame

查看:125
本文介绍了win.blit() 后台 pygame 时滞后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的游戏帧率有问题.我已将其设置为 60,但它只能达到 ~25fps.在显示背景之前这不是问题(仅使用 win.fill(WHITE) 就可以了).这里有足够的代码来重现:

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

推荐答案

确保背景 Surface 与显示 Surface 具有相同的格式.使用 convert() 创建一个具有相同像素格式的 Surface.这应该会提高性能,当背景是 blit 显示时,因为格式是兼容的,并且 blit 不必进行隐式转换.

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

<小时>

此外,创建字体一次就足够了,而不是每次绘制文本时.将 font = pygame.font.SysFont('Comic Sans MS', 25, True) 移动到应用程序的开头(在 pygame.init() 之后和之前的某个位置)主应用程序循环)


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)

这篇关于win.blit() 后台 pygame 时滞后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆