我使用迭代执行此代码,但不断收到错误。不确定它为什么要去做它正在做的事情。我对这种类型的编程是新手,并且在我创建的游戏中使用它。我对这个网站也不熟悉,所以请多包涵。这段代码将显示一个爆炸。当它遍历爆炸的图像时,一切都很好,直到最后,我得到了这个错误:
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)这里的任何帮助都将不胜感激!
发布于 2013-03-19 10:08:23
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 ...发布于 2013-03-19 10:37:30
我不确定你想要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
yieldhttps://stackoverflow.com/questions/15490314
复制相似问题