rock Spock paper lizard scissors en phyton básico

En una ocasión os mencioné coursera, y coursera consigue que haga este código muy básico de python. ¿Conocéis el juego de The Big Bang Theory? Os dejo un video muy ilustrativo:

Una imagen para tener delante las relaciones del juego, y aquí el código acorde a la última versión de python ^^


juego.py: Pulsa para ver/ocultar el código
# 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 the library for random numbers
import random

# Convert the number to the correspond number
def number_to_name(number):
    #mod five to avoid wrong numbers
    number=number%5
    if number==0 :
        result="rock"
    elif number==1:
        result="Spock"
    elif number==2:
        result="paper"
    elif number==3:
        result="lizard"
    else:
        result="scissors"
    
    return result;

#convert the name to number
def name_to_number(name):
    result=None
    if name=="rock":
        result=0
    elif name=="Spock":
        result=1
    elif name=="paper":
        result=2
    elif name=="lizard":
        result=3
    elif name=="scissors":
        result=4
    else:
        print("Wrong name!! The options are: ")
        print("rock,Spock,paper,lizard,scissors")
        print("")
        result=-1 # return a negative number for error
    
    return result;

#game
def rpsls(name): 
    # convert name to player_number using name_to_number
    player_number=name_to_number(name)
    
    #check first if I have no errors
    if player_number >=0 :
        # compute random 
        computer_number=random.randrange(0,5)

        # compute difference of player_number and comp_number modulo five
        result_game=(player_number-computer_number)%5
        # use if/elif/else to determine winner
        if result_game==0:
            who_wins="Player and computer tie!"
        elif result_game > 2:
            who_wins ="Computer wins!"
        else :
            who_wins="Player wins!"
        
        # convert comp_number to name using number_to_name
        name_computer=number_to_name(computer_number)
        # print results
        print("Player chooses " + name)
        print("Computer chooses "+name_computer)
        print (who_wins)
        print
    
# test your code
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
#test any error
rpsls("wrong name")

Etiquetas: ,,,,,,,. Guarda el enlace permanente.

Deja un comentario ^^