Variable X not updating when variables that should effect X change
The hp
attribute does not change when the str
or con
change. The only time it is set is in the constructor. You could define an update method to Char
like this:
class Char:
def __init__(self, x, y):
self.str = x
self.con = y
self.update()
def update(self):
self.hp = (self.con + self.str) / 2
and call it at the end of main
:
def main(dude):
print("strength: " + str(dude.str))
print("constitution: " + str(dude.con))
print("hp: " + str(dude.hp))
print("------")
action = input("press 1 to change str, 2 to change con")
if action == "1":
dude.str = dude.str + 10
main(dude)
elif action == "2":
dude.con = dude.con + 10
main(dude)
else:
main(dude)
dude.update()
Because you evaluate the hp
attribute only in the __init__()
method, i. e. only in your statement
player = Char(20, 20)
The most quick fix (not a very nice one, but a very simple) is to create a new instance of Char after each change:
if action == "1":
dude.str = dude.str + 10
dude = Char(dude.str, dude.con) # new dude (with current str and con)
main(dude)
elif action == "2":
dude.con = dude.con + 10
dude = Char(dude.str, dude.con) # new dude (with current str and con)
main(dude)
Whenever the Char's attributes are updated, the code needs to re-compute the HP.
All this sort of code is best put inside the Char
object:
class Char:
def __init__(self, x, y):
self.str = x
self.con = y
self.setHP()
def __str__(self):
text = "strength: " + str(self.str) + "\n" +\
"constitution: " + str(self.con) + "\n" +\
"hp: " + str(self.hp)
return text
def setHP(self):
self.hp = (self.con + self.str) / 2
def adjustStr(self, amount):
self.str += amount
self.setHP()
def adjustCon(self, amount):
self.con += amount
self.setHP()
def main(dude):
print(str(dude))
print("------")
action = input("press 1 to change str, 2 to change con")
if action == "1":
dude.adjustStr(10)
main(dude)
elif action == "2":
dude.adjustCon(10)
main(dude)
else:
main(dude)
player = Char(20, 20)
main(player)