首页 > 解决方案 > 石头剪刀布运行两次错误

问题描述

我是编程新手。我已经为石头剪刀布游戏编写了代码,但是有一个我似乎无法修复的错误。当游戏结束时,会询问用户是否想再玩一次。如果用户第一次回答“是”,然后再次播放,然后第二次回答“否”,则计算机出于某种原因再次询问用户是否想再次播放。在这种情况下,用户必须输入 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() 

标签: python

解决方案


你应该在调用之后跳出循环theGame。想象一下,你决定再玩 15 次。然后栈上有15个replay循环,等着问你要不要再玩。因为playAgain"yes"每个循环中,每个循环都会再次询问你,因为playAgain不是"no"


推荐阅读