Issue
I am trying to write a very simple programme for a rock, paper, scissors game. I produce a random integer which is the opponent's move, and then I input my own "guess" in integer form. Then, I combine these two integers into a list and test these coordinates against a results matrix.
I have converted "rock", "paper" and "scissors" into integers as follows:
guess = input("Enter your move: \"rock\", \"paper\", \"scissors\", or \"quit\": \n")
if guess == "rock":
guess = 0
if guess == "paper":
guess = 1
if guess == "scissors":
guess = 2
if guess == "quit":
break
weapon = random.randint(0, 2) # 0 is rock, 1 is paper, 2 is scissors
outputGuess = (int(guess), int(weapon))
Is there a way to get rid of all the if statements? I have tried the following, but it does not work:
guess = input("Enter your move: \"rock\", \"paper\", \"scissors\", or \"quit\": \n")
"rock" = 0
"paper" = 1
"scissors" = 2
weapon = random.randint(0, 2) # 0 is rock, 1 is paper, 2 is scissors
outputGuess = (int(guess), int(weapon))
Thank you!
Solution
You could use a dict to translate it into its integer counterpart.
guess = input("Enter your move: \"rock\", \"paper\", \"scissors\", or \"quit\": \n")
guesses = {'rock':0, 'paper':1, 'scissors':2}
weapon = random.randint(0, 2)
output = (guesses[guess], weapon)
You don't need to change the type of the weapon since it is already an integer.
Answered By - Austin Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.