繁体   English   中英

如何从python中的两个if语句接受答案

[英]How to accept an answer from two if statements in python

我对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()

我可以测试,但我认为可能是这样

我使用带有True/False变量来记忆游戏的"state"

顺便说一句:如果您在另一个功能中运行一个房间,您将具有隐藏的“递归”。 最好返回函数名称(不带() )并在函数外部运行它。

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")    

受到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号房,如何下车...

退出无处可去!

>

我承认,是/否不是最受启发的方法。 无论如何,您可能想将实际问题添加到输入中,以便播放器可以告诉您对它们的期望。 但总的来说,这似乎可行,您可以轻松地添加和互连任意数量的房间。 所有这些都应该仅使用一种功能。

关于if的链接和嵌套:嵌套的if通常是可以的,但是正如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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM