-2

我正在用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。方法。

4

1 回答 1

1

感谢@Anthony 和以下链接:在创建它们的函数之外的函数中使用全局变量

全局变量绝对是答案(除了使用类)。这是我的 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

这样我就没有错误或警告(在将它们声明为全局之前,我收到了为我的杠杆分配值的语法警告)并且一切正常。

于 2015-08-05T21:45:24.803 回答