2013-12-14 59 views
1

我刚开始练习,我应该完成一个基本的“愤怒的小鸟”克隆。 我被困在我想从列表中删除对象的地方。该列表包含游戏中使用的所有障碍物(框)。 所以如果我想删除一个盒子后,我必须做一个方法来做到这一点。无论我如何做,这都会失败。找不到列表以删除对象

class spel(object): 
    def __init__(self):   
     self.obstacles = [obstacle(50,pos=(200,90)),] 
    #defines all other stuff of the game 

class obstacle(object): 
    def __init__(self,size,pos): 
    #defines how it looks like 

    def break(self): 
     #methode that defines what happens when the obstacles gets destroyed 
     spel.obstacles.remove(self) 

我得到的错误是:

AttributeError: 'NoneType' object has no attribute 'obstacles' 

最后一行之后。 请原谅我的noob级别,但重要的是,我不会再需要在此之后再次编码,所以不需要解释所有内容。

回答

0

您已将'spel'定义为类,而不是对象。因此,您收到了一个错误,因为Python正在尝试查找spel类的成员'障碍',而这在运行单个spel对象的方法之前并不存在。

要将spel类的对象与创建的每个障碍物关联起来,您可以尝试为障碍类的对象提供引用其关联的spel对象的数据成员。数据成员可以在障碍类“__init__”函数中实例化。像这样:

class obstacle(object): 
    def __init__(self, spel, size, pos): 
     self.spel = spel 
     #etc 

    def break(self): 
     self.spel.obstacles.remove(self) 

希望有所帮助。

+2

也不使用break作为方法名称,它是一个保留字 – M4rtini

+0

谢谢。错过了。 – andreipmbcn

+0

谢谢! @ M4rtini我用荷兰语写了游戏,所以它是'breek'。我只是很快将其翻译为可读性... –

0

你还没有实例化spel类。

如果你想使用这样的类,你必须对它进行类型化(创建一个实例)。一类

外,像这样:

app = spel() # app is an arbitrary name, could be anything 

那么你会调用它的方法是这样的:

app.obstacles.remove(self) 

或者在你的情况下,从另一个类中:

self.spel = spel() 

self.spel.obstacles.remove(self) 
+0

我知道,我只是没有这一切都添加到我的职位(遗憾的是目前还不清楚) –

+0

确定,但这是与您接受的答案相同 – Totem

0

我提出以下几点建议:

class spel(object): 
    obstacles = [] 
    def __init__(self,size,pos):   
     spel.obstacles.append(obstacle(size,pos)) 
     #defines all other stuff of the game 

class obstacle(object): 
    def __init__(self,size,pos): 
     self.size = size 
     self.pos = pos 
    def brak(self): 
     #methode that defines what happens when the obstacles gets destroyed 
     spel.obstacles.remove(self) 

from pprint import pprint 

a = spel(50,(200,90)) 
pprint(spel.obstacles) 
print 

b = spel(5,(10,20)) 
pprint(spel.obstacles) 
print 

c = spel(3,None) 
pprint(spel.obstacles) 
print 

spel.obstacles[0].brak() 
pprint(spel.obstacles) 

回报

[<__main__.obstacle object at 0x011E0A30>] 

[<__main__.obstacle object at 0x011E0A30>, 
<__main__.obstacle object at 0x011E0B30>] 

[<__main__.obstacle object at 0x011E0A30>, 
<__main__.obstacle object at 0x011E0B30>, 
<__main__.obstacle object at 0x011E0AF0>] 

[<__main__.obstacle object at 0x011E0B30>, 
<__main__.obstacle object at 0x011E0AF0>] 
+0

谢谢,但解决方案@andreipmbcn给了我的是我应该做的。不过看到你的是很有趣的,因为我不知道你可以在“def__init__”之前放置东西, –