重新开始游戏中的while循环

时间:2018-07-27 08:53:59

标签: python python-3.x while-loop

我正在尝试用python编写剪刀石头布的游戏。这是代码:

D_0 = {1: "rock", 2: "scissors", 3: "paper"}
from random import randint
play = False
name = input("What is your name?: ")
print("%s you have to pick among rock,paper and scissors." % name)

while play == False:
    p_1 = input("which one?")
    computer = D_0[randint(1, 3)]
    print("my choice is: ",computer)
    if p_1 == computer:
        print("it's a draw")
    elif p_1 == "scissors" and computer == "paper":
        print("you won!")
    elif p_1 == "paper" and computer == "scissors":
        print("you lost!")
    elif p_1 == "scissors" and computer == "rock":
        print("you lost!")
    elif p_1 == "rock" and computer == "paper":
        print("you lost!")
    elif p_1 == "rock" and computer == "scissors":
        print("you won!")
    elif p_1 == "paper" and computer == "rock":
        print("you won!")
    else:
        print("Invalid input")
    break
again = input("do you want another round?:")
if again == "yes":
    play = False
else:
    play = True

该程序运行良好,但我想问玩家是否想再进行一轮。如果答案为是,则该程序必须重新开始循环。 问题是我不知道该怎么做,我知道它可能与True和False有关,我试图做一些您可以在代码中看到的事情,但是没有用。 请帮我。

1 个答案:

答案 0 :(得分:2)

一个简单的修复方法可能是将while循环设为True,然后继续循环直到您中断执行:

D_0 = {1: "rock", 2: "scissors", 3: "paper"}
from random import randint

name = input("What is your name?: ")
print("%s you have to pick among rock,paper and scissors." % name)

while True:
    p_1 = input("which one?")
    computer = D_0[randint(1, 3)]

    print("my choice is: ", computer)

    if p_1 == computer:
        print("it's a draw")
    elif p_1 == "scissors" and computer == "paper":
        print("you won!")
    elif p_1 == "paper" and computer == "scissors":
        print("you lost!")
    elif p_1 == "scissors" and computer == "rock":
        print("you lost!")
    elif p_1 == "rock" and computer == "paper":
        print("you lost!")
    elif p_1 == "rock" and computer == "scissors":
        print("you won!")
    elif p_1 == "paper" and computer == "rock":
        print("you won!")
    else:
        print("Invalid input")

    again = input("do you want another round?:")
    if again != "yes":
        break