2016-06-20 64 views
-4

我很確定這是我可以忽略的最簡單的錯誤。也有類似的問題一次,但不記得我如何解決它爲上帝的愛......返回動態計算

import random 

enemy_hp = 100 
player_hp = 100 
enemy_hit = random.randint(1, 10) 
enemy_meteor = 8 
enemy_heal = 3 
player_hit = random.randint(1,10) 
player_fireball = 5 
player_heal = 7 

def eHit(enemy_hit): 
    player_hp = 100-enemy_hit 
    print (player_hp) 

eHit(enemy_hit) 

好,我編輯它和它的工作作爲intented,但即便如此教程中,我用別的東西鬥爭。

我如何在調整後保存新值,使它不總是從100開始?

+1

我不知道是什麼問題。我不想猜。你願意告訴我們你的代碼有什麼問題嗎? –

+0

我的壞,快速的手指,編輯它 – Limitless

+0

我會認爲你誤解了函數的性質。'def eHit(enemy_hit)'定義一個函數,該函數接受一個名爲'enemy_hit'的參數,而不是使用更大範圍中具有相同名稱的變量。在函數體內,名爲'enemy_hit'的變量將具有傳遞給函數的任何值。有關更多信息,請閱讀:https://docs.python.org/3/tutorial/controlflow.html#defining-functions – Kendas

回答

0

正如你已經編輯了原來的問題,而現在你問

我如何保存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) 
+0

工作,甚至添加文字告訴他他有多少擊中和他仍然有多少馬力。感謝隊友,至少你很好:P – Limitless

1

​​是錯誤的; eHit是一個函數而不是變量。你應該稱呼它print(eHit(somthing))

完全基於變量聲明在開始的名字,我想你的意思print(eHit(enemy_hit))

然後你進入的player_hp是一個局部變量的問題,並賦值之前使用,所以現在你需要改變eHit()

def eHit(enemy_hit, player_hp): 
    player_hp -= enemy_hit 
    return player_hp - enemy_hit 

,現在你的print語句是

print(eHit(enemy_hit, player_hp))

對於您定義的其他功能也是如此。