gpt4 book ai didi

python - 放大pygame中的窗口导致滞后

转载 作者:行者123 更新时间:2023-12-04 09:33:01 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Set the width and height of a pygame surface

(1 个回答)


11 个月前关闭。




最近我一直在尝试在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com