Skip to content

Instantly share code, notes, and snippets.

@rkennesson
Forked from 1328/comments
Last active August 29, 2015 14:14
Show Gist options
  • Save rkennesson/9f336d725bec028f07d2 to your computer and use it in GitHub Desktop.
Save rkennesson/9f336d725bec028f07d2 to your computer and use it in GitHub Desktop.
from random import randrange
class Player(object):
def __init__(self, who = 'you'):
self.score = 0
self.who = who
def choose(self):
'''let's not make choice an instance variable, since it varies on each
play'''
choice = int(input("Rock [1] Paper [2] Scissors [3]"))
return choice
def win_round(self):
self.score += 1
def win_game(self):
'''let's make this a bit more modular'''
print("{} WON the match!".format(self.who))
class ComputerPlayer(Player):
def __init__(self, who = None):
# py3:
#super().__init__(who= 'The Computer')
# py2/py3
Player.__init__(self, who = 'The Computer')
def choose(self):
comp_choice = randrange(1, 4)
return comp_choice
class Game(object):
def __init__(self, num_rounds = 3):
self.player = Player()
self.computer = ComputerPlayer()
self.num_rounds = num_rounds
self.current_round = 0
def round(self):
human_choice = self.player.choose()
comp_choice = self.computer.choose()
return self.who_won(human_choice, comp_choice)
def play(self):
for i in range(self.num_rounds):
self.round()
if self.player.score > self.computer.score:
self.player.win_game()
elif self.computer.score > self.player.score:
self.computer.win_game()
else:
print("it's a tie!")
def who_won(self, score1, score2):
if score1 == score2:
print("It was a tie.")
elif score1 == 3 and score2 == 2:
print("The computer has won. Scissors cut paper.")
self.computer.win_round()
elif score1 == 2 and score2 == 3:
print ("You won. Scissors cut paper.")
self.player.win_round()
elif score1 == 2 and score2 == 1:
print ("You won. Paper covers rock.")
self.player.win_round()
elif score1 == 1 and score2 == 2:
print ("You lost to the computer. Paper covers rock.")
self.computer.win_round()
elif score1 == 1 and score2 == 3:
print ("You won. Rock smashes scissors.")
self.player.win_round()
elif score1 == 3 and score2 == 1:
print ("You lost. Rock smashes scissors.")
self.computer.win_round()
self.current_round += 1
if __name__ == '__main__':
game = Game()
game.play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment