如何将in项附加到类的列表中?

2024-09-29 01:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pygame中编写了一个小游戏,我不得不从一个类中将项目添加到列表中,但是当我运行代码时,第二个“障碍”没有出现,因为“障碍”类中的函数“move”没有将项目附加到列表中。 有人知道如何解决这个问题吗

下面是一些代码:

obs = []

class obstacles():
    def __init__(self):
        self.x = screen_width
        self.y = screen_height - ob_height
        self.rect = Rect(self.x, self.y, ob_width, ob_height)
        self.speed = 4
    

    def draw(self):
        pygame.draw.rect(screen, ob_col, self.rect)
    

    def move(self):
        self.rect.x -= self.speed
        if self.rect.x < 100:
            obs.append(obstacles())
    

def init():
   obs.append(obstacles())

  
ob_disegno = obstacles()
sq_disegno = square()

init()

run = True

while run:
    
        clock.tick(fps)
        screen.fill(background)

        ob_disegno.move()
        sq_disegno.draw()
    
        for i in obs:
            ob_disegno.draw()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                 run = False


        pygame.display.update()


pygame.quit()

Tags: runrectselfeventmoveinitdefscreen
1条回答
网友
1楼 · 发布于 2024-09-29 01:29:21

当然,对象会添加到列表中。但是,您从未在列表中绘制对象,因此您从未看到新对象。您只需绘制ob_disegno

for i in obs:
   ob_disegno.draw()

您需要移动并绘制列表中的元素:

for ob in obs:
    ob.move()
    ob.draw()

相关问题 更多 >