我是编程新手。我已经为剪刀石头布游戏编写了代码,但是有一个我似乎无法修复的错误。游戏结束时,询问用户是否要再次玩。如果用户第一次回答“是”,然后再次播放,然后第二次回答“否”,则计算机出于某种原因再次询问用户是否要再次播放。在这种情况下,用户必须输入no。这是因为尽管用户回答“否”,但答案仍重置为“是”,然后再次进行搜索。如何解决?
# This code shall simulate a game of rock-paper-scissors.
from random import randint
from time import sleep
print "Welcome to the game of Rock, Paper, Scissors."
sleep(1)
def theGame():
playerNumber = 4
while playerNumber == 4:
computerPick = randint(0,2)
sleep(1)
playerChoice = raw_input("Pick Rock, Paper, or Scissors. Choose wisely.: ").lower()
sleep(1)
if playerChoice == "rock":
playerNumber = 0
elif playerChoice == "paper":
playerNumber = 1
elif playerChoice == "scissors":
playerNumber = 2
else:
playerNumber = 4
sleep(1)
print "You cookoo for coco puffs."
print "You picked " + playerChoice + "!"
sleep(1)
print "Computer is thinking..."
sleep(1)
if computerPick == 0:
print "The Computer chooses rock!"
elif computerPick == 1:
print "The Computer chooses paper!"
else:
print "The Computer chooses scissors!"
sleep(1)
if playerNumber == computerPick:
print "it's a tie!"
else:
if playerNumber < computerPick:
if playerNumber == 0 and computerPick == 2:
print "You win!"
else:
print "You lose!"
elif playerNumber > computerPick:
if playerNumber == 2 and computerPick == 0:
print "You lose!"
else:
print "You win!"
replay()
def replay():
sleep(1)
playAgain = "rerun"
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
elif playAgain == "no":
sleep(1)
print "Have a good day."
sleep(1)
print "Computer shutting down..."
sleep(1)
else:
sleep(1)
print "What you said was just not in the books man."
sleep(1)
theGame()
答案 0 :(得分:1)
您应该在调用theGame
之后跳出循环。想象您决定再玩15次。然后,堆栈上有15个replay
循环,等待询问您是否要再次播放。由于在每个循环中playAgain
是"yes"
,由于playAgain
不是"no"
答案 1 :(得分:1)
这是因为调用堆栈的创建方式。
第一次播放并输入yes
再次播放时,您正在创建另一个对theGame()
的函数调用。完成该函数调用后,您的程序将继续执行while
循环,并询问是否要再次播放,无论是否输入了no
,因为该输入是对theGame()
的第二次调用。
要解决此问题,请在输入break
时致电playAgain
后立即添加no
或将theGame()
设置为yes
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
break ## or playAgain = "no"