user3295674
user3295674

Reputation: 913

pygame: replacing image of an item/enemy

I'm trying to write a program where the image for the 'enemy' I have changes once its health goes to 0. I have different classes for each element, but I have this under this class.

class Enemy(pygame.sprite.Sprite):
    def __init__(self, gs=None):
            pygame.sprite.Sprite.__init__(self)
            ...initialization stuff...
            self.image = pygame.image.load("enemy.png") #enemy image
            self.rect = self.image.get_rectangle()

            self.hp = 40  #initial health

    def damage(self):
           if self.rect.colliderect(self.user.rect): #collision/how the health goes down
                                    self.hp = self.hp - 5 

Now here's the part I'm curious about, I want to load a new image that replaces the old image I have for this enemy. Can I do/add (in the damage function)

           if(self.hp == 0):
                    self.image = pygame.image.load("dead.png")

Will this replace it? Or just load another image on top of it? Let me know what I'm missing, thank you!

Upvotes: 0

Views: 392

Answers (1)

sshashank124
sshashank124

Reputation: 32207

You should load all your images into your init method when you create the object and then you can do the assigning/changing later using lists. Here is an example:

class Enemy(pygame.sprite.Sprite):
    def __init__(self, gs=None):
        pygame.sprite.Sprite.__init__(self)
        self.images = [pygame.image.load("enemy.png"), pygame.image.load("dead.png")]
        self.current_image = self.images[0]
        self.rect = self.current_image.get_rectangle()

Then later you can do:

if(self.hp == 0):
    self.current_image = self.images[1]

This will in fact, as per your concern, replace the current image instead of just drawing over it. Hope that helps.

Upvotes: 2

Related Questions