如果输入的输入被视为"invalid",则尝试继续请求输入

  • 本文关键字:继续 请求 invalid 如果 python loops
  • 更新时间 :
  • 英文 :


这是我为CS类制作的文本冒险游戏的一小部分。你正在探索一所房子,你可以通过告诉游戏你想去北方、南方、东方还是西方来导航
所以我想添加一些内容来告诉你,当你输入了一个无效的输入时,如果你说的是Nroth、Suoth、Eas或Weast等拼写错误的单词。这些只是例子,但希望你知道我的意思,只要它不完全匹配北方、南方、东方或西方。在这段代码中,我该如何做到这一点?

我举了一个例子,如果你拼写错误,我想输出一个错误,上面写着"elif room=="门廊"但它应该继续询问你想去哪个方向,即使你出现错误,因为到目前为止,它仍在继续询问你要去哪个方向。无论你输入了什么,它都不会根据你进入的房间输出应该说的文本。

def pickRoom(direction, room):
if(direction == "quit") or (direction == "exit"):
print("Better luck next time!")
return "Exit"
elif room == "Porch":
if direction == "North":
return "Pantry"
else:
print("That is not a valid entry!")
elif room == "Pantry":
if direction == "North":
return "Kitchen"
elif direction == "East":
return "DiningRoom"
elif room == "DiningRoom":
if direction == "West":
return "Pantry"
elif room == "Kitchen":
if direction == "West":
return "LivingRoom"
elif direction == "East":
return "Bedroom"
elif room ==  "Bedroom":
if direction == "West":
return "Kitchen"
elif room == "LivingRoom":
if direction == "West":
return "Bathroom"
elif direction == "North":
return "Stairs"
elif room == "Bathroom":
if direction == "East":
return "LivingRoom"
elif room == "Stairs":
if direction == "South":
return "Bar"
elif room == "Bar":
if direction == "East":
return "Shop"
elif room == "Shop":
if direction == "North":
return "Closet"
elif direction == "South":
return "Storage"
elif room == "Storage":
if direction == "North":
return "Shop"
elif room == "Closet":
if direction == "South":
return "Shop"

如果您需要更大的代码部分,甚至整个.py文件来解决问题,请告诉我,谢谢。

elif room.lower() in ('perch','peach','pooch'):

你可以列出一大堆你想指出的拼写错误。如果他们的选择不正确,请检查他们输入的值是否在此列表中。

我不确定你需要什么,但这可能会有所帮助:

directions = ["south", "west", "east", "north"]
while True:
move = input("Choose which way you would like to gon")
if move.lower() in directions:
print("You have chosen to go " + move)
else:
print("Invalid move!")

只要有一个想法,这就是一个输出:

>>Choose which way you would like to go
north
>>You have chosen to go north
>>Choose which way you would like to go
North
>>You have chosen to go North
>>Choose which way you would like to go
nothr
>>Invalid move!
>>Choose which way you would like to go

您可以尝试根据正确选择的列表进行测试。我希望这能有所帮助!

if room in roomList:
# availableDirection is a dictionary that 
# has rooms as keys and valid directions as values.
if direction in availableDirection[room]:
# return the next room from a dictionary representing the 
# current room where the key is direction and value is the next room.
else:
return "Invalid direction"
else:
return "Invalid room"

为了保持在显示的代码部分内,根据请求,只需在末尾添加

else:
print("Sorry, that does not make sense to me.")
return room

通过这种方式,您可以解决当前问题,即在编程选项与输入不匹配的情况下,不可预测的值将重新调整为新的当前房间。在这种情况下,通过返回参数room,存储当前房间的变量将继续使用有效房间(当前房间(。

当返回一个不可预测的值时,它很可能不是正确的房间名称之一,这是保持逻辑结构正常运行所必需的。一旦房间变量包含垃圾,它就再也无法匹配任何选项,因此再也不会输出任何有意义的内容。

作为防止房间最终成为垃圾的额外预防措施(任何数量的可能事故之一(,您可以检查房间是否是现有的房间,否则将其重置为默认房间,或者退出并返回错误消息
"哎呀,意外传送到未知空间。下次地球再见。">

最新更新