user2291164
user2291164

Reputation: 21

How to call class attributes for a child class

The question is a little misleading, sadly. I can't quite find a good way to ask my question. I'm making a small text-based rpg. I'm stuck on how to say "hey, this enemy has spawned, load its attributes."

I have:

class Entity:
    def __init__(self, ID, name,  maxhealth, health, strength, defence, strBuff, defBuff):
        self.ID = ID
        self.name = name
        self.maxhp = maxhealth
        self.hp = health
        self.Str = strength
        self.Def = defence
        self.strBuff = strBuff
        self.defBuff = defBuff

class Monster(Entity):
    pass

Goblin = Monster(0, "Goblin", 10, 10, 5, 2, 0, 0)
goblin = {"ID": Goblin.ID, "name": Goblin.name, Goblin.hp: 10, Goblin.Str: 5, Goblin.Def: 2, Goblin.strBuff: 0, Goblin.defBuff: 0}
Satyr = Monster(1, "Satyr", 5, 5, 3, 6, 0, 0)
satyr = {"ID": Satyr.ID, "name": Satyr.name, Satyr.hp: 5, Satyr.Str: 3, Satyr.Def: 6, Satyr.strBuff: 0, Satyr.defBuff: 0}

And I can't quite find a way to say something like.

Monster.hp -= Player.Str

I can only seem to do it with specified enemies.

Upvotes: 0

Views: 44

Answers (1)

Lucas S.
Lucas S.

Reputation: 702

Your are creating two goblin and satyr dictionaries. They are not needed, as they contain the same data than the two objects Goblin and Satyr.

Instead, you can work with those two objects directly.

Below, I added a __str__ method to print information about an Entity, and I also added a hit method for one Entity to hit another.

Is this answering your question?

class Entity:
    def __init__(self, ID, name,  maxhealth, health, strength, defence, strBuff, defBuff):
        self.ID = ID
        self.name = name
        self.maxhp = maxhealth
        self.hp = health
        self.Str = strength
        self.Def = defence
        self.strBuff = strBuff
        self.defBuff = defBuff

    def __str__(self):
        return self.name + " has " + str(self.hp) + "HP"

    def hit(self, otherEntity):
        print(self.name + " hits " + otherEntity.name + "!!")
        otherEntity.hp -= self.Str

class Monster(Entity):
 pass

goblin = Monster(0, "Goblin", 10, 10, 5, 2, 0, 0)
satyr = Monster(1, "Satyr", 5, 5, 3, 6, 0, 0)

print(goblin)
print(satyr)
satyr.hit(goblin)
print(goblin)
print(satyr)
goblin.hit(satyr)
print(goblin)
print(satyr)

Output:

Goblin has 10HP
Satyr has 5HP
Satyr hits Goblin!!
Goblin has 7HP
Satyr has 5HP
Goblin hits Satyr!!
Goblin has 7HP
Satyr has 0HP

Upvotes: 2

Related Questions