无法保存物品

时间:2014-12-07 17:12:11

标签: python python-2.7

在下面的代码中,我想拥有僵尸保存的健康状态,每次我从僵尸的健康状况中减去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()

1 个答案:

答案 0 :(得分: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. 造成的伤害
  4. 这将以适当的方式打印僵尸的当前hp。无需自己输入。
  5. 此部分将使程序保持运行直至僵尸死亡

  6. 正如@jonrsharpe所说,考虑制作一个Zombie类。

    像这样:

    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)