我最近开始使用pygame.sprite.Sprite和sprite.Group()类,我遇到了一个问题,一旦我的精灵被分组,我就不能再初始化一个新的类实例,而是引发"TypeError:'NPC‘对象不可调用“。这是我的代码(为了简洁而删减);
class NPC(pygame.sprite.Sprite):
def __init__(self, start_x, start_y, image):...
npc_pop=pygame.sprite.Group()
locations=[(100,200), (300,300), (150,200)]
def spawn_NPC(x, y):
image_SS = ss.image_at(rando(), colorkey=(255, 0, 128)) #random image from sprite-sheet
new_guy = NPC(x, y, image_SS)
npc_pop.add(new_guy)
for c in locations:
spawn_NPC(c[0],c[1])
while gameLoop == True:
....
npc_pop.draw(screen)
if len(npc_pop) < 2:
spawn_NPC(100,100)在游戏循环NPC作为一个类并在没有问题的情况下填充sprite容器npc_pop之前,不要过多地讨论NPC类的细节。然而,NPC类的下一个实例被调用为一个函数,在最后一行上引发一个错误,该错误可以追溯到spawn_NPC()。为什么?
我读了这个线程Getting an Error Trying to Create an Object in Python,并实现了分组精灵在某种程度上改变了类,但我仍然不完全理解这个逻辑。
发布于 2016-10-17 11:26:35
我希望这段代码更清晰,我为我的NPC精灵类编写了一个专用模块并构建了一个类生成器,从而解决了我的问题。
import walk #NPC class now imported from a module
@classmethod
def spawnNPC(self, list):
for c in list:
image_SS = ss.image_at(rando(), colorkey=(255, 0, 128))
new_guy = walk.NPC(c[0],c[1],image_SS)
print type(new_guy), "googly"
new_guy.add(npc_pop)
#generate NPC instances at multiple locations before game start
MiniSpawn = type("MiniSpawn", (object,), {"spawnNPC":spawnNPC})
locations = [(333, 200), (300, 300), (200, 200), (50, 50)]
MiniSpawn.spawnNPC(locations)
#Generate new NPC instances in the game loop
if started == 1 and len(npc_mov) < 2:
MiniSpawn.spawnNPC([(200,300)])https://stackoverflow.com/questions/40010407
复制相似问题