最近我一直在尝试在 pygame 中以低分辨率、像素艺术风格构建游戏。
为了使我的游戏可用,我必须放大窗口,所以这是我为此开发的代码的基本示例,其中 SCALE 是整个窗口放大的值,而 temp_surf是在缩放函数放大图形之前我将图形传输到的表面。
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 窗口?有没有办法让我的代码更有效地运行?我愿意接受任何建议。
最佳答案
不要在每一帧中重新创建scaled_surf
。创建 pygame.Surface
这将是一项耗时的操作。创建scaled_surf
一次并持续使用它。
此外,我建议使用 pygame.transform.scale()
或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
关于python - 放大 pygame 中的窗口导致滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62737846/