在 pygame 中扩大 window 导致延迟

Scaling up window in pygame causing lag

最近我一直在尝试在 pygame 中以低分辨率、像素艺术风格制作游戏。

为了让我的游戏可用,我必须扩大我的 window,所以这是我为此开发的代码的一个基本示例,其中 SCALE 是整个 window 被放大了,temp_surf 是我在缩放函数放大之前将我的图形 blit 到的表面。

import sys
import ctypes
import numpy as np
ctypes.windll.user32.SetProcessDPIAware()

FPS = 60
WIDTH = 150
HEIGHT = 50
SCALE = 2

pg.init()
screen = pg.display.set_mode((WIDTH*SCALE, HEIGHT*SCALE))
pg.display.set_caption("Example resizable window")
clock = pg.time.Clock()
pg.key.set_repeat(500, 100)

temp_surf = pg.Surface((WIDTH, HEIGHT))


def scale(temp_surf):
    scaled_surf = pg.Surface((WIDTH*SCALE, HEIGHT*SCALE))
    px = pg.surfarray.pixels2d(temp_surf)
    scaled_array = []
    for x in range(len(px)):
            for i in range(SCALE):
                    tempar = []
                    for y in range(len(px[x])):
                            for i in range(SCALE):
                                    tempar.append(px[x, y])
                    scaled_array.append(tempar)

    scaled_array = np.array(scaled_array)
    pg.surfarray.blit_array(scaled_surf, scaled_array)
    return scaled_surf


while True:
    clock.tick(FPS)
    #events
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                pg.quit()
                sys.exit()

    #update
    screen.fill((0,0,0))
    temp_surf.fill ((255,255,255))
    pg.draw.rect(temp_surf, (0,0,0), (0,0,10,20), 3)
    pg.draw.rect(temp_surf, (255,0,0), (30,20,10,20), 4)

    scaled_surf = scale(temp_surf)


    #draw
    pg.display.set_caption("{:.2f}".format(clock.get_fps()))
    screen.blit(scaled_surf, (0,0))

    
    pg.display.update()
    pg.display.flip()

pg.quit()

对于这个例子,延迟很小。但是,当我尝试在我的游戏中实现此代码时,fps 从 60 下降到大约 10。

有没有更有效的方法来放大我不知道的 pygame window?有什么方法可以让我的代码更有效地 运行 吗?我愿意接受任何建议。

不要在每一帧中重新创建 scaled_surf。创建 pygame.Surface 是一项耗时的操作。创建scaled_surf一次,持续使用。
此外,我建议使用专为此任务设计的 pygame.transform.scale() or pygame.transform.smoothscale()

scaled_surf = pg.Surface((WIDTH*SCALE, HEIGHT*SCALE))

def scale(temp_surf):
    pg.transform.scale(temp_surf, (WIDTH*SCALE, HEIGHT*SCALE), scaled_surf)
    return scaled_surf