无法重复我的代码中提出的问题

时间:2016-03-22 12:53:11

标签: python python-3.x

我在Python 3.4.3中创建了一个基于文本的冒险游戏,但我无法弄清楚如何让代码重复一个问题。在此之前有一堆叙述,如果这有助于理解发生了什么。

print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")

str = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
print(" ")
if str in ("d"):
    print("You see your combat boots and the grassy ground below your feet. ")

if str in ("l"):
    print("The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...")

if str in ("r"):
    print("The forest is warm and inviting that way, you think you can hear a distant birds chirp.")

if str in ("u"):
    print("The blue sky looks gorgeous, a crow flies overhead... that's not a crow...")
    print("It's a Nevermore, an aerial Grim. You stand still until it passes.")

if str in ("b"):
    print("the grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.")
    print("Mount Glenn, one of the most Grim-infested places in all of Remnant.")
    print("It's a bit unsettling.")

else:
    print("Try that again")

我希望代码能够向用户重复提问,直到他们回答了所有可能的答案并继续讨论下一个问题。当他们得到别的东西时,我也想让它重复这个问题。我该怎么做呢?

4 个答案:

答案 0 :(得分:2)

不要将str用作变量名,它会影响重要的内置并导致奇怪的问题。

使用while循环将输出限制为有效选项。

valid_choices = ('d', 'l', 'r', 'u', 'b',)

choice = None
while choice not in valid_choices:
    text = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
    choice = text.strip()

if choice == 'd':
    print ('...')
elif choice == 'u':
    print ('...')

另见:

答案 1 :(得分:1)

基本上你可以把你的问题放在一个循环中并迭代它,直到你输入一个所需的' if'案件。我修改了你的代码如下。请看看

print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")

while True:
    str = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
    print(" ")
    if str in ("d"):
        print("You see your combat boots and the grassy ground below your feet. ")
        break

    if str in ("l"):
        print("The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...")
        break

    if str in ("r"):
        print("The forest is warm and inviting that way, you think you can hear a distant birds chirp.")
        break

    if str in ("u"):
        print("The blue sky looks gorgeous, a crow flies overhead... that's not a crow...")
        print("It's a Nevermore, an aerial Grim. You stand still until it passes.")
        break

    if str in ("b"):
        print("the grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.")
        print("Mount Glenn, one of the most Grim-infested places in all of Remnant.")
        print("It's a bit unsettling.")
        break

    else:
        print("Try that again")

答案 2 :(得分:0)

做这样的事情:

answered = False
while not answered:
    str = input("Question")
    if str == "Desired answer":
        answered = True

答案 3 :(得分:0)

这是我怎么做的;解释在评论中:

# Print out the start text
print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")

# Use a function to get the direction; saves some repeating later
def get_direction():
        answer = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
        print(" ")
        return answer

# Keep running this block until the condition is False.
# In this case, the condition is True, so it keeps running forever
# Until we tell Python to "break" the loop.
while True:
        # I changed "str" to "answer" here because "str" is already a Python
        # built-in. It will work for now, but you'll get confused later on.
        answer = get_direction()

        if answer == "d":
                print("You see your combat boots and the grassy ground below your feet. ")

                # Stop the loop
                break
        elif answer == "l":
                print("The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...")
                break
        elif answer == "r":
                print("The forest is warm and inviting that way, you think you can hear a distant birds chirp.")
                break
        elif answer == "u":
                print("The blue sky looks gorgeous, a crow flies overhead... that's not a crow...")
                print("It's a Nevermore, an aerial Grim. You stand still until it passes.")
                break
        elif answer == "b":
                print("the grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.")
                print("Mount Glenn, one of the most Grim-infested places in all of Remnant.")
                print("It's a bit unsettling.")
                break
        else:
                print("Try that again")

                # NO break here! This means we start over again from the top

现在,如果添加多个方向,这些都不会很好地扩展; 因为我认为你走后"对"你想要一个新问题,所以这是一个问题 循环中的新循环等。

# The start text
print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")

# Use a function to get the direction
def get_direction():
    answer = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
    print(" ")
    return answer


# Use a function to store a "location" and the various descriptions that
# apply to it
def location_start():
    return {
        'down': [
            # Function name of the location we go to
            'location_foo',

            # Description of this
            'You see your combat boots and the grassy ground below your feet.'
        ],

        'left': [
            'location_bar',
            'The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...'
        ],

        'right': [
            'location_other',
            'The forest is warm and inviting that way, you think you can hear a distant birds chirp.'
        ],

        'up': [
            'location_more',
            "The blue sky looks gorgeous, a crow flies overhead... that's not a crow...\n" +
                "It's a Nevermore, an aerial Grim. You stand still until it passes."
        ],

        'behind': [
            'location_and_so_forth',
            "The grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.\n" +
                "Mount Glenn, one of the most Grim-infested places in all of Remnant.\n" +
                "It's a bit unsettling."
        ],
    }

# And another location ... You'll probably add a bunch more...
def location_foo():
    return {
        'down': [
            'location_such_and_such',
            'desc...'
        ],
    }

# Store the current location
current_location = location_start

# Keep running this block until the condition is False.
# In this case, the condition is True, so it keeps running forever
# Until we tell Python to "break" the loop.
while True:
    # Run the function for our current location
    loc = current_location()
    answer = get_direction()

    if answer == ("d"):
        direction = 'down'
    elif answer == ("l"):
        direction = 'left'
    elif answer == ("r"):
        direction = 'right'
    elif answer == ("u"):
        direction = 'up'
    elif answer == ("b"):
        direction = 'behind'
    else:
        print("Try that again")

        # Continue to the next iteration of the loop. Prevents the code below
        # from being run
        continue

    # print out the key from the dict
    print(loc[direction][1])

    # Set the new current location. When this loop starts from the top,
    # loc = current_location() is now something different!
    current_location = globals()[loc[direction][0]]

现在,这只是一种方式;这里的一个缺点是你需要 如果要允许播放器,请重复对位置的描述 从不同方向接近一个位置。这可能不适用于您的 冒险游戏(原来adventure不允许这样,如果我记得的话 正确)。
你可以很容易地解决这个问题,但我会将其作为练习留给你; - )