这个程序相当不言自明。我已经开始学习Python的基础知识了,我对这一点非常迷恋。我习惯于C++和通过引用传递事物的奇妙能力。但是,在这里,我要改变的类变量(战士。守护神)不会改变,我读到这是因为整数是不可变的,它只是在本地创建一个新的对象。那么,我该如何将更改应用于原始变量呢?我搜索了又搜索,但都没有结果。我不想表演一些丑陋的曼纽尔,比如列一张单子,如果不必要的话就传给他。在
#python 3.2.2
# Create a small test project to have combat between two entities. #
# Combat should include 3 different stats: statATK, statDEF, and statHEALTH. #
# The two entities should be of the same class. #
class Fighter:
def __init__(self):
self.statHEALTH = 10
self.statATK = 3
self.statDEF = 3
def attack(self, enemyhealth):
enemyhealth = (enemyhealth - self.statATK)
return enemyhealth
def defend(self):
statDEF += 1
def main():
James = Fighter()
Keaton = Fighter()
while James.statHEALTH > 0:
print("Do you wish to attack or defend?")
print("1. Attack")
print("2. Defend")
choice = input()
if choice == "1":
James.attack(Keaton.statHEALTH)
print("You did", James.statATK, "damage!")
Keaton.attack(James.statHEALTH)
print("Keaton has", Keaton.statHEALTH, "health left.")
print("Keaton did", Keaton.statATK, "damage!")
print("You have", James.statHEALTH, "health left.")
#elif choice == "2":
#James.defend()
#Keaton.attack(James.statHEALTH)
main()
试着做:
然后将类定义为:
^{pr2}$这还有一个很容易扩展的好处,例如,您可以为某些元素添加命中表(
for i in random.randint(1,100) if i < 20: #miss; elif 20 <= i < 80: #hit; elif 80<= i: #crit
)或抵抗,或者添加一个标志,允许您的防御者在其takedamage
函数中进行反击(可能调用一个新函数getcountered
以防止无限循环)。在也许你可以换个角度想。在您的例子中,
Fighter.attack()
只返回攻击后敌人的生命值。所以说真的,它应该是对敌人对象的方法调用。你可以添加一种方法,当战士受到攻击时,降低他们的生命值:如果你把电话改成
^{pr2}$。。因为你
return
攻击造成的伤害。显然,这很难看;重复你自己是不好的。相反,您可以使attack
看起来像:然后就这么做
当你打电话的时候。在
相关问题 更多 >
编程相关推荐