-1

我是 Python 新手,但请耐心等待。

在我的代码中,我试图通过函数将变量room变为。2west()

代码:

编辑:我已经隔离了大部分非必要的代码。

room = 1

cmds = 'west'.lower()

def isValidCMD(cmd):
    if cmd in cmds:
        return True
    else:
        print("Unknown command. For help type /help, for available options type /options")
        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)
        return False

def runCMD(cmd):
    if cmd == '/help':
        help()
    elif cmd == '/exit':
        exit()
    elif cmd == '/about':
        about()
    elif cmd == '/stats':
        stats()
    elif cmd == '/options':
        options()
    elif cmd == 'north':
        north()
    elif cmd == 'south':
        south()
    elif cmd == 'east':
        east()
    elif cmd == 'west':
        west()
    elif cmd == '/lookaround':
        look_around()

def west():
    if room == 1:
        print("You head on over to the lab, to get some advice from Professor Andrew.")
        return 2 #LINE 40 < -------
    elif room == 7:
        print("You head back to Auderban Square feeling primed for battle.")
    else:
        print("You cannot go west.")
        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)

def main():
    while True:
        # Town 
        if room == 1:
            print("\nYou are at the centre of town, Auderban Square.".upper())
            print("\nYou look at the signpost and see 4 signs.")
            print("\t- North - Twinleaf Forest")
            print("\t- South - Store of Celestia")
            print("\t- East - Deskemon Training Ground")
            print("\t- West - Auderban's Deskemon centre")
        # Lab
        elif room == 2:
            print("You are at Auderban's Deskemon Centre")
            AndrewConv()
            print("\nYou see the exit at the door.")
            print("\t- East - Auderban Square")

        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)
main()

输出:

room保持其价值,1.

请给未来一些建议,这样我就不会犯同样的错误两次。

4

2 回答 2

1

用这个替换west()函数:

def west():
    global room
    ...
于 2014-05-11T15:36:57.663 回答
0

全局变量被广泛认为是不好的编程习惯,因为很难确定在大型程序中何时何地可以修改它们。它们还使得几乎不可能编写线程安全和可重入的代码。

一个简单的方法是让每个函数都接受room作为参数并返回“新房间”。room然后,您可以在每次调用命令时始终更新main 函数中的 。

不过,您最终可能会跟踪的不仅仅是房间。考虑使用像字典或类这样的可变数据结构来存储游戏状态,然后将其传递给您的命令函数。那样的话,跟许多状态变量一样简单,你仍然不需要全局变量。

def main():
    state = {'room': 1}
    while True:
        [...]
        if isValidCMD(cmd, state):
            runCMD(cmd, state)

def west(state):
    thisroom = state['room']
    if thisroom == 1:
        print("You head on over to the lab, to get some advice from Professor Andrew.")
        state.update(room=2)
    elif thisroom == 7:
        print("You head back to Auderban Square feeling primed for battle.")
    else:
        print("You cannot go west.")
        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)

此代码还有一些其他问题。例如,您在每个命令提示符中复制命令提示符代码,这很脆弱且容易出错,而且没有必要,因为main()无论如何您都会返回。

编辑:这是一个最小的可运行示例:

def main():
    state = {'room': 1}
    for i in range(20):
        oldroom = state['room']
        nextroom(state)
        print("Went from room {} to room {}.".format(oldroom, state['room']))

def nextroom(state):
    state['room'] += 2
于 2014-05-12T13:26:08.993 回答