(I added the function in question @ Bottom)
Working on my first python app.
Im making a simple rock, paper, scissors game.
I have a function that takes in two parameters:
- The users input
- The computers input
The function looks like this:
seeIfUserWon(userInput, selectRandomOption()) where selectRandomOption() just chooses a random Enum (ROCK, PAPER, SCISSORS)
The code works if I replace selectRandomOption with hardcoded input.
Currently that code gives me the error:
ValueError: 'Paper' is not a valid RPS where RPS is an Enum class with 3 cases: ROCK, PAPER, SCISSORS
But like I said if I just put in RPS.ROCK for the second parameter then it works...
What am I not understanding about python.. maybe I need to use a lambda here but I'm not sure? Any references would be appreciated as well!
Functions I used:
def selectRandomOption() -> RPS:
pick = options[random.randint(0,2)]
return RPS(pick)
Options:
options = ["Rock", "Paper", "Scissors"]
Which I then validate with:
def validateUserInput(input):
if "rock" in input.lower():
return RPS.ROCK
elif "paper" in input.lower():
return RPS.PAPER
elif "scissors" in input.lower():
return RPS.SCISSORS
else:
raise Exception
Enum :
class RPS(Enum):
ROCK = auto()
PAPER = auto()
SCISSORS = auto()
3 Answers 3
Rather than randomly picking an integer, then looking up a string, then getting an enum value, consider just choosing the enum value directly. For example:
import random
class RPS(Enum):
ROCK = auto()
PAPER = auto()
SCISSORS = auto()
random.choice(list(RPS))
# <RPS.SCISSORS: 3>
3 Comments
selectRandom... not returning the right case.. ?(...), you need to pass the value not the name. These are integers the way you are using it. You could do something like RPS['ROCK'], but as others showed RPS(1) is probably better, or changing the values to strings. Still, I think it's nicer just to use choice().It's tricky to say for sure without seeing the seeifuserwon function but I think this is probably what's going on.
If you rewrite this function as below:
def selectRandomOption() -> RPS:
pick = random.randint(1, 3)
return RPS(pick)
I suspect that will fix your problem... You've defined RPS as an Enum class. To get the corresponding class member for a value you need to pass the number to the Enum class - details here.
I also changed it to (1, 3) in the above since the count starts from 1 not 0 in the Enum class.
1 Comment
Try this:
class RPS(Enum):
ROCK = "Rock"
PAPER = "Paper"
SCISSORS = "Scissors"
RPS(pick)is supposed to work? Also, why not just put the enums in the list in the first place?RPSwith a string argument, but it only takes integer arguments (that's whatauto()does, it's assigning the integers 1-3 to your Enums. Either 1) give your Enums string values (i.e.: ROCK = "rock") so that you can simply doRPS("rock")or put the Enums themselves into the list from which you're randomly choosing:choice((RPS.ROCK, RPS.PAPER, RPS.SCISSORS)).inputas that is the name of a built-in function and you're overwriting it