Python 3没有正确读取我的输入

时间:2013-12-20 02:21:39

标签: python-3.x input

我正在尝试在python中编写一个基本的文本冒险,只是为了练习,因为我有一段时间没有编码。但是,当我运行我的代码时,它会跳到actionRead()if-elif-else语句的最后并打印else语句。我只能假设这是因为它没有正确读取输入。有帮助吗?这是下面的代码:

action = ""
room = 1

def commandLine():
    action = ""
    action = input("//> ")
    actionRead()

def actionRead():
    if action == "HELP":
        print("Type NORTH to go north, WEST to go west, and so on...")
        commandLine()
    elif action == "NORTH":
        if room == 1:
            room = 2
            look(2)
            commandLine()
        elif room == 4:
            room = 3
            look(3)
            commandLine()
        else:
            print("You can't go that way, stupid.")      
    elif action == "WEST":
        if room == 3:
            room = 2
            look(2)
            commandLine()
        elif room == 4:
            room = 1
            look(1)
            commandLine()
        else:
            print("You can't go that way, stupid.")
    elif action == "EAST":
        if room == 2:
            room = 3
            look(3)
            commandLine()
        elif room == 1:
            room = 4
            look(4)
            commandLine()
        else:
            ("You can't go that way, stupid.")
    elif action == "SOUTH":
        if room == 2:
            room = 1
            look(1)
            commandLine()
        elif room == 3:
            room = 4
            look(4)
            commandLine()
        else:
            ("You can't go that way, stupid.")
    else:
        print("That not a command, grue-for-brains...")
        commandLine()

def look(room):
    if room == 1:
        print("You are in a white room with bandages on the floor. You can go north or east.")
    elif room == 2:
        print("You are in a grey room with paintings on the ceiling. You can go east or south.")
    elif room == 3:
        print("You are in a pitch black room. You are likely to be eaten by a grue. You can go west or south.")
    elif room == 4:
        print("You are in a grey room with a large green splatter on the wall. You can go west or north.")
    else:
        print("An error has occurred. Please restart the game.")

# ACTIONS #

print("What would you like to do? Type HELP for help.")
look(1)
commandLine()

1 个答案:

答案 0 :(得分:0)

您没有将action的结果传递给actionRead()函数。变量在范围内是局部的,如果没有显式传递,则在一个函数中分配的值不能在另一个函数中读取。

您不需要在action = ""中初始化commandLine(),这不是Java:)

一旦你解决了这个问题,你会遇到另一个问题,就是传递你当前所在房间的价值,但是我会把它留给你解决,因为它需要重新修改你的程序。

作为提示,如果变量没有您认为应该具有的值,或者通常您的程序运行不正常,请开始投入print()并查看您提出的内容 - 它'通常会非常有用。

祝你好运!