【问题标题】:How can I reduce the lag and CPU usage in pygame? (pytmx is used for loading the map)如何减少 pygame 中的延迟和 CPU 使用率? (pytmx 用于加载地图)
【发布时间】:2021-06-21 05:12:43
【问题描述】:

我在游戏中遇到了严重滞后的问题。我的游戏有一张很大的地图。地图为 250x250 瓷砖。每个图块为 32x32。请注意,我使用的是旧笔记本电脑。当我打开任务管理器时,它说我的 CPU 使用率高达 50%,但内存使用率只有 30-40 MB。我是初学者,所以我会很感激任何帮助。 我正在使用从一些 YouTube 教程中获得的代码。我对其进行了一些修改以使其适用于我的项目。

    import pygame as pg, time, random
    from pygame.locals import *
    from pytmx.util_pygame import load_pygame


    def blit_all_tiles(screen, tmxdata, world_offset):
    for layer in tmxdata:
        for tile in layer.tiles():
            # tile[0] = x coordinate
            # tile[1] = y coordinate
            # tile[2] = image data
            x_pixel = tile[0] * 32 + world_offset[0]
            y_pixel = tile[1] * 32 + world_offset[1]
            screen.blit(tile[2], (x_pixel, y_pixel))


    # Game Variables
    def main():
    tmxdata = load_pygame("assets/Chris' adventure.tmx")
    # Standing
    player_stand = pg.image.load("CharAssets/Cris 01.png")
    player_stand = pg.transform.scale(player_stand, (32, 32))
    # Moving Right
    player_left = [
        pg.image.load("CharAssets/Cris 04.png"),
        pg.image.load("CharAssets/Cris 05.png"),
        pg.image.load("CharAssets/Cris 06.png"),
    ]
    player_up = [
        pg.image.load("CharAssets/Cris 07.png"),
        pg.image.load("CharAssets/Cris 08.png"),
        pg.image.load("CharAssets/Cris 09.png"),
    ]
    player_down = [
        pg.image.load("CharAssets/Cris 01.png"),
        pg.image.load("CharAssets/Cris 02.png"),
        pg.image.load("CharAssets/Cris 03.png"),
    ]
# Resize
player_left = [pg.transform.scale(image, (32, 32)) for image in player_left]
player_left_f = 0
player_up = [pg.transform.scale(image, (32, 32)) for image in player_up]
player_up_f = 0
player_down = [pg.transform.scale(image, (32, 32)) for image in player_down]
player_down_f = 0
# Flipping
player_right = [pg.transform.flip(image, True, False) for image in player_left]
player_right_f = 0
direction = "stand"
world_offset = [0, 0]

quit = False
x = 400
y = 200 + 128
# Game Loop
while not quit:
    screen.fill((0, 0, 0))
    blit_all_tiles(screen, tmxdata, world_offset)
    # Events
    keypressed = pg.key.get_pressed()
    for event in pg.event.get():
        # print(event)
        if event.type == QUIT:
            quit = True
    if keypressed[ord("a")]:
        x = x - 20
        world_offset[0] += 40
        direction = "left"
    if sum(keypressed) == 0:
        direction = "stand"
    if keypressed[ord("d")]:
        x = x + 20
        world_offset[0] -= 40
        direction = "right"
    if keypressed[ord("w")]:
        y = y - 20
        world_offset[1] += 40
        direction = "up"
    if keypressed[ord("s")]:
        y = y + 20
        world_offset[1] -= 40
        direction = "down"
    if y < 204:
        y = 204
    if y >= screen.get_height() - 204 - 32:
        y = screen.get_height() - 204 - 32
    if x < 204:
        x = 204
        # world_offset[0] += 10
    if x >= screen.get_width() - 204 - 32:
        x = screen.get_width() - 204 - 32

    # Game Logic
    # player = Rect(x, y, 32, 32)
    # pg.draw.rect(screen, (225, 0, 120), player)
    if direction == "stand":
        screen.blit(player_stand, (x, y))
    elif direction == "left":
        screen.blit(player_left[player_left_f], (x, y))
        player_left_f = (player_left_f + 1) % len(player_left)
    elif direction == "right":
        screen.blit(player_right[player_right_f], (x, y))
        player_right_f = (player_right_f + 1) % len(player_right)
    elif direction == "up":
        screen.blit(player_up[player_up_f], (x, y))
        player_up_f = (player_up_f + 1) % len(player_up)
    elif direction == "down":
        screen.blit(player_down[player_down_f], (x, y))
        player_down_f = (player_down_f + 1) % len(player_down)

    # Screen Update
    pg.display.update()
    clock.tick(60)


    # Game Initialization
    if __name__ == "__main__":
    width, height = 800, 600
    pg.init()
    pg.mixer.init()
    screen = pg.display.set_mode((width, height))
    pg.display.set_caption("Chris' quest")
    clock = pg.time.Clock()
    main()
    pg.quit()

我成功导入了地图,现在可以使用,但延迟非常大。我很困惑,我不知道如何解决这个问题。我会很感激帮助。提前致谢。

【问题讨论】:

  • 您可以尝试的一件事是不要在每一帧中渲染每个图块。在游戏开始时,为整个地图创建一个大的 Surface,将瓷砖渲染到该表面,并在每一帧将该表面blit 到屏幕上。要尝试的另一件事是跳过无论如何不在屏幕上的blitting tile。这样,您可以跳过大部分 blit 调用。
  • @sloth 这第二个想法听起来不错。你知道我应该怎么做吗?谢谢

标签: python pygame pytmx


【解决方案1】:

确保图像Surface 与显示Surface 具有相同的格式。使用convert()(或convert_alpha())创建一个具有相同像素格式的Surface。当图像在显示器上显示为blit 时,这会提高性能,因为格式是兼容的并且blit 不需要执行隐式转换。

例如:

player_stand = pg.image.load("CharAssets/Cris 01.png")

player_stand = pg.image.load("CharAssets/Cris 01.png").convert_alpha()

另一种选择是创建游戏的单个大地图。

通过在其上绘制所有图块来创建一个与整个地图大小相同的pygame.Surface

def create_map():
    game_map = pygame.Surface((250 * 32, 250 * 32))
    for layer in tmxdata:
        for tile in layer.tiles():
            # tile[0] = x coordinate
            # tile[1] = y coordinate
            # tile[2] = image data
            x_pixel = tile[0] * 32
            y_pixel = tile[1] * 32
            game_map.blit(tile[2], (x_pixel, y_pixel))
    return game_map  
game_map = create_map()

在应用程序中,您使用blit 方法的可选area 参数仅在屏幕上绘制地图的一部分:

while not quit:
    # [...]

    sub_area = screen.get_rect(topleft = world_offset)
    screen.blit(game_map, (0, 0), sub_area) 

    # [...]

此解决方案提高了性能。但是,您需要为内存使用付费。

【讨论】:

  • 我尝试按照它所说的那样实现这个代码,但是我收到一个错误“未解析的引用'game_map”,它说虽然我做了你所说的一切,但名称没有定义
  • 我的代码保持不变。我只在每张图片之后添加了 convert_alpha() 。我现在尝试实现您的代码,但未定义 tmxdata
  • 很遗憾听到您这样想。我认为它不起作用,因为我的地图是 .tmx 文件。谢谢
  • @VladimirAvramović 你以前画过瓷砖。为什么现在不能画?在您将图块绘制到screen 之前,现在将它们绘制到game_map
猜你喜欢
  • 2018-02-09
  • 2016-01-07
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
相关资源
最近更新 更多