【问题标题】:How can I append in item to a list from a class?如何将项目附加到班级的列表中?
【发布时间】:2021-04-23 16:27:43
【问题描述】:

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

这里有一些代码:

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

【问题讨论】:

  • 我建议它还没有出现。您的代码将在添加新障碍之前等待 x 坐标小于 100。 x 坐标从屏幕宽度开始,每个刻度减少 4。这需要一点时间。例如,在 1920x1080 屏幕上,您的游戏以 30fps 运行,需要 16 秒。 编辑:根据 Rabbid76 的回答,你永远不会画出额外的障碍。

标签: python list class pygame


【解决方案1】:

当然,对象被添加到列表中。但是,您永远不会在列表中绘制对象,因此您永远不会看到新对象。你就画ob_disegno:

for i in obs:
   ob_disegno.draw()

你需要移动和绘制列表的元素:

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

【讨论】:

  • @nick17 我已经扩展了答案。
猜你喜欢
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-11
  • 2020-08-19
  • 2011-10-12
  • 2011-05-15
相关资源
最近更新 更多