import random class Hand(object): NAMES = ['rock', 'paper', 'scissors', 'spock', 'lizard'] WINS = {0: (2, 4), 1: (0, 3), 2: (1, 4), 3: (2, 0), 4: (3, 1)} def __init__(self, num): if (num < 0) or (num > 4): raise ValueError self.num = num def is_valid(self): return self.num != -1 def is_win(self, another): return another.num in Hand.WINS[self.num] def to_name(self): if self.num != -1: return Hand.NAMES[self.num] else: return "invalid" ef main_interactive(): accepted = False while not accepted: s = raw_input( """Make a choice: 0) Rock 1) Paper 2) Scissors 3) Spock 4) Lizard """) try: player_hand = Hand(int(s)) accepted = True except ValueError: print("Sorry, invalid choice. Please, try again.\n") comp_hand = Hand(random.randint(0,4)) result = convert_res_to_string( compare_hands( player_hand, comp_hand) ) print("Player: {0}, Computer: {1} - {2}".format(player_hand.to_name(), comp_hand.to_name(), result)) def compare_hands(h1, h2): if h1.is_win(h2): return -1 elif h2.is_win(h1): return 1 else: return 0 def convert_res_to_string(res, name1 = "Player", name2 = "Computer"): results = {-1: "{0} wins.".format(name1), 0: "Draw.", 1: "{0} wins".format(name2)} return results[res] if __name__ == '__main__': main_interactive()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question