我正在制作一个个人冒险游戏项目,但似乎无法在一个函数中运行此代码,
current_room = "South"
def go_to_room():
if "go" in main_input:
if "north" in main_input:
current_room = "North"
while True:
main_input = input(str())
go_to_room(main_input)
print("You are in the " + current_room + " room.")
当我运行它并键入“向北”时,它会返回
You are in the South room
但是如果我这样写代码,
current_room = "South"
while True:
main_input = input(str())
if "go" in main_input:
if "north" in main_input:
current_room = "North"
print("You are in the " + current_room + " room.")
它完美地工作。
那么有人可以帮助我,告诉我我做错了什么吗?
答案 0 :(得分:0)
问题是范围。 main_input
仅在go_to_room
的范围内更改,因此该值在函数外将保持不变。同样,函数永远不会被调用,只需定义它即可。在这种情况下,我建议将参数传递给函数以使其起作用。
current_room = "South"
def go_to_room(room):
if "go" in room:
if "north" in room:
return "North"
while True:
main_input = input("Room: ")
current_room = go_to_room(main_input)
print("You are in the " + current_room + " room.")
答案 1 :(得分:0)
您必须调用该函数。
while True:
main_input = input(str())
go_to_room()
print("You are in the " + current_room + " room.")
答案 2 :(得分:0)
尝试这样写:
current_room = "South"
def go_to_room(user_input):
if "go" in user_input:
if "north" in user_input:
global current_room
current_room = "North"
while True:
main_input = input()
go_to_room(main_input)
print("You are in the " + current_room + " room.")
答案 3 :(得分:0)
在代码的第一部分中,您没有调用函数go_to_room()
。因此,当您运行此代码时,您将停留在while循环中,这就是为什么输出为
You are in the South room
在代码的第二部分中,您检查了given_input
是go' and
北`之一。
如果发现这是正确的,则仅current_room
的值更改为North
。然后您将得到相应的输出。