To fulfil the requirements of the instructions, this version of rock, paper, scissors game works by taking a number from the user and the computer to represent their hand. (0 = rock, 1 = paper, 2 = scissors) From the numbers we then get the string representations of their hands. Next, we determine the winner by comparing the string representations of their hands. Lastly, we print out the result of the game to announce the winner.
I tried to make the function determine_winner()
as simple as possible and this is how far I could get. Do you think it is a good idea to use dictionary there? Any comments to improve in general would be appreciated.
import random
user_hand = None
computer_hand = None
winner = None
result = None
def get_hand(num: int) -> str:
"""Get str representation of the user or the computer's hand."""
if num == 0:
return "rock"
elif num == 1:
return "paper"
elif num == 2:
return "scissors"
def determine_winner() -> str:
"""Get str representation of the winner."""
user_win_combinations = {"rock": "scissors", "paper": "rock", "scissors": "paper"}
if user_hand == computer_hand:
winner = "Draw"
elif (user_hand, computer_hand) in user_win_combinations.items():
winner = "You"
else:
winner = "Computer"
return winner
# take in a number 0-2 from the user that represents their choice
print("Rock = 0, paper = 1, scissors = 2")
while True:
user_input = input("Please enter your choice: ")
if user_input in ["0", "1", "2"]:
break
else:
print("Incorrect input!")
# get str representations of user's hand and computer's hand.
user_hand = get_hand(int(user_input))
computer_hand = get_hand(random.randint(0,2))
# determine who wins
winner = determine_winner()
# print out the result
print(f"Your choice ({user_hand}) vs Computer's choice ({computer_hand})")
if winner == "Draw":
result = "It's a draw!"
else:
result = f"{winner} won!"
print(result)
Output examples:
# Draw
Rock = 0, paper = 1, scissors = 2
Please enter your choice: 1
Your choice (paper) vs Computer's choice (paper)
It's a draw!
# User wins
Rock = 0, paper = 1, scissors = 2
Please enter your choice: 2
Your choice (scissors) vs Computer's choice (paper)
You won!
# Computer wins
Rock = 0, paper = 1, scissors = 2
Please enter your choice: 2
Your choice (scissors) vs Computer's choice (rock)
Computer won!
1 Answer 1
Your code is working, but it needs a lot of improvements.
The function get_hand
is redundant, there is no need to convert from int
to str
just to perform checks.
You can just compare int
s directly.
If you need to print the result human readably, just use a list
to keep track of the str
s and use indexing to retrieve them when needed.
And you absolutely shouldn't use (key, val) in dict.items()
to check if dict[key] == val
, it is terribly inefficient and unpythonic, as it defeats the purpose of having a dict
in the first place. Instead use the correct syntax I mentioned.
And since you already used functions, you should put the game inside a function to increase reusability.
And don't use globals for function arguments, pass them as arguments to functions properly.
There are still a lot room for improvements, but fixing aforementioned issues would make the code good for a beginner.
Suggested code:
import random
HANDS = ['rock', 'paper', 'scissors']
USER_WIN_COMBINATIONS = {0: 2, 1: 0, 2: 1}
def determine_winner(user_hand, computer_hand):
if user_hand == computer_hand:
return "It's a draw!"
winner = "Computer"
if computer_hand == USER_WIN_COMBINATIONS[user_hand]:
winner = "You"
return f"{winner} won!"
def game()
print("Rock = 0, paper = 1, scissors = 2")
while True:
user_input = input("Please enter your choice: ")
if user_input in {"0", "1", "2"}:
break
else:
print("Incorrect input!")
user_hand = int(user_input)
computer_hand = random.randrange(3)
print("Your choice ({0}) vs Computer's choice ({1})".format(HANDS[user_hand], HANDS[computer_hand])
print(determine_winner(user_hand, computer_hand))
if __name__ == '__main__':
game()
-
\$\begingroup\$ A little FYI, I wrote all this on my phone and didn't run any of the code, as I was going to sleep and my computer isn't in my bedroom. The point is I know exactly what the code will do without needing to run it. \$\endgroup\$Ξένη Γήινος– Ξένη Γήινος2023年04月13日 19:51:41 +00:00Commented Apr 13, 2023 at 19:51
-
\$\begingroup\$ "You can just compare
int
s directly." Yes I was thinking the same but thought to stick to the exercise's original instructions as it might have a reason for it. But all your points make total sense and very helpful. \$\endgroup\$isadoramoon– isadoramoon2023年04月14日 14:49:47 +00:00Commented Apr 14, 2023 at 14:49
Explore related questions
See similar questions with these tags.