所以我有一个基于磁贴的游戏,大216X384个单位。 cell_array中的每个方块都是草,我预先加载了convert_alpha()。每次绘制时(我的fps为30),它循环通过cell_array并将其blit到屏幕上。如果cell_array为空,则执行此操作和其他操作大约需要0.02秒,因此30 fps可以正常工作。但当它充满了草,它需要0.08-0.1秒,使它滞后很多。任何提示,技巧或想法可以提供帮助吗?
这是cell_array代码的样子。
cell_array = []
width_of_cells = 10
height_of_cells = 10
cell_Rows = 216
cell_Cols = 384
def initialize_empty_cell_board(rows, cols):
for x in range(cell_Cols):
new = []
for y in range(cell_Rows):
new.append(["NULL", False, True])
cell_array.append(new)
def add_tile(board, tile, cx, cy):
for i in range(tile.c_width):
for q in range(tile.c_height):
if cx+i < cell_Cols and cy+i < cell_Rows:
board[cx+i][cy+i] = [tile, False, tile.is_passible]
board[cx][cy] = [tile, True, tile.is_passible]
initialize_empty_cell_board(cell_Rows, cell_Cols)
这是blitting代码:
cx = -1
cy = -1
for x in cell_array:
cy = -1
cx += 1
for y in x:
cy += 1
if y[0] != "NULL" and y[1] == True:
screen.blit(y[0].img.name, (cx*cells.width_of_cells, cy*cells.height_of_cells))
这是图像代码的样子:
class Image(object):
def __init__(self, src):
self.name = pygame.image.load(src).convert_alpha()
答案 0 :(得分:0)
如果游戏不必每帧都进行一次,那么处理会更容易。我假设这个草瓦是地板或背景。这意味着所有的草都可以预先形成一个表面,每一帧都只需要表面。
这个例子:
import pygame as py
py.init()
window = (400,400)
screen = py.display.set_mode(window)
font = py.font.Font(None,36)
clock = py.time.Clock()
def draw_onto_screen():
for i in xrange(0,200):
for j in xrange(0,200):
py.draw.rect(screen,(0,255,0),(i,j,5,5))
text = font.render(str(clock.get_fps()),1,(10,10,10))
screen.blit(text,(0,0))
done = False
while not done:
for event in py.event.get():
if event.type == py.QUIT:
done = True
draw_onto_screen()
py.display.flip()
clock.tick(60)
py.quit()
每帧绘制40,000个方格,并且在我的机器上显示平均 11fps (您可以自己运行并查看左上角的fps)。
然而,如果我们首先将所有正方形绘制到另一个表面上(让我们称之为背景)并且我们得到的表面就是简单的blit:
import pygame as py
py.init()
window = (400,400)
screen = py.display.set_mode(window)
font = py.font.Font(None,36)
clock = py.time.Clock()
def draw_onto_screen():
for i in xrange(0,200):
for j in xrange(0,200):
py.draw.rect(background,(0,255,0),(i,j,5,5))
background = py.Surface(window)
draw_onto_screen() #### only called once
done = False
while not done:
for event in py.event.get():
if event.type == py.QUIT:
done = True
screen.blit(background,(0,0)) #### blit the background onto screen
text = font.render(str(clock.get_fps()),1,(10,10,10))
screen.blit(text,(0,0))
py.display.flip()
clock.tick(60)
py.quit()
其中绘制的内容完全相同,但以 62.5fps 巡航。现在,当您想要移动背景时,只需将其blit到另一个位置(当前(0,0))
希望这有帮助。