【问题标题】:How do I get this choose your own adventure story in python to start over if the user enters that they want to play again?如果用户输入他们想再次玩,我如何让这个选择你自己在 python 中的冒险故事重新开始?
【发布时间】:2017-12-18 19:28:45
【问题描述】:

到目前为止,这是我的代码,它有效:

print('Welcome to choose your own adenture.')
print('You enter a room with two doors.  Do you want to enter the red door or the white door?')
door = input()

while True:

  if door == 'white':
    print("there was a dragon behind the door.  It ate you and you died.")
    break
  elif door == 'red':
    run_or_dead = input("there is a bear behind the door.  Do you want to wave your arms and shout, or play dead?")
    while True:
      if run_or_dead == 'wave':
        print("Nice try, but the bear did't buy it.  It ate you and you died.")
        break
      elif run_or_dead == 'play dead':
        print("Nice try, but the bear did't buy it.  It ate you and you died.")
        break
      else:
        run_or_dead = input('Not a valid answer.  Do you want to wave or play dead?')
    break

  else:
    door = input('that is not a valid choice.  Do you want to enter the red door or the white door?')

我不知道如何让程序询问用户是否要重复整个过程,如果他们输入“是”就这样做

【问题讨论】:

标签: python loops if-statement nested adventure


【解决方案1】:

一种简单的方法是用另一个loop 包围您的while True,例如:

play_more = True
while play_more:
    # your while True loop goes here
    uinput = input('Type yes if you wanna play more')
    play_more = uinput.lower() == 'yes'

【讨论】:

  • @cricket_007 +1
  • 最佳答案,因为 OP 是初学者。
【解决方案2】:

你可以把游戏放到一个函数中,只要用户输入一个预定义的值就可以调用它:

def game():
    print('Welcome to choose your own adenture.')
    print('You enter a room with two doors.  Do you want to enter the red door or the white door?')
    door = input()

    if door == 'white':
        print("there was a dragon behind the door.  It ate you and you died.")
        return 0
    elif door == 'red':
        run_or_dead = input(
            "there is a bear behind the door.  Do you want to wave your arms and shout, or play dead?")
        while True:
            if run_or_dead == 'wave':
                print("Nice try, but the bear did't buy it.  It ate you and you died.")
                return 0
            elif run_or_dead == 'play dead':
                print("Nice try, but the bear did't buy it.  It ate you and you died.")
                return 0
            else:
                run_or_dead = input('Not a valid answer.  Do you want to wave or play dead?')

    else:
        door = input('that is not a valid choice.  Do you want to enter the red door or the white door?')
        return 0

while input('Do you want to play a game? [y/n]') == 'y':
    game()

由于它是一个函数,因此您不能再使用break 来停止游戏,但只需使用return 即可。

【讨论】:

  • 运行时好像有这个问题。它适用于大多数答案,但是当您为门问题输入无效答案时,它会在您输入第二个答案后循环回到开头。尝试为门问题输入无效答案,这样您就可以明白我的意思。
猜你喜欢
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
相关资源
最近更新 更多