有什么方法可以加快Python和Pygame的速度吗?

| 我在Pygame中编写了一个简单的自上而下的rpg,但是我发现它非常慢。...尽管我不期望python或pygame与使用C / C ++或事件字节编译的编译语言制作的游戏的FPS相匹配像Java,但是pygame的当前FPS仍然是15。我尝试渲染16色位图,而不是PNG或24位图,这稍微提高了速度,然后无奈之下,我将所有内容都切换为黑白单色位图,使FPS升至35。现在,根据我阅读过的大多数游戏开发书籍,为了使用户对游戏图形完全满意,二维游戏的FPS至少应为40,那么有没有办法提高pygame的速度?     
已邀请:
        对python2使用Psyco:
import psyco
psyco.full()
另外,启用双缓冲。例如:
from pygame.locals import *
flags = FULLSCREEN | DOUBLEBUF
screen = pygame.display.set_mode(resolution, flags, bpp)
如果不需要,也可以关闭Alpha:
screen.set_alpha(None)
不必每次都翻转整个屏幕,而是要跟踪已更改的区域并仅对其进行更新。例如,大致如下所示(主循环):
events = pygame.events.get()
for event in events:
    # deal with events
pygame.event.pump()
my_sprites.do_stuff_every_loop()
rects = my_sprites.draw()
activerects = rects + oldrects
activerects = filter(bool, activerects)
pygame.display.update(activerects)
oldrects = rects[:]
for rect in rects:
    screen.blit(bgimg, rect, rect)
大多数(全部?)绘图函数都返回一个rect。 您还可以仅设置一些允许的事件,以更快地处理事件:
pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP])
另外,我不会为手动创建缓冲区而烦恼,也不会使用HWACCEL标志,因为我在某些设置上遇到了问题。 使用此工具,我已经为小型2d平台实现了相当不错的FPS和平滑度。     
        加载图像时,如果绝对需要透明度或其他alpha值,请使用Surface.convert_alpha()方法。我一直在将它用于我编写的游戏中,并且性能得到了极大的提高。 例如:在构造函数中,使用以下命令加载图片:
self.srcimage = pygame.image.load(imagepath).convert_alpha() 
据我所知,您对图像所做的任何转换都保留了此方法调用的性能。例如:
self.rotatedimage = pygame.transform.rotate(self.srcimage, angle).convert_alpha()
如果使用的图像上带有
convert_alpha()
,则图像变得多余。     
        使用图像时,使用图像的convert()函数进行转换很重要。 我读过convert()禁用通常很慢的alpha。 在使用16位色深和图像转换功能之前,我还遇到了速度问题。现在,即使我在屏幕上放大了大图像,我的FPS仍约为150。
image = image.convert()#video system has to be initialed
旋转和缩放也需要大量时间来计算。如果变形后的大图像是不可变的,则可以将其保存在其他图像中。 因此,想法是一次计算并多次重用结果。     
        所有这些都是不错的建议,并且效果很好,但是您还应该牢记两件事: 1)将表面涂到表面上比直接绘制要快。因此,将固定的图像预先绘制到表面上(在主游戏循环之外),然后将表面涂抹到主屏幕上将更加有效。例如:
# pre-draw image outside of main game loop
image_rect = get_image(\"filename\").get_rect()
image_surface = pygame.Surface((image_rect.width, image_rect.height))
image_surface.blit(get_image(\"filename\"), image_rect)
......
# inside main game loop - blit surface to surface (the main screen)
screen.blit(image_surface, image_rect)
2)确保通过绘制用户看不见的东西来浪费资源。例如:
if point.x >= 0 and point.x <= SCREEN_WIDTH and point.y >= 0 and point.y <= SCREEN_HEIGHT:
    # then draw your item
这些是一些通用概念,可帮助我保持较高的FPS。     
        首先,请始终使用\'convert()\',因为它会禁用Alpha,从而使出血更快。 然后,仅更新需要更新的屏幕部分。
global rects

rects = []

rects.append(pygame.draw.line(screen, (0, 0, 0), (20, 20), (100, 400), 1)) 

pygame.display.update(rects) # pygame will only update those rects
注意: 移动精灵时,必须从其最后位置开始将rect包括在列表中。     
        您可以尝试使用Psyco(http://psyco.sourceforge.net/introduction.html)。它通常会带来很大的不同。     

要回复问题请先登录注册