# Amy Luo # Girls Who Code 2018 SIP Technical Project import random # dictionary that converts user play and computer play into English for output # formatting CHOICES = {0:'rock', 1:'paper', 2:'scissors'} # lists the cases in which the computer would win in the format: #(ai_play, user_play) where 0 = rock, 1 = paper, 2 = scissors AI_WINS = [(0, 2), (2, 1), (1, 0)] class RockPaperScissors: def __init__(self): self.ai_play = None self.user_play = None self.ai_points = 0 self.user_points = 0 def _ai_play(self): '''Randomly generates the play made by the computer (AI)''' self.ai_play = random.randint(0, 2) def _user_play(self): '''Gets play inputted by the user''' while True: user = input('Please enter 0 for rock, 1 for paper and 2 for ' 'scissors: \n') # checks input is indeed an integer and is 0, 1 or 2 if user.isdigit() and 0 <= int(user) <= 2: break else: print('Invalid Input! Try Again!') self.user_play = int(user) def determine_winner(self): '''Determines the winner of this round''' if self.ai_play == self.user_play: print('This round was a draw.') return # constructs a tuple from the ai play and the user play play_pair = (self.ai_play, self.user_play) if play_pair in AI_WINS: print('The AI won this round!') self.ai_points += 1 else: print('You won this round!') self.user_points += 1 def play(self): '''Plays a game of rock, paper, scissors''' # checks that the input is an integer while True: try: rounds = int(input('Input how many rounds of rock, paper, scissors you ' 'would like to play: \n')) break except ValueError: print('Please input an integer for the number of rounds you wish to play.') # obtains the ai play and the user play and determines the winner for this round for r in range(rounds): self._ai_play() self._user_play() print('You chose %s and the AI chose %s.'%(CHOICES[self.user_play], CHOICES[self.ai_play])) self.determine_winner() print('--------------------------------------------') # displays the score and prints the final winner for the game print('You won %d round(s), and the AI won %d round(s).' %(self.user_points, self.ai_points)) if self.ai_points == self.user_points: print('The game was a draw.') elif self.ai_points > self.user_points: print('The AI won the game!') else: print('You won the game!') if __name__ == '__main__': game = RockPaperScissors() game.play()
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