保存项目时遇到问题

问题描述:

在下面的代码中,我想要保存僵尸的健康状态,并且每次从僵尸的健康状态中减去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

考虑以下几点:

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)