我对python代码中的嵌套if语句有疑问。我想知道我是否可以在while循环中有两个if语句,它们都有一个嵌套的if语句。然后,该人将能够从嵌套的if语句或其他while循环if语句进行回复。对我的代码的任何想法将不胜感激。
这是我想要制作的游戏的代码示例。我正在努力学习并将新技能融入其中,所以这是我的问题。
有没有办法让它当我在问题输入中键入“向前看”时,对于第二个输入我说“向后看”而不是“去那里”然后输入可以用于输入问题而不是move_on输入?
def first_room():
print("Your in a room how to get out...")
next_room = True
while next_room:
question = input()
if question == "look forward".lower():
print("You are looking forward")
move_on = input()
if move_on == 'go there'.lower():
next_room = False
second_room()
else:
pass
if question == 'look backward'.lower():
print("You are looking backward")
move_on = input()
if move_on == 'go there'.lower():
next_room = False
third_room()
else:
pass
def second_room():
print("This is the second room")
def third_room():
print("This is the third room")
first_room()
答案 0 :(得分:1)
我可以'测试它,但我认为它可能是这样的
我使用True/False
的变量来记住游戏的"state"
BTW:如果你在另一个功能中运行一个房间,你将隐藏"递归"。最好返回函数名称(不带()
)并在函数外运行。
def first_room():
print("Your in a room how to get out...")
looking_forward = False
looking_backward = False
while True:
question = input().lower()
if question == "look forward":
if not looking_forward:
print("You are looking forward")
looking_forward = True
looking_backward = False
else:
print("You are already looking forward, so what next")
elif question == 'look backward':
if not looking_backward:
print("You are looking backward")
looking_forward = False
looking_backward = True
else:
print("You are already looking backward, so what next")
elif question == 'go there':
if looking_forward:
return second_room # return function name to execute outside
if looking_backward:
return third_room # return function name to execute outside
else:
print('Go where ???')
def second_room():
print("This is the second room")
def third_room():
print("This is the third room")
# --------------------------------
next_room = first_room # assign function without ()
while next_room is not None:
next_room = next_room() # get function returned from function
print("Good Bye")
答案 1 :(得分:1)
受到furas关于递归的评论的启发,我想知道如何处理具有一般功能的任何房间。在目前的设计中,许多房间需要很多功能,它们将一遍又一遍地使用大量相同的代码。如果每个房间都以某种方式“特殊”,需要特定的代码,这可能是不可避免的。另一方面,如果你有一种通用的方式来导航房间,你可以节省很多工作。
所以我想,也许你可以用一些常见的形式存储房间属性,并且有一个通用功能,要求玩家输入并建议他们可以做什么。作为“常见形式”,我在这里选择了一个词典列表,认为它是最容易使用的。
每个列表索引(零索引的+1)对应于房间号,例如, roomlist[0]
是第一个房间。每个词典都存储了我们需要了解的关于房间的信息,例如:您可以查看哪个方向以及该方向与哪个房间相连。您也可以稍后使用有关每个房间的其他信息来扩展字典。 (如某些房间的特殊功能)
我的尝试:
# Room dictionaries: Each key is a direction and returns the
# room number it connects to. E.g. room1 'forward' goes to room2.
room1 = {'forward': 2,
'backward': 3}
room2 = {'forward': 4,
'backward': 1,
'left': 3}
room3 = {'forward': 5,
'backward': 1,
'right': 2}
roomlist = [room1, room2, room3]
def explore_room(roomindex, room):
# roomindex is the list index (not room number) of the selected room.
# room is the dictionary describing the selected room.
question = None
move_on = None
print("You are in room %s, how to get out..." % (roomindex+1))
# Room number added to help you keep track of where you are.
next_room = True
while next_room:
if question == 'exit' or move_on == 'exit':
break
# If the user replied 'exit' to either question the loop breaks.
# Just to avoid an infinite loop.
question = input().lower()
# Added the .lower here so we don't have to repeat it in each if.
# Pick a direction. The response must be valid AND
# it must be a valid direction for the current room.
if question == "look forward" and 'forward' in room.keys():
print("You are looking forward")
direction = 'forward'
elif question == 'look backward' and 'backward' in room.keys():
print("You are looking backward")
direction = 'backward'
elif question == 'look left' and 'left' in room.keys():
print('You are looking to the left')
direction = 'left'
# ...
else:
print('There is nowhere else to go!')
continue
# Start the loop over again to make the user pick
# a valid direction.
# Choose to move on or stay put.
move_on = input().lower()
if move_on == 'yes':
roomindex = room[direction]-1
# Direction is the dictionary key for the selected direction.
# Room number is roomindex-1 due to zero-indexing of lists.
return roomindex
# Exits explore_room and tells you which room to go to next.
elif move_on == 'no':
continue # Ask for a new direction.
else:
print('Please answer yes or no')
continue # Ask for a new direction.
return None
# No room selected. While return None is implicit I included it here for clarity.
roomindex = 0
while True:
if roomindex is None:
# User exited the function without choosing a new room to go to.
break
roomindex = explore_room(roomindex, roomlist[roomindex])
你在1号房间,如何出去......
期待
你期待
是的你在2号房间,怎么出去......
向左看
你正在向左看
是的你在3号房间,怎么出去......
向后看
你正在向后看
是的你在1号房间,如何出去......
退出没有其他地方可去!
>
我承认,是/否是不是最有启发性的方法。您可能还想在输入中添加实际问题,这样玩家就可以知道对它们的期望。但总的来说,这似乎很有效,你可以很容易地添加和互连任意数量的房间。所有这些都应该只使用一个功能。
关于ifs的链接和嵌套: 嵌套的ifs通常都没问题,但正如furas所说,它们可能会失控并使代码膨胀。但是,在您的情况下,您不需要嵌套ifs。如我的示例所示,您可以先询问方向,然后检查玩家是否想要去那里单独。这两个是完全独立的,因此不需要嵌套语句。
一个基本的单问题变体,再次受到furas原始答案的启发:
def explore_room(roomindex, room):
# roomindex is the list index of the selected room.
# room is the dictionary describing the selected room.
question = None
print("You are in room %s, how to get out..." % (roomindex+1))
# Roomnumber added to help you keep track of where you are.
next_room = True
while next_room:
if question == 'exit':
break
# If the user replied 'exit' to either question the loop breaks.
# Just to avoid an infinite loop.
question = input('Choose an action: ').lower()
# Added the .lower here so we don't have to repeat it each time.
# Pick a direction. The response must be valid AND
# it must be a valid direction in this room.
if question == "look forward" and 'forward' in room.keys():
print("You are looking forward")
direction = 'forward'
elif question == 'look backward' and 'backward' in room.keys():
print("You are looking backward")
direction = 'backward'
elif question == 'look left' and 'left' in room.keys():
print('You are looking to the left')
direction = 'left'
# ...
elif question == 'move':
roomindex = room[direction]-1
return roomindex
# Fails if player selects 'move' before picking a direction.
# It's up to you how you want to handle that scenario.
else:
print('Valid actions are "look forward/backward/left/right" and "move". Enter "exit" to quit.')
continue
# Start the loop over again to make the user pick
# a valid direction.
return None