在Python中的多个函数中更改局部变量?

时间:2019-02-26 17:24:47

标签: python python-3.x

背景:我目前正在写一篇基于文字的冒险游戏,每个敌人都有一定的回合次数,可以在攻击返回之前对其进行攻击。 因此,为处理此问题,代码在斗争中的函数中设置了一个参数,指示您可以攻击多少次。

def fight_sequence(rounds):
  while rounds > 0:
    attack = input()
    if attack == magic:
      magic("you teleport away to safety. Congratulations you have stayed alive through your journey and found a few souvenoirs. nice job!", 1, "you muster up all of your energy, chant the spell.... and nothing happens.Cthulu... seems unimpressed", 1, "")
    elif attack == sword:
      sword(1)
def magic(teleportmessage, teleportsuccess, firemessage, firefail, winmessage):
  x = 0
  while x == 0:
    fightorflight = input("""you open the book to cast a spell
    Do you want to try teleporting or use a fireball?""").lower()
    if "teleport" in fightorflight:
      if teleportsuccess = 1:
        print(teleportmessage)
        x = 1
      else:
        choice = input("You can't teleport out of this battle. Would you like to try a fireball?")
        if choice == yes:
          fightorflight = "fireball"
        else:
          x = 1
    elif "fire" in fightorflight:
      print(firemessage)
      if firefail == 1:
        choice = input("do you want to try to teleport instead?").lower()
        if "yes" in choice:
          fightorflight = "teleport"
        else:
          x = 1
      else:
        print(winmessage)
    else:
      print("Sorry not sure what you mean")
def sword(attacksuccess):
  if attacksuccess == 1:
    print("You pull out the sword and swing at the monster damaging it severely.")
  else:
    print("You pull out the sword and swing at the monster, but its immune to blunt objects.")
fight_sequence(3)

magic()和sword()都需要能够将回合数减少1,最初我只是在进入魔术或剑功能之前就这样做了。但是,有些可攻击的物品可以让您多次攻击,因此对他们不起作用。如魔法,如果他们也选择传送。有没有一种方法可以让我在另一个函数内部更改变量回合? 我认为使用返回值可能会有所帮助,但我不确定该怎么做

2 个答案:

答案 0 :(得分:1)

您可以简单地向magic函数添加一个新参数,并在调用它时传递“ rounds”变量。

例如

def fight_sequence(rounds):    
...
    magic("some message", false, "fired", false, "you won", rounds)

def magic(teleportmessage, teleportsuccess, firemessage, firefail, winmessage, rounds):

您通过变量(不仅是值),因此它将在每个可以看到回合的上下文中更改。

HTH。

答案 1 :(得分:0)

我建议使用类而不是大量的功能来创建此游戏,这是下面英雄游戏中的一个示例。

class Hero:
   def __init__(self):
       self.health = 10
   def eatApple(self):
       self.health += 1
   def takeDamage(self):
       self.health -= 1

init函数在类初始化时运行。

player = Hero()
print(player.health) # will print 10
player.takeDamage() 
print(player.health) # will print 9 

这样,您可以为函数使用全局变量,这些变量可以在每个函数中进行更改,并且井井有条。