Skip to content Skip to sidebar Skip to footer

Working On Classes For A Text Based Game In Python

i'm trying to create a function to raise max hp whenever a stat is increased or decreased. i have tried changing self.maxHpCalc() player.** moving the variables = (int) into the

Solution 1:

Here's some fixed code, with a small driver program to exercise the classes.

Note the following changes

  1. The function maxHpCalc should be a bound method, if it is to operate on data contained in a player instance. Therefore it should have a self parameter and should reference strength and defense from that self reference.
  2. When calling _maxHpCalc you should reference self. I made it a bound method and it needs an instance to work on. I added an underscore to indicate it's a private method.
  3. You should call maxHpCalcafter setting the values of strength and defense, otherwise they are not defined at the point the function is called.
  4. player.maxHp makes no sense. player is a class and has no static property maxHp, you need an instance to access that property. I create an instance and reference that.

code:

classplayer:
    def__init__(self, hp=1, maxHp=1, strength=4, defense=5):
        self.hp = hp
        self.strength = strength
        self.defense = defense
        self.maxHp = self._maxHpCalc()

    def_maxHpCalc(self):
        return self.strength + self.defense

classorc(player):
    def__init__(self, hp, maxHp, strength , defense):
        super().__init__(hp, maxHp, strength, defense)

p = player()
o = orc(1,2,3,4)

print(p.maxHp)
print(o.maxHp)

I also have to ask, why include a constructor parameter maxHp if you don't use it but calculate it from other parameters?

Post a Comment for "Working On Classes For A Text Based Game In Python"