0

このコードは反復を使用していますが、エラーが発生し続けます。なぜそれが何をしているのかわからない。私はこのタイプのプログラミングに不慣れで、これを自分が作成したゲームで使用しています。私もこのサイトに詳しくないので、ご容赦ください。このコードは爆発を示しています。爆発の画像をステップスルーすると、すべてが正常になり、最後に到達するまで、次のエラーが発生します。

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)

ここでの助けは大歓迎です!

4

2 に答える 2

4

StopIterationイテレータが使い果たされたときに発生する例外です。他の例外と同じようにキャッチできます。

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

または、nextビルトインを使用すると、2番目の引数を渡すことで、反復可能オブジェクトが使い果たされたときに特別なものを返すことができます。

def update(self):
    self.image = next(self.image_iter,None)
    if self.image is None:
        pass #move on, explosion is over ...
于 2013-03-19T02:08:22.930 に答える
0

あなたが何をしたいのか正確に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
于 2013-03-19T02:37:29.727 に答える