【发布时间】:2018-02-23 16:38:15
【问题描述】:
我使用 Python 和 pygame 编写了一个程序,它加载材料图片,然后创建块,每个块都分配有随机材料。 Block 是一个类,在绘图过程中,它会遍历存储有块的数组,但这非常慢。难道没有比将它们存储在数组中并迭代更快的方法吗?
class block:
def __init__(self, texture, x, y):
self.texture = texture
self.x = x
self.y = y
material = pygame.image
material.grass = pygame.image.load("textures/grass.png")
material.water = pygame.image.load("textures/water.png")
material.sand = pygame.image.load("textures/sand.png")
materials = [material.grass, material.water, material.sand]
white = (255,255,255);(width, height) = (2048, 1008);black = (0, 0, 0);screen = pygame.display.set_mode((width, height))
b_unit = 16
b = []
count = 0
cx = 0
cy = 0
while count < (width * height) / (b_unit * b_unit):
b.append(block(random.choice(materials), b_unit * cx, b_unit * cy))
cx += 1
count += 1
if cx == width / b_unit:
cx = 0
cy += 1
while True:
for block in b:
screen.blit(block.texture, (block.x + viewx, block.y + viewy))
pygame.display.flip()
【问题讨论】:
-
始终转换您的图像:stackoverflow.com/a/48574695/6220679
-
我没有看到任何真正的加速技巧可以做到。您可以使用元组减少类的开销。但是速度的加快不会很明显。它们是什么类型的图像(浮点数、字节)?在 blit 期间是否发生了转换?
-
一直单独对块进行 Blitting 也会很慢。如果在游戏过程中背景没有改变,最好在程序启动时将背景
blocks blit 到一个大表面上,然后每帧只对该背景表面进行一次blit。 -
@J. Bakker 它们是 16x16 png 图像
-
@skrx 好的,我该怎么做?