Python - 获取覆盖变量的函数

时间:2015-07-04 14:59:15

标签: python-3.x

所以我正在测试一些基于文本的游戏的机制。如果玩家有护甲,它会使受到的伤害减半,如果没有,则会造成全部伤害。我遇到的问题是,每当我尝试运行两次函数时,它会重置健康状况,因为它已被硬编码。所以我想知道如何在每次运行后获取覆盖运行状况变量的函数?

以下是代码:

import random
inventory = ["Armour","Sword","Healing Potion"]
health=100

def randDmg():
    dealtDamage = random.randint(1,10)
    print("You have taken "+str(dealtDamage)+" damage.")
    return dealtDamage

def dmgCheck(damage, health):
    if "Armour" in inventory:
        damage = damage/2
    else:
        damage = damage
    health-=damage
    return health

print("Your new health is "+str(dmgCheck(randDmg(), health)))

1 个答案:

答案 0 :(得分:0)

在dmgCheck函数的顶部定义一个全局可以正常工作 - 那么你不需要将它作为本地传递。当你在它的时候,如果你在dmgCheck中调用randDmg函数,你就不需要传递它。

import random
inventory = ["Armour","Sword","Healing Potion"]
health=100

def randDmg():
    dealtDamage = random.randint(1,10)
    print("You have taken "+str(dealtDamage)+" damage.")
    return dealtDamage

def dmgCheck():
    global health
    damage = randDmg()
    if "Armour" in inventory:
        damage = damage/2
    else:
        damage = damage
    health-=damage
    return health

print("Your new health is" + str(dmgCheck()))
print("Your new health is" + str(dmgCheck()))

使用pythons的字符串格式化语法也可以简化最后一点:

print("Your new health is %s" % dmgCheck())

使用可以使用的Python类做类似的事情:

import random

class Game(object):

    def __init__(self, inventory, health):
        self.inventory = inventory
        self.health = health

    def randDmg(self):
        dealtDamage = random.randint(1,10)
        print("You have taken "+str(dealtDamage)+" damage.")
        return dealtDamage

    def dmgCheck(self):
        damage = self.randDmg()
        if "Armour" in self.inventory:
            damage = damage/2
        else:
            damage = damage
        self.health -= damage
        return self.health

    def play(self):
        result = self.dmgCheck()
        print("Your new health is %s" % result)



game = Game(["Armour","Sword","Healing Potion"], 100)

game.play()
game.play()