Rock-paper-scissors-lizard-Spock in Python

by
Share this Article: Facebook0Google+0Twitter13LinkedIn0Reddit0StumbleUpon1

Rock-paper-scissors-lizard-Spock is an expansion of the classic selection method game rock-paper-scissors. It operates on the same basic principle, but includes two additional weapons: the lizard (formed by the hand as a sock-puppet-like mouth) and Spock (formed by the Star Trek Vulcan salute). This reduces the chances of a round ending in a tie. The game was invented by Sam Kass with Karen Bryla, as “Rock Paper Scissors Spock Lizard” and it was also mentioned in four episodes of The Big Bang Theory.

For more info, check out the this link.

And here is my Python script for the game :D

<pre>[cc escaped="true" lang="python"]
 # Include 'randrange' function (instead of the whole 'random' module
 from random import randrange

# Setup a dictionary data structure (working with pairs efficiently
 converter = {'rock':0, 'Spock':1, 'paper':2, 'lizard':3, 'scissors':4}

# Retrieves the name (aka key) of the corresponding number (aka value)
 def number_to_name(number):
 if (number in converter.values()):
 return converter.keys()[number]
 else:
 print ("Error: There is no '" + str(number) + "' in " + str(converter.values()) +'\n')

# Retrieves the number (aka value) of the corresponding name (aka key)
 def name_to_number(name):
 if (name in converter.keys()):
 return converter[name]
 else:
 print ("Error: There is no '" + name + "' in " + str(converter.keys()))

def rpsls(name):
 player_number = name_to_number(name)
 # converts name to player_number using name_to_number

comp_number = randrange(0,5)
 # compute random guess for comp_number using random.randrange()

result = (player_number - comp_number) % 5
 # compute difference of player_number and comp_number modulo five

# Announce the opponents to each other
 print 'Player chooses ' + name
 print 'Computer chooses ' + number_to_name(comp_number)

# Setup the game's rules
 win = result == 1 or result == 2
 lose = result == 3 or result == 4

# Determine and print the results
 if win:
 print 'Player wins!\n'
 elif lose:
 print 'Computer wins!\n'
 else:
 print 'Player and computer tie!\n'

# Main Program -- Test my code
 rpsls("rock")
 rpsls("Spock")
 rpsls("paper")
 rpsls("lizard")
 rpsls("scissors")

# Check my Helper Function reliability in case of wrong input
 #number_to_name(6) # Error in case of wrong number
 #name_to_number('Rock') # Error in case of wrong name
 [/cc]</pre>

For questions please refer to our Q/A forum at : http://ask.unixmen.com/

Share this Article: Facebook0Google+0Twitter13LinkedIn0Reddit0StumbleUpon1