I have to write a program game similar to rock paper scissors, but with five options instead of three. I was able to write the code with a system of ifs, but I would like to know if there is a better way to write the code.
Game rules:
As you can see, there are a total of 5 options (X → Y means X wins over Y):
- Rock → Lizard & Scissors
- Paper → Rock & Spock
- Scissors → Paper & Lizard
- Lizard → Spock & Paper
- Spock → Scissors & Rock
Main Code:
import random
from ex2_rpsls_helper import get_selection
def rpsls_game():
com_score = 0
player_score = 0
draws = 0
while(abs(com_score - player_score) < 2):
print(" Please enter your selection: 1 (Rock), 2 (Paper), 3 (Scissors), 4 (Lizard) or 5 (Spock): ")
selection = int(input())
# a while loop to make sure input i between 0<x<6
while(selection <= 0 or selection > 5):
print( "Please select one of the available options.\n")
selection = int(input())
com_selection = random.randint(1,5)
print(" Player has selected: "+get_selection(selection)+".")
print(" Computer has selected: "+get_selection(com_selection)+".")
# A set of else and elseif to determin who is the winner
if(give_winner(selection, com_selection)):
print(" The winner for this round is: Player\n")
player_score += 1
elif(give_winner(com_selection,selection)):
print(" The winner for this round is: Computer\n")
com_score += 1
else:
print(" This round was drawn\n")
draws += 1
print("Game score: Player "+str(player_score)+", Computer "+str(com_score)+", draws "+str(draws))
if(player_score > com_score):
return 1
else:
return -1
The IFS system:
def give_winner(first_selection, second_selection):
if(first_selection is 1):
if(second_selection is 3 or second_selection is 4):
return True
elif(first_selection is 2):
if(second_selection is 1 or second_selection is 5):
return True
elif(first_selection is 3):
if(second_selection is 2 or second_selection is 4):
return True
elif(first_selection is 4):
if(second_selection is 2 or second_selection is 5):
return True
elif(first_selection is 5):
if(second_selection is 3 or second_selection is 1):
return True
return False
Any ideas?
is. Even if that usually works with integers in the range from -5 to 255, it is not correct. You are not interested on if you have the same object, but if they have the same value. Thus, use==.