【发布时间】:2016-10-13 00:25:04
【问题描述】:
我最近开始在 pygame 中使用 pygame.sprite.Sprite 和 sprite.Group() 类,我遇到了一个问题,一旦我的精灵被分组,我不能再初始化一个新的类实例,而是引发“TypeError:'NPC' object is not callable”。这是我的代码(为了简洁而删减);
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 类,在游戏循环之前,NPC 表现为类并毫无问题地填充精灵容器 npc_pop。然而,NPC 类的下一个实例被调用为一个函数,该函数在追溯到 spawn_NPC() 的最后一行引发错误。为什么?
我读了这个帖子Getting an Error Trying to Create an Object in Python 并意识到分组精灵会以某种方式改变类,但我仍然不完全理解逻辑。
【问题讨论】:
-
您的缩进错误,因此我们无法读取您的代码。在将代码放在 SO 上之前,每行前添加 4 个空格。
-
总是添加完整的错误信息。不仅有消息,还有产生问题的线路等。
-
链接中描述的问题与组无关。例如,您可以设置
print = "Hello World",然后每个print(some_text)都会给您错误'str' object is not callable,因为现在print不是函数而是保持值"Hello World"的变量,现在print(some_text)意味着"Hello World"(some_text)- 所以你有在类似于NPC = ...或some_NCP_object = ...的代码行中查找
标签: python-2.7 pygame sprite