dimanche 7 octobre 2018

How do I stop this loop in Python?

This works exactly as I want it to, with the exception that I can't get it to stop when the user enters an invalid option. It's a Rock, Paper, Scissors game that not only registers the user's input but it keeps score of the current round and keeps the final score of all rounds until the game ends... which as it is right now, never happens. How do I end this game when the user inputs an invalid option? I tried using break, but it's invalid.

def rock_paper_scissors():
    playerScore = 0
    computerScore = 0

    print("")

    player = input("Choose Rock, Paper, or Scissors: ")
    player = player.lower()

    choices = ["rock", "paper", "scissors"]

    computer = random.choice(choices)


    if player == computer:
        print("I chose " + str(computer) + " and you chose " + player + ". It's a tie!")
    elif player == "rock" and computer == "scissors":
        playerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". Congratulations! You won! " + player + " beats " + str(computer) + ".")
    elif player == "paper" and computer == "rock":
        playerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". Congratulations! You won! " + player + " beats " + str(computer) + ".")
    elif player == "scissors" and computer == "paper":
        playerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". Congratulations! You won! " + player + " beats " + str(computer) + ".")
    elif computer == "rock" and player == "scissors":
        computerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". You lost! " + str(computer) + " beats " + player + ".")
    elif computer == "paper" and player == "rock":
        computerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". You lost! " + str(computer) + " beats " + player + ".")
    elif computer == "scissors" and player == "paper":
        computerScore += 1
        print("I chose " + str(computer) + " and you chose " + player + ". You lost! " + str(computer) + " beats " + player + ".")
    else:
        print("Sorry, but you entered an invalid option.  The game has ended.  See below for the final score.  Thank you for playing")
        print("")
        print("Your score:", str(playerScore) + ", Computer score:", str(computerScore))

    return playerScore, computerScore

playerFinal = 0
computerFinal = 0

while True:
    player, computer = rock_paper_scissors()
    playerFinal += player
    computerFinal += computer
    print("Your score:", str(playerFinal) + ", Computer score:", computerFinal)

Aucun commentaire:

Enregistrer un commentaire