且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-13 23:26:13

将Psyco用于python2:

Use Psyco, for python2:

import psyco
psyco.full()

此外,启用双缓冲.例如:

Also, enable doublebuffering. For example:

from pygame.locals import *
flags = FULLSCREEN | DOUBLEBUF
screen = pygame.display.set_mode(resolution, flags, bpp)

如果不需要,也可以关闭Alpha:

You could also turn off alpha if you don't need it:

screen.set_alpha(None)

不要每次都翻转整个屏幕,而是要跟踪已更改的区域并仅对其进行更新.例如,大致如下所示(主循环):

Instead of flipping the entire screen every time, keep track of the changed areas and only update those. For example, something roughly like this (main loop):

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)

大多数(全部?)绘图函数返回一个矩形.

Most (all?) drawing functions return a rect.

您还可以仅设置一些允许的事件,以更快地处理事件:

You can also set only some allowed events, for more speedy event handling:

pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP])

此外,我不会为手动创建缓冲区而烦恼,也不会使用HWACCEL标志,因为在某些设置中遇到了问题.

Also, I would not bother with creating a buffer manually and would not use the HWACCEL flag, as I've experienced problems with it on some setups.

使用此工具,我已经在一个小型2d平台上获得了相当不错的FPS和平滑度.

Using this, I've achieved reasonably good FPS and smoothness for a small 2d-platformer.