加快循环PyGame抽奖的速度

我有一个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的效果很奇怪。

评论
ksit
ksit

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 target Surface. Set the pixels directly, instead of drawing each cell separately by pygame.draw.rect():

def draw_living_cells(self):
    self.screen.fill(BLACK)

    pixel_array = pg.PixelArray(self.screen) 

    size = self.screen.get_size() 
    for x in range(0, GRID_WIDTH + 1):
        for y in range(0, GRID_HEIGHT):
            if self.grid[x + 1][y + 1] == 1:
                rect = pygame.Rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE)
                pixel_array[rect.left : rect.right, rect.top : rect.bottom] = LIFE_COLOR

    pixel_array.close()

    pg.display.flip()
点赞
评论