我正在创建一个文本冒险游戏,并且希望如果用户键入“x
”或“examine
”,它会打印一个文本冒险游戏的描述room(存储在函数内的字符串中)
这是代码:
def look(dsc):
print(dsc)
def usr_input(dsc):
a = input(">>> ")
if a == "examine" or a == "x":
look(dsc)
if a == "help":
print("north, n, east, e, south, s, west, w, up, u, down, d, inventory, i, examine, x")
if a == "north" or a == "n" or a == "forwards":
return "north"
if a == "east" or a == "e" or a == "right":
return "east"
if a == "south" or a == "s" or a == "backwards":
return "south"
if a == "west" or a == "w" or a == "left":
return "west"
if a == "up" or a == "u":
return "up"
if a == "down" or a == "d":
return "down"
else:
print("Sorry, I don't understand that. (Type 'help' for a list of commands")
usr_input()
return False
def room_00():
room_description = "Description goes here"
print(room_description)
usr_input(room_description)
room_00()
基本上,每当用户键入 x
时,我都需要函数“look
”来打印该房间的描述,但我无法链接这些函数。
你的代码似乎运行没有任何问题,忽略上面的人,Python 3 确实需要括号来进行打印调用。
它返回了一个回溯,因为在第 28 行,您在不提供参数的情况下调用了 usr_input() 函数。
您可以通过如下定义函数来解决此问题:
def look(dsc=''):
print(dsc)
这会将空字符串传递给函数,除非您将其传递给您自己的字符串。
另一个问题是您使用的是原始 if 语句。所以最后的评估在这里:
if a == "down" or a == "d":
return "down"
else:
print("Sorry, I don't understand that. (Type 'help' for a list of commands")
usr_input()
return False
转到else分支,因为x既不是“down”也不是“a”,你应该用elif替换第一个下面的所有if语句,并保留最后一个else
我是一名优秀的程序员,十分优秀!