Python Pygame 正在减速

Python Pygame is slowing down

我正在使用 pygame 创建一个 Python 游戏。游戏运行良好,但我向游戏中添加的角色越多,游戏速度就越慢。我该如何解决?

这是主要代码:

finish = False
background_x = 0
background_y = 0
REFRESH_RATE = 180
background = pygame.image.load(BACKGROUND_IAMGE)

while not finish:
    clock.tick(REFRESH_RATE)
    SCREEN.blit(background, (background_x, background_y))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finish = True

    block_on_right = False
    block_on_left = False
    is_player_on_block = False
    for block in blocks:
        block.load_image(background_x)
        if player.is_crash(block):
            for i in range(player.vy):
                if player.get_bottom_y() - i == block.get_y():
                    is_player_on_block = True
                if player.y + i == block.get_bottom_y():
                    player.set_jump(False)
            for i in range(player.vx):
                if player.get_right_x() - i == block.get_x():
                    block_on_right = True
                if player.x + i == block.get_right_x():
                    block_on_left = True
        for monster in monsters:
            if monster.is_crash(block):
                monster.turn_around()

    keys = pygame.key.get_pressed()

    if (keys[pygame.K_UP] or keys[pygame.K_SPACE] or keys[pygame.K_w]) and not player.is_mid_air():
        player.set_jump(True)

    if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and not block_on_right:
        if player.get_direction() != "right":
            player.turn_around()
        player.set_walk(True)

        background_x -= player.vx
        player.x += player.vx

    if (keys[pygame.K_LEFT] or keys[pygame.K_a]) and not block_on_left:
        if player.get_direction() != "left":
            player.turn_around()
        player.set_walk(True)
        if background_x != 0:
            background_x += player.vx
            player.x -= player.vx

    if not any(keys):
        player.stand_still()
        player.set_walk(False)

    for monster in monsters:
        SCREEN.blit(monster.get_image(), (background_x + monster.get_x(), monster.get_y()))
        monster.step()

    if player.get_bottom_y() == FLOOR_Y or is_player_on_block:
        player.set_is_mid_air(False)
    else:
        player.set_is_mid_air(True)
        player.fall()

    player.check_jump()

    player_image = player.get_image().convert()
    player_image.set_colorkey(PINK)

    SCREEN.blit(player_image, (player.x + background_x, player.y))
    pygame.display.flip()

pygame.quit()

我不是有效减少执行时间的专家,但有一些技巧(看看它们是否有帮助)。
首先,看看您是否可以使用较慢的刷新率。
其次,我注意到你每次迭代都在重新绘制背景。我认为有一种方法可以只更新部分屏幕。所以你应该能够绘制一次背景,然后只重绘你角色所在的屏幕部分。这可能会有所帮助,特别是如果您的背景是静态的。
如果仍然较慢,请查看是否可以减小图像的尺寸(可能是个坏主意,但值得一试)
希望至少其中一些是可以实现的。