我正在创建一个文本冒险游戏,通过用户输入调用函数。在 start() 中输入 1 会调用 start_observe,但 2 会调用 start()。为什么?



下面是带有可用选项的代码。我不知道发生了什么!

def start():
slow_print("""_

It's Monday, 9:33pm, August 4th, 2024.
You lay in the back of an old truck headed ...yada yada... emember the last time you were awake.
Enter (1) to observe your surroundings.
Enter (2) to scream your lungs out.
Enter (3) to climb out of the truck.
Enter (4) to hear what's going on around you.

_""", 1)
choice = input("--> ")
reset_console()

"1";调用start_observe(),但是"2"不调用start_scream(),我很困惑!

if "1" in choice:
start_observe()
else:
start()
if "2" in choice:
start_scream()
else:
start()
if "3" in choice:

我唯一能想到的是我没有正确缩进,或者函数没有按照它们需要的顺序排列(尽管我测试了它,但这不是它)。

更新,我把它改成这个嵌套的if语句风格,它工作了,如果我以这种方式更新,我会遇到任何进一步的问题吗?

choice = input("--> ")
reset_console()

if "1" in choice:
start_observe()
else:
if "2" in choice:
start_scream()
else:
if "3" in choice:
start_climb()
else:
if "4" in choice:
start_hear()
else:
start()

还有,谢谢你Luther的帮助!

更新#2:哈哈,好吧,我很笨。在我意识到else: if = elif之后,我就这样做了。哈哈哈。

if "1" in choice:
start_observe()
elif "2" in choice:
start_scream()
elif "3" in choice:
start_climb()
elif "4" in choice:
start_hear()
else:
start()

假设choice'2',代码如下:

if "1" in choice: # False
start_observe()
else: # This clause runs.
start()

如果这段代码在start函数中,它将在代码运行后开始递归调用。

相关内容

最新更新