Dom*_*nto 10 python python-3.x
我是python的初学者.作为大多数初学者,我正在尝试制作基于文本的RPG.我终于得到了升级系统,并且处于另一个障碍.当角色升级时,他们会将x技能点分配给技能(将x添加到变量x次).其中两个变量会影响字符的运行状况,但是,当用户更改这两个变量时,运行状况变量保持不变.我已经简化了我的代码以便于阅读(因为我上面的散文从lol开始并不是那么清楚):
class Char:
def __init__(self, x, y):
self.str = x
self.con = y
self.hp = (self.con + self.str) / 2
player = Char(20, 20)
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)
main(player)
Run Code Online (Sandbox Code Playgroud)
虽然在这种情况下这些变量可以增加10,但hp保持在20
我该如何解决这个问题?
谢谢!
Kin*_*ley 10
每当Char的属性更新时,代码都需要重新计算HP.
所有这些代码最好放在Char对象中:
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)
Run Code Online (Sandbox Code Playgroud)