正如你已經編輯了原來的問題,而現在你問
我如何保存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