如何StopIteration

时间:2013-03-19 02:05:28

标签: python iteration pygame

我这个代码使用迭代,我不断收到错误。不确定它为什么会这样做。我是这类编程的新手,并且在我创建的游戏中使用它。我也不熟悉这个网站,所以请耐心等待。此代码将显示爆炸。当它逐步浏览爆炸的图像时,一切都很好,直到它结束,我得到这个错误:

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)

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

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 ...

答案 1 :(得分:0)

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

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