从另一个函数

时间:2015-08-05 20:53:08

标签: python text-based adventure

我正在使用python中基于文本的冒险游戏。没有什么超级花哨的。我希望在2个不同的房间里有一个杠杆,在第三个房间打开一扇门。需要拉动两个杠杆才能解锁门。

这是带杠杆的两个房间。

def SnakeRoom():

    choice = raw_input("> ")

    elif "snake" in choice:
        FirstRoom.SnakeLever = True
        print "As you pull the lever... You hear something click down the hall behind you."
        SnakeRoom()
    elif "back" in choice:
        FirstRoom()
    else:
        dead("Arrows shoot out from the walls. You don't make it.")

def WolfRoom():

    choice = raw_input("> ")

    elif "wolf" in choice:
        FirstRoom.WolfLever = True
        print "As you pull the lever... You hear something click down the hall behind you."
        WolfRoom()
    elif "back" in choice:
        FirstRoom()
    else:
        dead("Arrows shoot out from the walls. You don't make it.")

这是带门的房间。

def FirstRoom():
    Lever = WolfLever and SnakeLever
    choice = raw_input("> ")

    if "straight" in choice and Lever != True:
        print "You see a large gate in front of you. The gate is locked, there doesn't seem to be any way to open it."
        FirstRoom()
    elif "straight" in choice and Lever == True:
        SecondRoom()
    elif "left" in choice:
        WolfRoom()
    elif "right" in choice:
        SnakeRoom()
    elif "lever" in choice:
        print "WolfLever: %s" % WolfLever
        print "SnakeLever: %s" % SnakeLever
        print "Lever: %s" % Lever
        FirstRoom()

我缩短了代码,因此您不必阅读所有不必要的内容。

我最大的问题是我还不熟悉Python语言,所以我不确定如何用词汇来找到我想要的答案。

编辑:而不是FirstRoom.WolfLever我也尝试使用WolfLever,在我的代码正文中,在Start()上面我有:

WolfLever
SnakeLever
Lever = WolfLever and SnakeLever

但我的功能并没有更新这些值。所以我尝试了FirstRoom。方法

1 个答案:

答案 0 :(得分:1)

归功于@Anthony和以下链接:Using global variables in a function other than the one that created them

Globals肯定是答案(除了使用类)。这就是我的WolfRoom()和SnakeRoom()函数现在的样子:

def WolfRoom():
    global WolfLever

    choice = raw_input("> ")

    elif "wolf" in choice:
        WolfLever = True
        print "As you pull the lever... You hear something click down the hall behind you."
        WolfRoom()

对于FirstRoom(),我添加了

global Lever

到函数的开头,在Start()之前我有

WolfLever = False
SnakeLever = False

这样我就没有错误或警告(在将它们声明为全局之前获得了为我的杠杆赋值的语法警告)并且一切都运行良好。