1

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

在一个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()

这里的碰撞是成功的,因为它将文本打印到屏幕上。然后它继续检查_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/TuAZxUkqhttp://pastebin.com/kmYytiYV

和错误:

Traceback (most recent call last):
    File "C:\Users\User\Desktop\Coins!\Coins!.py", line 129, in <module>
        collected_group.draw(screen)
    File "C:\Python32\lib\site-packages\pygame\sprite.py", line 475, in draw
        self.spritedict[spr] = surface_blit(spr.image, spr.rect)
AttributeError: 'Coin' object has no attribute 'image'
4

1 回答 1

0

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

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

调用update()组中所有 Sprite 的方法 [...]

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

将包含的 Sprite 绘制到 Surface 参数。这使用Sprite.image源表面的属性和Sprite.rect。[...]

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

Coin() 没有属性“图像”

只需重命名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
        # [...]
于 2020-12-21T14:07:09.283 回答