python - 如何在 pygame 中只复制一次背景?

标签 python background pygame blit

我正在制作一款平台游戏,在位图传输背景时遇到了问题。 在我当前的代码中,游戏循环每帧都会在游戏窗口上绘制背景,这使得当我想使用不仅仅是纯色的任何背景时游戏非常滞后。 我的问题是如何只将背景传输一次(如果可能的话),这样游戏就不会减慢太多。

以下是我的 Game 类中导致图像位 block 传输的一些部分:

class Game:
    def __init__(self):
        pg.init()
        pg.mixer.init()
        self.bg = pg.image.load("background.jpg")
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        self.running = True
        self.font_name = pg.font.match_font(FONT_NAME)
        self.pillarhp = 100


    def new(self):
        self.run()

    def run(self):
        self.clock.tick(FPS)
        self.playing = True
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()


    def draw(self):
        now = pg.time.get_ticks()
        self.screen.blit(self.bg, [0, 0])
        self.screen.blit(self.island, [0,0])
        self.all_sprites.draw(self.screen)
        self.draw_text("Score: " + str(self.score), 20, BLACK, 40, 20)
        self.draw_text("Pillar HP: " + str(self.pillarhp), 20, BLACK, 40, 50)
        pg.display.flip()

最佳答案

调用convert背景表面的方法,例如

self.bg = pg.image.load("background.jpg").convert()

这将提高性能。

对于具有每像素透明度的图像,您可以使用 convert_alpha 方法,但使用 convert 方法转换的图像的位 block 传输速度会快得多。

关于python - 如何在 pygame 中只复制一次背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47856390/

相关文章:

Python 线程 self._stop() 'Event' 对象不可调用

android - 在代码中编辑按钮形状(描边、渐变)

html - 在 HTML 中将 Logo 添加到背景

html - 背景图片不显示

python - Sprite 碰撞

python - pandas:如何获取 .to_string() 方法以将列标题与列值对齐?

python - 直接从协程调用Python的协程

python - 如何让汽车到达赛道顶部

python - Pygame health/maxhealth = 0.0 而不是 0.66

python - 如何使用 strptime 解析 str(my_datetime)?