Reputation: 23
I'm really new to the concept of classes in Python so please excuse my lack of understanding... I'm trying to make a basic and simple fighting RPG based off a YouTube tutorial I saw a while back. I had the idea that your character's health would be based on "90 + level * 10". And this worked great up until I tried to level my character, to find that the level increased but the health stayed the same as when I first loaded the program. I understand why it's doing this but is there a way to almost bypass and get it to update based on the level?
Here's a bit of the code
class Player:
def __init__(self):
self.level = 1
self.maxhealth = 90 + self.level * 10
self.health = self.maxhealth
PlayerIG = Player()
Upvotes: 0
Views: 77
Reputation: 525
__init__
is only run when you instantiate your class. I'm guessing you are currently updating a player's level doing PlayerIG.level +=1
. If you do that __init__
is not ran again and therefore the maxhealth is not updated so you are going to want a level up method.
class Player:
def __init__(self, level): # allows you to create a player of level != 1
self.level = level
self.maxhealth = 90 + self.level * 10
self.health = self.maxhealth
def level_up(self):
self.level += 1
self.maxhealth += 10
PlayerIG = Player(1) # creates a player of level 1 and maxhealth 100
PlayerIG.level_up() # PlayerIG is now level 2 with a maxhealth of 110
Upvotes: 0
Reputation: 780871
Define health
as a function, not a property
class Player:
def __init__(self):
self.level = 1
self.maxhealth = 90 + self.level * 10
def health(self):
return 90 + self.level * 10
PlayerIG = Player()
print(PlayerIG.health())
or provide a function that updates health
, and call it whenever you level up.
class Player:
def __init__(self):
self.level = 1
self.update_health()
def update_health(self):
self.health = 90 + self.level * 10
def level_up(self):
self.level += 1
self.update_health()
Upvotes: 2