【问题标题】:Variables reset when calling method调用方法时变量重置
【发布时间】:2016-06-14 08:42:17
【问题描述】:

我正在创建一个基于文本的游戏,它需要你搜索两个地方才能在游戏中前进,但它也有两个虚拟选项会让你误入歧途。这些都不重要。问题是,一旦在选择“if”选项之一之后再次调用该方法,并且其中一个变量设置为 true,它会在最顶部将其设置回 false。

def marketplace():
    searchArmorer=False
    searchBlacksmith=False
    while (searchArmorer==False and searchBlacksmith==False):
        print("Search the:")
        search=input("\n A. The blacksmith \n B. Crocodile Shop \n C. Armorer \n D. Exotic Cheese shop \n")
            if search=="A":
            searchBlacksmith=True
            print("You find some dusty looking copper swords in the corner that the blacksmith says you can borrow. If you haven't got it already, now all you need is some armor. \n")
            marketplace()
        elif search=="B":
            croc=input("You open the door to have a crocodile leap out at you! Will you attempt to fight it, or run away? \n A. Fight \n B. Flee \n")
            #croc fight
            if croc=="A":
                print("You have died. Crocodiles are dangerous.")
                break
            elif croc=="B":
                print("You escape back to the village square. \n")
                marketplace()
            #end of croc fight
        elif search=="C":
            searchArmorer=True
            print("You ask if the armorer has any cheap armor, but he says the cheapest he has is leather. It's not your first choice, but beggars can't be choosers. \n")
            marketplace()
        elif search=="D":
            print("You see nothing that could help you on your quest. \n")
        marketplace()

【问题讨论】:

  • 不记得marketplace()。相反,请使用continue。你没有利用你的循环。

标签: python loops python-3.x methods text-based


【解决方案1】:

“While”循环会一次又一次地执行,直到条件为假,所以你不需要在循环内再次调用该函数。

删除或注释掉所有对marketplace() 的调用,它会正常工作。

另外,如果你使用 if - elif,你也不需要使用continue,因为它只会执行其中一个句子。

【讨论】:

  • 我必须调用它两次,一次是沿着军械库路径,一次是沿着铁匠路径。但是,一旦重新启动,它就会重置两者,因为我必须启动变量。我正在寻找解决方法。
猜你喜欢
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多