pygame精灵列表丢失首个元素,重复最后一个元素
我有一个函数,它的作用是加载一个精灵表,找到一块精灵,然后把每个单独的精灵放到一个列表里。在把精灵添加到列表之前,它会先把这个精灵显示到屏幕上。一旦所有精灵都加载完毕,它就会遍历这个列表,依次显示每个精灵。这两次显示的结果应该是一样的,但实际上,第一个精灵在列表中丢失了,而最后一个精灵却被重复显示了。这两次显示的结果看起来是这样的:
每个精灵都是按照它们被添加到列表的顺序显示的,从左到右、从上到下,所以第一个精灵是左上角的那个,最后一个是右下角的那个。
这是加载精灵的函数:
def assembleSprites(name, screen):
"""Given a character name, this function will return a list of all that
character's sprites. This is used to populate the global variable spriteSets"""
spriteSize = (35, 35)
spritesheet = pygame.image.load("./images/patchconsprites.png")
sprites = []
start = charCoords[name]
char = list(start)
image = pygame.Surface((35,35))
# load each sprite and blit them as they're added to the list
for y in range(5):
char[0] = start[0]
for x in range(9):
rect = (char[0], char[1], char[0]+spriteSize[0], char[1]+spriteSize[1])
image.blit(spritesheet, (0,0), rect)
image = image.convert()
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
screen.blit(image, (x*40, y*40))
pygame.display.update()
sprites.append(image)
char[0] += spriteSize[0]+2
char[1] += spriteSize[1]+2
# check that the list was constructed correctly
count = 0
for y in range(6,11):
for x in range(9):
screen.blit(sprites[count], (x*40,y*40))
count += 1
pygame.display.update()
return sprites
有没有人能看出我在列表中搞错了什么?
1 个回答
7
image.blit(spritesheet, (0,0), rect)
你没有在每次循环的时候重新初始化 image
,所以它还是上一次循环中用的那个表面,这个表面已经在列表里了。每次循环的时候,你都在覆盖之前步骤中添加到列表里的精灵。
我建议你在这行代码之前,立即创建一个新的 image= pygame.Surface((35,35))
,而不是在循环开始之前。