尝试仅在用户说出来时重新循环游戏

时间:2016-01-28 18:59:13

标签: python-2.7

我试图制作一个古老的摇滚,纸张,剪刀游戏,我通过询问用户是否愿意重播来做得更好。

这是我一直在研究的代码:

# ROCK, PAPER, SCISSORS !!!
# BY: NICK GRIMES

from random import randint

replay = True
while replay == True:
    replay = False

userChoice = raw_input("> Choose rock, paper, or scissors: ")
computerChoice = randint(1, 101)

if computerChoice <= 34:
    computerChoice = "rock"
elif computerChoice <= 67:
    computerChoice = "paper"
else:
    computerChoice = "scissors"

print "> The computer chooses: " + str(computerChoice)


if userChoice == computerChoice:
    print "> It's a tie! Thank you for playing!"
    askUserPlayAgain = raw_input("> Would you like to play again? Enter [yes or no]: ")
    if askUserPlayAgain.lower()[0] == "y":
        replay == True
    elif askUserPlayAgain.lower()[0] == "n":
        break

    # ---

elif userChoice == "rock":
    if computerChoice == "scissors":
        print "> Rock crushes scissors!"
        print "> You win!"
    else:
        print "> Paper covers rock!"
        print "> Computer wins!"

    # ---

elif userChoice == "paper":
    if computerChoice == "rock":
        print "> Paper coveres rock!"
        print "> You win!"
    else:
        print "> Scissors cuts paper!"
        print "> Computer wins!"

    # ---

elif userChoice == "scissors":
    if computerChoice == "rock":
        print "> Rock crushes scissors"
        print "> Computer wins!"
    else:
        print "> Scissors cuts paper"
        print "> You win!"

    # ---

else:
    print "Please choose either rock, paper, or scissors only!"

现在,实际的游戏一直有效,但是在试图实现这个新想法时,我实际上删除了比较这两个选项的功能,并将它们留给了if / else&#39; s ......

主要问题在于:当用户键入“是”时,它应该重新启动游戏,但由于某些原因它绝对没有任何作用。如果有人看到可能导致此问题的任何事情,请告诉我。谢谢!

2 个答案:

答案 0 :(得分:1)

刚刚改变

while replay == True:

while  True:

它对我来说很好。

答案 1 :(得分:1)

这对我来说没有多大意义:

replay = True
while replay == True:
    replay = False

我认为您最好使用while True:循环。如果用户选择重新启动游戏并且不需要重播变量,请使用continue关键字。

from random import randint

while True:
    userChoice = raw_input("> Choose rock, paper, or scissors: ")
    computerChoice = randint(1, 101)
    if computerChoice <= 34:
        computerChoice = "rock"
    elif computerChoice <= 67:
        computerChoice = "paper"
    else:
        computerChoice = "scissors"
    print("> The computer chooses: " + str(computerChoice))
    if userChoice == computerChoice:
        print("> It's a tie! Thank you for playing!")
    askUserPlayAgain = raw_input("> Would you like to play again? Enter [yes or no]: ")
    if askUserPlayAgain.lower()[0] == "y":
        continue
    elif askUserPlayAgain.lower()[0] == "n":
        break