在PyGame中渲染大图像导致低帧率

时间:2016-07-22 21:10:18

标签: python pygame

我正在尝试在PyGame中创建一个'Runner'风格的游戏(如Geometry Dash),背景不断移动。到目前为止一切正常,但背景图像的渲染限制帧速率超过每秒35帧。在我添加无限/重复背景元素之前,它可以轻松地以60 fps运行。这两行代码负责(删除后,游戏可以60 + fps运行):

screen.blit(bg,(bg_x,0))| screen.blit(bg,(bg_x2,0))

我能做些什么来让游戏跑得更快?提前谢谢!

简化源代码:

import pygame
pygame.init()

screen = pygame.display.set_mode((1000,650), 0, 32)
clock  = pygame.time.Clock()

def text(text, x, y, color=(0,0,0), size=30, font='Calibri'): # blits text to the screen
    text = str(text)

    font = pygame.font.SysFont(font, size)
    text = font.render(text, True, color)

    screen.blit(text, (x, y))

def game():
    bg = pygame.image.load('background.png')
    bg_x = 0 # stored positions for the background images
    bg_x2 = 1000

    pygame.time.set_timer(pygame.USEREVENT, 1000)
    frames = 0 # counts number of frames for every second
    fps = 0

    while True:
        frames += 1
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.USEREVENT: # updates fps every second
                fps = frames
                frames = 0 # reset frame count

        bg_x -= 10 # move the background images
        bg_x2 -= 10

        if bg_x == -1000: # if the images go off the screen, move them to the other end to be 'reused'
            bg_x = 1000
        elif bg_x2 == -1000:
            bg_x2 = 1000

        screen.fill((0,0,0))
        screen.blit(bg, (bg_x, 0))
        screen.blit(bg, (bg_x2, 0))

        text(fps, 0, 0)

        pygame.display.update()
        #clock.tick(60)

game()

这是背景图片:

enter image description here

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用convert()

    bg = pygame.image.load('background.png').convert()

来自documentation

  

您经常需要在没有参数的情况下调用Surface.convert(),以创建一个可以在屏幕上更快地绘制的副本。

     

对于Alpha透明度,与.png图像一样,在加载后使用convert_alpha()方法,以使图像具有每像素透明度。