【问题标题】:Issues with creating objects of classes in Python在 Python 中创建类对象的问题
【发布时间】:2020-03-06 15:38:28
【问题描述】:

我试图让剑在我按下空格键时出现,在我按下键 5 时消失。

if event.type == pg.KEYUP:
                if event.key == pg.K_ESCAPE:
                    self.quit()
                if event.key == pg.K_SPACE:
                    self.sword = Sword(self, self.player.rect.centerx-7, self.player.rect.bottom, self.player)
                if event.key == pg.K_5:
                    self.sword.kill()

我可以毫无问题地让第一把剑出现和消失,但是当我再次尝试按空格键时,我收到以下错误消息:

File "/Users/(User)/Desktop/ZeldaGame/sprites.py", line 183, in __init__
    self.image.set_colorkey(WHITE)
AttributeError: 'Sword' object has no attribute 'set_colorkey'

这是我的剑术课:

class Sword(pg.sprite.Sprite):
    def __init__(self, game, x, y, entity):
        self.groups = game.all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = self.game.sword
        self.image.set_colorkey(WHITE)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        self.rect.x = x 
        self.rect.y = y 
        if entity.direction == 'down':
            self.image = pg.transform.rotate(self.image, -90)

        def update(self):
            kill()

谁能帮我让剑能够出现、消失、反复出现?

【问题讨论】:

  • Sword.kill 到底是做什么的?它似乎试图调用self.set_colorkey 而不是self.image.set_colorkey
  • @chepner Sword.kill() 是 pg.sprite.Sprite 的内置函数,它从精灵组 game.all_sprites 中删除精灵。我正在对 game.all_sprites 中的所有精灵进行 blitting,所以当我使用 Sword.kill() 删除它时,它会停止在屏幕上进行 blit。

标签: python class pygame


【解决方案1】:

警告:我对 PyGame 一无所知。

似乎game.sword 最初,在创建第一把剑之前,是一个pygame.Surface 对象 - 这只是一个猜测,因为您没有显示那部分代码。 (set_colorkey 似乎是一个pygame.Surface 方法,并且由于您可以第一次调用Sword.__init__ 而没有任何错误告诉我game.sword 最初必须是pygame.Surface 对象,否则@987654328 @ 会引发错误)。

然后,第二次按空格键时,game.sword 将引用 Sword 对象,因为您在第一次按空格键时执行了 self.sword = Sword(...。您输入第二把剑的__init__,但现在game.sword 指的是Sword,而不是pygame.SurfaceSwords 没有 set_colorkey 方法,因此会出现错误(我猜 pygame.Sprite 不会继承自 pygame.Surface)。

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2022-01-16
    • 2021-07-04
    • 2013-07-01
    相关资源
    最近更新 更多