【问题标题】:Why is objects accelerating in for loop?为什么对象在 for 循环中加速?
【发布时间】:2019-09-25 08:19:14
【问题描述】:

在我的 for 循环中,我有一个声明为 p.x -= p.vel。显然,这会导致对象对屏幕上的每个对象进行加速。如果我从列表中弹出对象,它不会加速太多,但它仍然会加速一点。我怎样才能解决这个问题?程序是用pygame写的

这个游戏基本上是一个飞扬的小鸟游戏,它是在加速的管道,但我希望它们始终以相同的速度移动

这是类和变量


    def __init__(self, x, width):
        self.bottom_height = random.randint(50, 400)
        self.top_height = screen_height - 175 - self.bottom_height
        self.width = width

        self.bottom_y = screen_height - self.bottom_height
        self.top_y = 0
        self.x = x

        self.vel = 2.5

        self.pipes = []

这里是函数

    def spawn(self):
        for p in pipe.pipes:
            if bird.x == p.x:
                pipe.pipes.append(Pipe(pipe.x, pipe. width))

    def move(self):
        self.spawn()
        for p in pipe.pipes:
            if 0 - p.width < p.x < screen_width + 50:
                p.x -= p.vel
            else:
                pipe.pipes.pop(pipe.pipes.index(p))

【问题讨论】:

  • 什么加速?您正在使用的库(pygame?)将比“oop”和“loops”作为标签更有用
  • 游戏中的管道(飞扬的小鸟)。

标签: python python-3.x loops pygame


【解决方案1】:

你的问题很可能在这里:

for p in pipe.pipes:
    if 0 - p.width < p.x < screen_width + 50:
        p.x -= p.vel
    else:
        pipe.pipes.pop(pipe.pipes.index(p))

您正在对列表进行迭代,并且在对其进行迭代时,您正在从中删除元素。

以这个例子为例,源自您的代码:

s = [1, 2, 3, 4, 5]
for i in s:
    print(i)
    s.pop(s.index(i))

您期望输出是什么?提示:不会是1 2 3 4 5。

要解决此问题,您可以遍历列表,在另一个列表中跟踪要删除的元素并在循环后删除它们,或者循环遍历列表的副本并每次从原始列表中删除元素你需要。

另外,如果你保存要删除的元素的索引,它会更快。

类似的东西(未经测试!):

def move(self):
    self.spawn()
    index_to_remove = []
    for i in range(len(pipe.pipes)):
        if 0 - p.width < p.x < screen_width + 50:
            p.x -= p.vel
        else:
            index_to_remove.append(i)
    for index in index_to_remove:
        del pipe.pipes[index]

【讨论】:

  • 还在加速获取:IndexError: list assignment index out of range
  • 是的,你在那段代码中做同样的事情,你只需要应用同样的想法(跟踪要删除的索引并在循环后执行)
猜你喜欢
  • 2021-09-03
  • 2016-01-31
  • 2019-11-03
  • 1970-01-01
  • 2020-12-16
  • 2011-06-10
  • 1970-01-01
相关资源
最近更新 更多