从列表中绘制多个对象(PyGame)

时间:2017-02-21 16:10:58

标签: python pygame

我对python很新,并试图为大学课程创建一个boid克隆。

#the class
class Boid:
    def __init__(self, screen):
        self.screen = screen
        self.pos = Vector2D(random.randrange(400), random.randrange(400))
        self.rad = 20   
        self.speed = Vector2D(-4, -4)

    def draw(self):
        py.draw.circle(self.screen, (255,50,50), (self.pos.x, self.pos.y), self.rad)

# adding objects to a list
self.boid = Boid(self.screen)
self.boid1 = Boid(self.screen)
self.boid2 = Boid(self.screen)
self.boidlist = [self.boid, self.boid1, self.boid2]

#in the game loop, drawing from list
for boid in boidlist:
    boid.draw()

据我了解,它目前只是绘制第一个对象三次,而不是boid(1),boid(2)等。我尝试过这样的事情:

for i in range(3):
    boid(i).draw()

但我无法弄清楚如何将其格式化以便无误地工作。 非常感谢帮助!

1 个答案:

答案 0 :(得分:0)

您误解了如何创建和实例化类:

输入:

self.boid = Boid(self.screen)
self.boid1 = Boid(self.screen)
self.boid2 = Boid(self.screen)

我认为您要创建3个Boid实例,并将其屏幕参数设为screen。为此:

boid = Boid(screen) # 'self.' is only when you create the class
boid1 = Boid(screen)
boid2 = Boid(screen)

最终固定代码:

将对象添加到列表

boid = Boid(screen) # 'self.' is only when you create the class
boid1 = Boid(screen)
boid2 = Boid(screen)

boidlist = [boid, boid1, boid2]

#in the game loop, drawing from list
for boid in boidlist: # This should now work correctly
    boid.draw()