Write a Python program that allows a user to play Rock Pape
Write a Python program that allows a user to play Rock
-
Paper
-
Scissors
-
Lizard
-
Spock against the
computer. Have the program keep score of how many times each has won a round.
Write
functions
to
do the follow
ing:
1.
Displays the menu options to play the game, to display the score, or to quit.
Checks user input for validity and then returns the inputted value.
2.
Asks the user to input their choice: rock, paper, scissors, lizard, or Spock.
Checks user input for va
lidity and then returns the inputted value.
3.
Randomly
chooses
the computer’s throw and returns the value.
4.
Compares the two throws and returns who is the winner of that round.
Rock
crushes
scissors, and
lizard. Paper
covers
rock and
disproves
Spock. Scissors
cuts
paper and
decapitates lizard. Lizard
poisons Spock and eats paper.
Spock vaporizes rock, and
smashes scissors.
5.
Displays the scores.
The program repeats until the user decides to quit. Display
the final score before exiting.
Do not use global variables.
Check all user input for invalid values.
Solution
# The Python program for the above questions are:
# \"rock\", \"paper\", \"scissors\", \"lizard\", \"Spock\" to numbers
# 0 - rock, 1 - Spock, 2 - paper, 3 - lizard, 4 - scissors
import random
def number_to_name(number):
# convert number to a name
if number == 0:
return \"rock\"
elif number == 1:
return \"Spock\"
elif number == 2:
return \"paper\"
elif number == 3:
return \"lizard\"
else:
return \"scissors\"
def name_to_number(name):
# convert name to number
if name == \"rock\":
return 0
elif name == \"Spock\":
return 1
elif name == \"paper\":
return 2
elif name == \"lizard\":
return 3
else:
return 4
def rpsls(name):
# convert name to player_number using name_to_number
player_number = name_to_number(name)
# compute random guess for comp_number using random.randrange()
comp_number = random.randrange(0,5)
# compute difference of player_number and comp_number modulo five
difference = (player_number - comp_number) % 5
# convert comp_number to name using number_to_name
comp_name = number_to_name(comp_number)
# print results
print \"Player chooses\", name
print \"Computer chooses\", comp_name
if difference == 1 or difference == 2:
print \"Player wins!\"
elif difference == 3 or difference == 4:
print \"Computer wins!\"
else:
print \"Player and Computer tie!\"
print \"Thanks for Playing this Game\"



