【问题标题】:How to StopIteration如何停止迭代
【发布时间】:2013-03-19 10:37:29
【问题描述】:

我使用迭代的代码,我不断收到错误。不知道为什么它正在做什么。我是这种类型的编程新手,并在我创建的游戏中使用它。我也不熟悉这个网站,所以请多多包涵。此代码将显示爆炸。当它逐步浏览爆炸的图像时,一切都很好,直到它结束,我得到这个错误:

Traceback (most recent call last):
  File "C:\Users\Steve\Desktop\Project April\Alien Metor Storm v1_4\AlienMetorStorm.py", line 560, in <module>
    main()
  File "C:\Users\Steve\Desktop\Project April\Alien Metor Storm v1_4\AlienMetorStorm.py", line 222, in main
    ships.update()
  File "C:\Python31\lib\site-packages\pygame\sprite.py", line 399, in update
    for s in self.sprites(): s.update(*args)
  File "C:\Users\Steve\Desktop\Project April\Alien Metor Storm v1_4\explosion.py", line 26, in update
    self.image = next(self.image_iter)
StopIteration

代码如下:

import pygame

class Explosion(pygame.sprite.Sprite):
    def __init__(self,color,x,y):
        pygame.sprite.Sprite.__init__(self)
        self.frame = 0
        self.width = 0
        self.height = 0
        self.x_change = 0
        self.y_change = 0
        self.images = []
        for i in range (0,25):
            img = pygame.image.load('Explosion'+str(i)+'.png').convert()
            img.set_colorkey([0,0,0])
            self.images.append(img)
        self.image = self.images[0]
        self.image_iter = iter(self.images)
        self.rect = self.image.get_rect()
        self.rect.left = x
        self.rect.top = y

    def update(self):
        self.image = next(self.image_iter)

这里的任何帮助将不胜感激!

【问题讨论】:

    标签: python iteration pygame


    【解决方案1】:

    StopIteration 是迭代器耗尽时引发的异常。您可以像任何其他异常一样捕获它:

    def update(self):
         try:
             self.image = next(self.image_iter)
         except StopIteration:
             pass #move on, explosion is over ...
    

    或者,next 内置函数允许您通过传递第二个参数在迭代耗尽时返回一些特殊的东西:

    def update(self):
        self.image = next(self.image_iter,None)
        if self.image is None:
            pass #move on, explosion is over ...
    

    【讨论】:

    • 如果动画应该永远重复,itertools.cycle 会这样做。
    • 不知道next() 的第二个参数,再加一个!
    • @TokenMacGuy -- 另一个几乎从未使用过的是 iter 的 2 参数形式(这与 1 参数形式确实不同)
    【解决方案2】:

    我不确定你到底想要 update 做什么,但这里有一个生成器版本你可以使用,所以你不需要外部迭代器

    def update(self):
        for image in self.images:
            self.image = image
            yield
    

    或者如果你想永远迭代

    def update(self):
        while True:
            for image in self.images:
                self.image = image
                yield
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      • 1970-01-01
      • 2017-12-10
      • 2015-12-15
      • 2018-07-20
      • 1970-01-01
      • 2020-08-06
      相关资源
      最近更新 更多