这是我为CS课制作的文字冒险游戏的一小部分。您正在探索一所房子,并通过告诉游戏是否要向北,向南,向东或向西走来导航。
因此,如果您输入了错误的单词(例如Nroth,Suoth,Eas或Weast)之一,则我想添加一些内容来告诉您输入无效的内容。这些只是示例,但希望您理解我的意思,即使它与北,南,东或西不完全匹配。
在该部分代码中我该怎么做?
我举了一个错误的例子,如果您在拼写错误中显示“ elif room ==“ porch”,但我想输出该错误,但是即使出现该错误,它也应该继续询问您要去哪个方向因为到目前为止,它继续询问您要去哪个方向,而无论您输入什么内容,它都不会输出根据您输入的房间而应该说的文字。
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文件来找出答案,谢谢。
答案 0 :(得分:0)
elif room.lower() in ('perch','peach','pooch'):
您可能只想列出所有要指出的错误拼写。如果他们做出的选择不正确,请检查他们输入的值是否在此列表中。
答案 1 :(得分:0)
我不确定您需要什么,但这可能会有所帮助:
directions = ["south", "west", "east", "north"]
while True:
move = input("Choose which way you would like to go\n")
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
答案 2 :(得分:0)
您可以尝试根据正确的选择列表进行测试。我希望这会有所帮助!
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"
答案 3 :(得分:0)
要按照要求保留在所示的代码部分内,只需在末尾添加
else:
print("Sorry, that does not make sense to me.")
return room
这样,您可以解决当前问题,在没有与输入匹配的已编程选项的情况下,不可预测的值将重新调整为新的当前房间。在这种情况下,通过返回参数room
,存储当前房间的变量将继续一个有效房间(当前房间)。
当返回一个不可预测的值时,它很可能不是正确的房间名称之一,为了使逻辑结构保持正确,它需要使用正确的房间名称。一旦room变量包含垃圾,它将再也无法匹配任何选项,因此不再输出任何有意义的信息。
作为防止房间垃圾(由于任何可能的事故之一)的额外预防措施,您可以检查房间是否为现有房间之一,否则将其重置为默认房间-或出现错误消息退出< br /> “糟糕,意外传送到未知空间。下次再见。”