2014-12-07 135 views
-2

在下面的代碼中,我想要保存殭屍的健康狀態,並且每次從殭屍的健康狀態中減去50。殭屍的健康應該是100,每次射擊應該是50。我無法保存它。相反,我必須打印它。保存項目時遇到問題

shoot = -50 
zombie_hp = -100 

def zombie1(shoot, zombie_hp): 
    return shoot - zombie_hp 

def attack(): 
    print "You see a zombie in the distance." 
    attack = raw_input("What will you do?: ") 
    print zombie1(zombie_hp, shoot) 
    if attack == "shoot" and shoot == -50: 
     print "Zombie health 50/100" 
     attack2 = raw_input("What will you do?: ") 
     print zombie1(zombie_hp, shoot) 
     if attack == "shoot": 
      print "Zombie health 0/100 (Zombie dies)" 
attack() 
+3

* 「我有麻煩」 * **是**不是一個有用的問題陳述。你期望會發生什麼,而發生了什麼?你似乎沒有試圖*「讓它保存」*。你也永遠不會*賦值''zombie1'返回的值。如果你想保留「殭屍」的狀態,考慮製作一個「殭屍」類。 – jonrsharpe 2014-12-07 18:32:16

回答

0

考慮以下幾點:

damage = 50 
zombie_hp = 100 

def attack(): 
    global zombie_hp #1 
    zombie_hp -= damage #2 
    print "Zombie health %s/100"%zombie_hp #3 
    if zombie_hp <= 0: 
     print "Zombie dies" 

print "You see a zombie in the distance." 
while zombie_hp > 0: #4 
    user_input = raw_input("What will you do?: ") 
    if user_input == 'shoot': 
     attack() 
  1. 利用全球zombie_hp改變outter zombie_hp,否則它不會改變
  2. 這將減去從zombie_hp損害
  3. 這將以適當的方式打印當前的殭屍HP。不需要自己輸入。
  4. 這部分將保持程序的運行,直到殭屍死

正如@jonrsharpe指出,考慮制定殭屍類。

像這樣:

class Zombie: 
    def __init__(self): 
     self.hp = 100 

def attack(target): 
    target.hp -= DAMAGE 
    print "Zombie health %s/100"%target.hp 
    if target.hp <= 0: 
     print "Zombie dies" 


DAMAGE = 50 
zombie1 = Zombie() 

print "You see a zombie in the distance." 
while zombie1.hp > 0: 
    user_input = raw_input("What will you do?: ") 
    if user_input == 'shoot': 
     attack(zombie1) 
相關問題