我正在尝试在背景不断移动的 PyGame 中制作“运行者”风格的游戏(如几何短跑)。到目前为止一切正常,但背景图像的渲染限制了帧速率超过每秒 35 帧。在我添加无限/重复背景元素之前,它可以很容易地以 60 fps 的速度运行。这两行代码负责(删除后,游戏可以以 60+fps 运行):
屏幕.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()
这是背景图片:
请您参考如下方法:
您是否尝试过使用 convert()?
bg = pygame.image.load('background.png').convert()
来自documentation :
You will often want to call Surface.convert() with no arguments, to create a copy that will draw more quickly on the screen.
For alpha transparency, like in .png images use the convert_alpha() method after loading so that the image has per pixel transparency.
