我想让我在按下空格键时出现一把剑,而在按下键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()
谁能帮助我使剑能够出现,消失以及一遍又一遍地出现?
答案 0 :(得分:3)
警告:我对PyGame一无所知。
在创建第一把剑之前,game.sword
最初似乎是pygame.Surface
对象-这只是一个猜测,因为您没有显示代码的那部分。 (set_colorkey
似乎是一种pygame.Surface
方法,并且由于您可以在没有任何错误的情况下首次调用Sword.__init__
的事实告诉我game.sword
最初必须是一个pygame.Surface
对象,否则self.image.set_colorkey(WHITE)
会引发错误)。
然后,第二次按下空格键时,game.sword
将引用Sword
对象,因为您是第一次按下空格键时执行了self.sword = Sword(...
。您输入第二把剑的__init__
,但是现在game.sword
指的是Sword
,而不是pygame.Surface
。 Sword
没有set_colorkey
方法,因此出现错误(我猜pygame.Sprite
不会继承自pygame.Surface
)。