Issue
I'm currently pretty stuck on this rock, paper, scissors program and would greatly appreciate some help. I have looked through other posts concerning rock, paper, scissors programs but I'm still stuck.
The error I'm getting currently is When I ask the user to choose 'Rock', 'Paper' or 'Scissors' it will keep asking it a couple more times and then I get an error. Also, it seems to me that a good portion of the posts I look at involve concepts that I haven't used in class, so I'm not comfortable with them.
choices = [ 'Rock', 'Paper', 'Scissors' ]
# 1. Greetings & Rules
def showRules():
print("\n*** Rock-Paper-Scissors ***\n")
print("\nEach player chooses either Rock, Paper, or Scissors."
"\nThe winner is determined by the following rules:"
"\n Scissors cuts Paper -> Scissors wins"
"\n Paper covers Rock -> Paper wins"
"\n Rock smashes Scissors -> Rock wins\n")
# 2. Determine User Choice
def getUserChoice():
usrchoice = input("\nChoose from Rock, Paper or Scissors: ").lower()
if (usrchoice not in choices):
usrchoice = input("\nChoose again from Rock, Paper or Scissors: ").lower()
print('User chose:', usrchoice)
return usrchoice
# 3. Determine Computer choice
def getComputerChoice():
from random import randint
randnum = randint(1, 3)
cptrchoice = choices(randnum)
print('Computer chose:', cptrchoice)
return randnum
# 4. Determine Winner
def declareWinner(user, computer):
if usrchoice == cptrchoice:
print('TIE!!')
elif (usrchoice == 'Scissors' and cptrchoice == 'Rock'
or usrchoice == 'Rock' and cptrchoice == 'Paper'
or usrchoice == 'Paper' and cptrchoice == 'Scissors'):
print('You lose!! :(')
else:
print('You Win!! :)')
#5. Run program
def playGame():
showRules() # Display the title and game rules
user = getUserChoice() # Get user selection (Rock, Paper, or Scissors)
computer = getComputerChoice() # Make and display computer's selection
declareWinner(user, computer) # decide and display winner
Solution
You have few problems with the code:
First is you are converting user input
to lowercase but your list items are not. So the check will fail.
choices = [ 'rock', 'paper', 'scissors' ]
Second thing is you are calling choice(randnum) which will throw an error as you have to use []
to retrieve element from list.
cptrchoice = choices[randnum]
Third is what happens if you enter invalid string. You only check with if
but you need while loop
while (usrchoice not in choices):
usrchoice = getUserChoice() #input("\nChoose again from Rock, Paper or Scissors: ").lower()
Fourth is in declareWinner
, your params
are user
and computer
but then you are using usrchoice
and cptrchoice
in if
conditions
def declareWinner(usrchoice, cptrchoice):
if usrchoice == cptrchoice:
Try this and give it a shot
Answered By - sam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.