Skip to content

Instantly share code, notes, and snippets.

@claraj
Created February 16, 2021 17:59
Show Gist options
  • Save claraj/ad60cb1abb2461fcd99f08b7413ea7ec to your computer and use it in GitHub Desktop.
Save claraj/ad60cb1abb2461fcd99f08b7413ea7ec to your computer and use it in GitHub Desktop.
Python enum for Rock-Paper-Scissors choices
from enum import Enum
import random
class Play(Enum):
ROCK = 1
PAPER = 2
SCISSORS = 3
def __str__(self):
return self.name.title() # so when printing an enum, it prints 'Rock' instead of 'ROCK'
def main():
user_choice = int(input('Please choose \n1. Rock, \n2. Paper, \n3. Scissors\n')) # TODO validation, ensure only numbers 1, 2, or 3 are accepted
user_play = Play(user_choice) # convert number to enum.
computer_choice = random.randint(1, 3)
computer_play = Play(computer_choice)
print(f'You played {user_play}')
print(f'Computer played {computer_play}')
winner = who_won(user_play, computer_play)
print(f'The outcome is: {winner}')
def who_won(user, computer):
if user == computer:
return 'tie'
elif user == Play.ROCK and computer == Play.SCISSORS or user == Play.PAPER and computer == Play.ROCK or user == Play.SCISSORS and computer == Play.PAPER :
return 'user wins'
else:
return 'computer wins'
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment