正如你已经编辑了原来的问题,而现在你问
我如何保存calulation后的新值,以便它不以100总是 开始?
需要return
新值,并分配给player_hp
变量和移动的enemy_hit
的随机所以它其实需要一个新的价值,你叫eHit()
之前,像这样
import random
enemy_hp = 100
player_hp = 100
enemy_meteor = 8
enemy_heal = 3
player_hit = random.randint(1,10)
player_fireball = 5
player_heal = 7
def eHit(enemy_hit, player_hp):
player_hp = player_hp - enemy_hit
return player_hp
while player_hp > 0:
enemy_hit = random.randint(1, 10)
player_hp = eHit(enemy_hit, player_hp)
print (player_hp)
我已经把while player_hp > 0
在那里用于测试目的
想想这个,我会再做一次有点不同,下面的代码让你可以自己试试这个:
import random
player_hp = 100
def random_hit(start = 1, stop = 10):
return random.randint(start, stop)
def enemy_hit(player_hp):
return player_hp - random_hit()
while player_hp > 0:
player_hp = enemy_hit(player_hp)
print (player_hp)
现在你可以调用random_hit()
默认,或改变参数“做大”打像random_hit(20, 30)
,你也可以拨打random_hit()
其他功能,无需重复分配。
而且你可以采取进一步的是,作为一个命中是一个打击,不管是谁打谁,所以没有双重功能,这样的事情:
import random
player_hp = 100
enemy_hp = 100
def hit(hp, start = 1, stop = 10):
return hp - random.randint(start, stop)
while player_hp > 0: ## while loop only for testing purposes
# for a enemy hitting a player with normal force, call this:
player_hp = hit(player_hp)
print (player_hp)
while enemy_hp > 0: ## while loop only for testing purposes
# for a player hitting an enemy with extra force, call this:
enemy_hp = hit(enemy_hp, 10, 20)
print (enemy_hp)
我不知道是什么问题。我不想猜。你愿意告诉我们你的代码有什么问题吗? –
我的坏,快速的手指,编辑它 – Limitless
我会认为你误解了函数的性质。'def eHit(enemy_hit)'定义一个函数,该函数接受一个名为'enemy_hit'的参数,而不是使用更大范围中具有相同名称的变量。在函数体内,名为'enemy_hit'的变量将具有传递给函数的任何值。有关更多信息,请阅读:https://docs.python.org/3/tutorial/controlflow.html#defining-functions – Kendas