Reputation: 95
I am trying to make a sword appear when I press the space bar and disappear when I hit key 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()
I can make the first sword appear and disappear without any issue, but when I try to press the spacebar again, I get this error message:
File "/Users/(User)/Desktop/ZeldaGame/sprites.py", line 183, in __init__
self.image.set_colorkey(WHITE)
AttributeError: 'Sword' object has no attribute 'set_colorkey'
Here is my Sword class:
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()
Could anyone help me make the sword able to appear, disappear, and appear over and over again?
Upvotes: 1
Views: 44
Reputation: 10819
Warning: I don't know anything about PyGame.
It seems as if game.sword
initially, before the very first sword is created, is a pygame.Surface
object - This is just a guess, because you didn't show that part of the code. (set_colorkey
seems to be a pygame.Surface
method, and by virtue of the fact that you can invoke Sword.__init__
the first time without any errors tells me that game.sword
must initially be a pygame.Surface
object, otherwise self.image.set_colorkey(WHITE)
would raise an error).
Then, the second time you press the spacebar, game.sword
will be refering to a Sword
object, since you executed self.sword = Sword(...
the first time you pressed the spacebar. You enter the second sword's __init__
, but now game.sword
refers to a Sword
, not a pygame.Surface
. Sword
s don't have a set_colorkey
method, hence the error (I'm guessing pygame.Sprite
does not inherit from pygame.Surface
).
Upvotes: 3