gruntfutuk

Rock Paper Scissors with classes example

Oct 13th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. """This program plays a game of Rock, Paper, Scissors between two Players,
  4. and reports both Player's scores each round."""
  5.  
  6. from random import choice
  7.  
  8. moves = ['rock', 'paper', 'scissors']
  9. hand = ['rock', 'paper', 'scissors']
  10. number_of_rounds = 10
  11.  
  12.  
  13. class Player:
  14.     '''The Player class is the parent class for all of the Players
  15.    in this game'''
  16.    
  17.     def __init__(self):
  18.         self.score = 0
  19.        
  20.     def move(self):
  21.         return 'rock'
  22.  
  23.     def learn(self, my_move, their_move):
  24.         pass
  25.  
  26.  
  27.     def beats(one, two):
  28.         return ((one == 'rock' and two == 'scissors') or
  29.                (one == 'scissors' and two == 'paper') or
  30.                (one == 'paper' and two == 'rock'))
  31.    
  32.     def winner(p1, p2, move1, move2):  # p1 is self
  33.         if beats(move1, move2):
  34.             return p1
  35.         elif beats(move2, move1):
  36.             return p2
  37.         else:
  38.             return None
  39.        
  40.  
  41.  
  42. class RandomPlayer(Player):
  43.     '''Makes moves based on random choices'''
  44.    
  45.     def move(self):
  46.         return choice(hand)
  47.    
  48. class Game:
  49.     def __init__(self, p1, p2):
  50.         self.p1 = p1
  51.         self.p2 = p2
  52.         self.round = 0
  53.  
  54.     def play_round(self):
  55.         move1 = self.p1.move()
  56.         move2 = self.p2.move()
  57.         print(f"Player 1: {move1}  Player 2: {move2}")
  58.         self.p1.learn(move1, move2)
  59.         self.p2.learn(move2, move1)
  60.         win = self.p1.winner(self.p2, move1, move2)
  61.         if not win:
  62.             print('Draw')
  63.         elif win is self.p1:
  64.             print('Player 1 wins')
  65.             self.p1.score += 1
  66.         else:
  67.             print('Player 2 wins')
  68.             self.p2.score += 1
  69.  
  70.     def play_game(self):
  71.         print("Game start!")
  72.         while self.round < number_of_rounds:
  73.             self.round += 1
  74.             print(f"Round {self.round}:")
  75.             self.play_round()
  76.         print("Game over!")
  77.  
  78. if __name__ == '__main__':
  79.     game = Game(RandomPlayer(), RandomPlayer())
  80.     game.play_game()
  81.     game.play_round()
Add Comment
Please, Sign In to add comment