【问题标题】:Scaling up window in pygame causing lag [duplicate]在pygame中扩大窗口导致滞后[重复]
【发布时间】:2020-10-25 12:03:42
【问题描述】:

最近我一直在尝试在 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 窗口?有没有办法让我的代码更有效地运行?我愿意接受任何建议。

【问题讨论】:

    标签: python pygame game-development


    【解决方案1】:

    不要在每一帧中重新创建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
    

    【讨论】:

    • 是的!我在我的大型程序上尝试了这个,它运行良好。事后看来,仅使用 scale 命令似乎很明显。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2018-10-16
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多