检查组中每个角色的冲突 -> 属性错误



我想检查一下精灵组中的哪个对象与另一个对象碰撞,然后在那个位置创建一个新精灵(比如爆炸)。

在while循环中,我移动对象,然后检查碰撞。

if not game_over:
    move_coins()
    move_pointer()
    if pygame.sprite.spritecollideany(pointer, coin_group):
        print_text(pygame.font.Font(None,16), 0, 0, "Collision!")
        check_collision()

这里的碰撞是成功的,因为它将文本打印到屏幕上。然后继续执行check_collision()。

def check_collision():
    for coin in coin_group:
        if pygame.sprite.collide_rect(coin, pointer):
            create_newcoin()
def create_newcoin():
    bcoin = Coin()
    bcoin.load("coin1s.png", 32, 32, 1)
    bcoin.position = 0,0 
    collected_group.add(bcoin)

create_newcoin()函数在check_collision()之外正常工作,但是当它运行这个循环时,我得到一个属性错误。

Coin() has no attribute 'image'

谁能解释为什么我得到这个错误,我需要做什么来修复它?如果有必要,我可以提供更多的代码,但我想我已经把它缩小到导致错误的这一部分。谢谢。


嗯,我只是粘贴我正在处理的代码。http://pastebin.com/TuAZxUkq和http://pastebin.com/kmYytiYV

和错误:

Traceback (most recent call last):
    File "C:UsersUserDesktopCoins!Coins!.py", line 129, in <module>
        collected_group.draw(screen)
    File "C:Python32libsite-packagespygamesprite.py", line 475, in draw
        self.spritedict[spr] = surface_blit(spr.image, spr.rect)
AttributeError: 'Coin' object has no attribute 'image'

pygame.sprite.Group.draw()pygame.sprite.Group.update()是由pygame.sprite.Group提供的方法。

前者将包含的pygame.sprite.Sprite委托给update方法-您必须实现该方法。参见pygame.sprite.Group.update():

对组中所有精灵调用update()方法[…]

后者使用包含的pygame.sprite.Sprite s的imagerect属性来绘制对象-您必须确保pygame.sprite.Sprite s具有所需的属性。参见pygame.sprite.Group.draw():

将包含的精灵绘制到Surface参数。这使用Sprite.image属性作为源表面,Sprite.rect。[…]

Coin子类MySpriteMySprite有属性master_image,没有属性image。因此,调用pygame.sprite.Group.draw()将导致错误:

Coin()没有属性'image'

只需将mater_image重命名为image即可解决问题:

class MySprite(pygame.sprite.Sprite):
    def load(self, filename, width=0, height=0, columns=1):
        self.set_image(image e, width, height, columns)
 
    def set_image(self, image, width=0, height=0, columns=1):
        self.image = image
        # [...]

最新更新