【问题标题】:Pygame sprite object not callable after pygame.sprite.Group()Pygame sprite 对象在 pygame.sprite.Group() 之后不可调用
【发布时间】:2016-10-13 00:25:04
【问题描述】:

我最近开始在 pygame 中使用 pygame.sprite.Spritesprite.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


【解决方案1】:

我希望这段代码更清楚,我通过为我的 NPC sprite 类编写一个专用模块并构建一个类生成器来解决我的问题。

    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)])

【讨论】:

    猜你喜欢
    • 2013-04-03
    • 2023-03-03
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多