mercredi 8 mai 2019

Looping program based on user input

I am making a game of Rock, Paper, Scissors where after the game has ended it displays to the screen 'Would you like to play again?". I am struggling to get the game to run again when the user selects yes. I am able to have the program say goodbye and quite when the user selects no.

I could copy and paste the code inside the If statement if the user selects yes a bunch of times but this is very inefficient and I feel there must be an easier way.

import random
selection = ("Rock", "Paper", "Scissors")
user1 = input("Pick Rock, Paper, or Scissors: ").upper()
computer = random.choice(selection)
if (user1 == "ROCK"):
        if (computer == "Paper"):
            print ("The computer selected: " + (computer))
            print ("You lost")
        elif (computer == "Scissors"):
            print ("The computer selected: " + (computer))
            print ("You win")
        elif (computer == "Rock"):
            print ("The computer selected: " + (computer))
            print ("Tie")
        else:
            print ("Uh oh something went wrong. Please try again")
elif (user1 == "PAPER"):
            if (computer == "Scissors"):
                print ("The computer selected: " + (computer))
                print ("You lost")
            elif (computer == "Rock"):
                print ("The computer selected: " + (computer))
                print ("You win")
            elif (computer == "Paper"):
                print ("The computer selected: " + (computer))
                print ("Tie")
            else:
                print ("Uh oh something went wrong. Please try again")
elif (user1 == "SCISSORS"):
        if (computer == "Rock"):
            print ("The computer selected: " + (computer))
            print ("You lost")
        elif (computer == "Paper"):
            print ("The computer selected: " + (computer))
            print ("You win")
        elif (computer == "Scissors"):
            print ("The computer selected: " + (computer))
            print ("Tie")
        else:
                print ("Uh oh something went wrong. Please try again")
else:
            print ("Invalid Selection")
while True:
    # main program
    while True:
        answer = input('Run again? (y/n): ')
        if answer in ('y', 'n'):
            break
        print ('Invalid input.')
    if answer == 'y':
        continue
    else:
        print ('Goodbye')
        break

My expected result is when the user types "y" and hits enter the game will start again but as of now when the user types "y" it just repeats the same "Would you like to play again. I understand it does that because I don't have any actual code inside the If statement but I don't know what I need to add to it to get the desired result.

Aucun commentaire:

Enregistrer un commentaire