Skip to content

Instantly share code, notes, and snippets.

@anirudhjayaraman

anirudhjayaraman/RPSLS.py

Last active Aug 29, 2015
Embed
What would you like to do?
Code for IIPP Mini Project [Rock Paper Scissors Lizard Spock]
# Rock-paper-scissors-lizard-Spock template
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
import random
# helper functions
def name_to_number(name):
if name == "rock":
number = 0
return number
elif name == "Spock":
number = 1
return number
elif name == "paper":
number = 2
return number
elif name == "lizard":
number = 3
return number
elif name == "scissors":
number = 4
return number
else:
error = "Invalid play..."
return error
# convert name to number using if/elif/else
def number_to_name(number):
if number == 0:
name = "rock"
return name
elif number == 1:
name = "Spock"
return name
elif number == 2:
name = "paper"
return name
elif number == 3:
name = "lizard"
return name
elif number == 4:
name = "scissors"
return name
else:
error = "invalid number..."
return error
# convert number to a name using if/elif/else
def rpsls(player_choice):
# print out the message for the player's choice
print "Player chooses " + str(player_choice)
# compute random guess for comp_number using
# random.randrange()
comp_number = random.randrange(0, 5)
# convert comp_number to comp_choice using the
# function number_to_name()
comp_choice = number_to_name(comp_number)
print "Computer chooses " + str(comp_choice)
# convert the player's choice to player_number
# using the function name_to_number()
player_number = name_to_number(player_choice)
#
# \n is used to print a blank line to separate
# consecutive games
if type(player_number) == int:
# compute difference of comp_number and player_number
# modulo five - if player_number is an integer
# player_number is a string if function
# name_to_number returns an error message
diff_modulo_five = (player_number - comp_number) % 5
# use if/elif/else to determine winner, print
# winner message
if diff_modulo_five in range(1,3):
print "Player wins!\n"
elif diff_modulo_five in range(3,5):
print "Computer wins!\n"
else:
print "Player and computer tie!\n"
else:
# print no outcome in case of erroneous input
print name_to_number(player_choice) + " no outcome!"
# test your code - THESE CALLS MUST BE PRESENT IN
# YOUR SUBMITTED CODE
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
rpsls("random erroneous input")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment