Last active
August 29, 2015 13:57
-
-
Save pdparker/9910919 to your computer and use it in GitHub Desktop.
Rock Paper Scissors Lizard Spock - Written in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import difflib | |
import random | |
def name_to_number(x): | |
''' | |
Coverts player choice to number. | |
''' | |
#Uses dict rather than conditionals. | |
my_dict = {'rock':0, 'Spock':1, 'paper':2, 'lizard':3, 'scissors':4} | |
#returns the value associated with the string key | |
return my_dict[x] | |
def number_to_name(x): | |
''' | |
Takes number from name_to_number and converts back to name. | |
''' | |
#Using dict rather than conditionals | |
my_dict = {0:'rock', 1:'Spock', 2:'paper', 3:'lizard', 4:'scissors'} | |
#returns the value associated with the string key | |
return my_dict[x] | |
def winners(x,y): | |
''' | |
Defines the winner or the rpsls round | |
''' | |
if x==y: | |
return 'Player and computer tie.' | |
elif (name_to_number(x)-name_to_number(y))%5 < 3: | |
return 'Player wins!' | |
else: | |
return 'Computer wins!' | |
def computer_choose(): | |
''' | |
Defines computers choice randomly. | |
''' | |
#Would be worth tracking player choices and alter probability of choice. | |
y = number_to_name(random.randrange(0,5)) | |
return(y) | |
def rpsls(x): | |
''' | |
Plays a round of rpsls. Fuzzy matching for misspelling. | |
''' | |
pos = ['rock','Spock','paper','lizard','scissors'] | |
if x not in pos: | |
print "%s is not a playable choice. Will take best guess at what you mean:\n" %(x) | |
x = difflib.get_close_matches(x, pos, n=1) | |
if not x: | |
raise Exception("Nope! Could not figure out what you meant. try again.") | |
else: | |
x = str(x).strip('[\']') | |
y = computer_choose() | |
print 'Player chooses %s' %(x) | |
print 'Computer chooses %s' %(y) | |
print winners(x,y) | |
print '\n' | |
# test your code - LEAVE THESE CALLS IN YOUR SUBMITTED CODE | |
rpsls('rock') | |
rpsls('Spock') | |
rpsls('paper') | |
rpsls('lizard') | |
rpsls('scissors') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment