Saturday, 3 May 2014

Rock-Paper-Scissor-Lizard-Spock game in PYTHON

The key idea of this game is as follows:
It's very simple:

  1. Scissors cuts paper
  2. Paper covers rock
  3. Rock crushes lizard
  4. Lizard poisons Spock
  5. Spock smashes scissors
  6. Scissors decapitates lizard
  7. Lizard eats paper
  8. Paper disproves Spock
  9. Spock vaporizes rock
  10. Rock crushes scissors
The program is as follows:


# 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
import math
def name_to_number(name):
    
    if(name=="rock"):
        num=0
    elif(name=="spock"):
        num=1
    elif(name=="paper"):
        num=2
    elif(name=="lizard"):
        num=3
    elif(name=="scissors"):
        num=4
    else:
        num=None
    return num



def number_to_name(number):
   
    if(number==0):
        name="rock"
    elif(number==1):
        name="spock"
    elif(number==2):
        name="paper"
    elif(number==3):
        name="lizard"
    elif(number==4):
        name="scissors"
    else:
        name=None
    return name

   
    

def rpsls(player_choice): 
    
    
    # print a blank line to separate consecutive games
    print
    # print out the message for the player's choice
    print "Player's choice: ", player_choice
    # convert the player's choice to player_number using the function name_to_number()
    player_number=name_to_number(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 out the message for computer's choice
    print "Computer's choice: " , comp_choice
    # compute difference of comp_number and player_number modulo five
    
    result=(comp_number-player_number)%5
    if(result>=0):
        if(result>=3):
            print "Player wins"
        elif(result==0):
            print "There is a tie"
        else:
            print "Computer wins"
    else:
        if(result>-3):
            print "Computer wins"
        else:
            print "Player wins"
        
   
    
# test your code 
rpsls("rock")
rpsls("spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")

No comments:

Post a Comment