我有一个pygame游戏,目前在“绘制到屏幕”过程中出现瓶颈。这是代码(pg是pygame):
def draw_living_cells(self):
self.screen.fill(BLACK)
for x in range(0, GRID_WIDTH + 1):
for y in range(0, GRID_HEIGHT):
if self.grid[x + 1][y + 1] == 1:
pos = (int(x * CELL_SIZE), int(y * CELL_SIZE), int(CELL_SIZE), int(CELL_SIZE))
pg.draw.rect(self.screen, LIFE_COLOR, pos, 0)
pg.display.flip()
我认为多处理可能会有所帮助,但是我不确定如何实现(由于可能存在的共享内存问题)还是完全没有帮助。
在800x600的显示屏中,使用大小为200x150的self.grid的此过程大约需要20毫秒。我认为在这样一个简单的过程中获得〜50fps的效果很奇怪。
I would suggest that you modify your code to use pygame's Sprite mechanics and in particular look at the sprite group
pygame.sprite.DirtySprite
. You can then mark the cells that have changed as dirty and have it only redraw those cells instead of all the cells.This change would also require you to not redraw the entire background with the
self.screen.fill(BLACK)
.Since your method is named
draw_living_cells()
, that implies that there are dead cells that you do not redraw. Since you would not be filling the entire background that means that you have to draw the background onto the screen where the dead cell used to be.Use
pygame.PixelArray
for direct pixel access of the targetSurface
. Set the pixels directly, instead of drawing each cell separately bypygame.draw.rect()
: