Skip to content

Instantly share code, notes, and snippets.

@ianliu
Created April 9, 2014 17:40
Show Gist options
  • Save ianliu/10295742 to your computer and use it in GitHub Desktop.
Save ianliu/10295742 to your computer and use it in GitHub Desktop.
Rock, paper, scissors!
from random import randint
CHOICES = ['rock', 'paper', 'scissors']
INITIALS = [c[0] for c in CHOICES]
class Player(object):
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
class HumanPlayer(Player):
def __init__(self, name):
super(HumanPlayer, self).__init__(name)
def get_choice(self):
s = input("Whats your choice, rock, paper or scissors? ").lower()[0]
while s not in INITIALS:
s = input("This choice does not exist! Pick another: ").lower()[0]
return INITIALS.index(s)
class ComputerPlayer(Player):
def __init__(self, name):
super(ComputerPlayer, self).__init__(name)
def get_choice(Player):
return randint(0, len(CHOICES) - 1)
def game(p1, p2):
print("Welcome %s and %s!" % (p1.get_name(), p2.get_name()))
while True:
c1 = p1.get_choice()
c2 = p2.get_choice()
print("%s chose %s and %s chose %s" % (p1.get_name(), CHOICES[c1], p2.get_name(), CHOICES[c2]))
cond = (c1 - c2) % 3
if cond == 0:
print("Its a tie!")
elif cond == 1:
print("%s won!" % (p1.get_name(),))
else:
print("%s won!" % (p2.get_name(),))
print("-------")
try:
game(HumanPlayer("Ian"), ComputerPlayer("[CPU]"))
except KeyboardInterrupt:
print("Bye")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment