Home » Python » optimization – How efficient is my rock paper scissors that I made using python?-Exceptionshub

# optimization – How efficient is my rock paper scissors that I made using python?-Exceptionshub

Questions:

Let me know how I can optimize this code. I am fairly new to coding so any advice on my code would be appreciated. Any other features I could add to enhance my game would also be greatly appreciated. Thank you.

``````while True:
print('''Please pick one of the following:
Rock
Paper
Scissors''')
gameDict = {"rock":1,"paper":2,"scissors":3}

in1 = input("Player 1: ").lower()
in2 = input("Player 2: ").lower()

while in1 not in gameDict:
in1 = input("Player 1, please enter correct option: ").lower()
while in2 not in gameDict:
in2 = input("Player 2, please enter correct option: ").lower()
p1 = gameDict.get(in1)
p2 = gameDict.get(in2)

val = p1-p2

if val in [-1,2]:
print("Player 1 wins!!")
cont=input("Would you like to play again?(y/n): ")
if cont == "y":
continue
else:
break
elif val in [-2,1]:
print("Player 2 wins!!")
cont=input("Would you like to play again?(y/n): ")
if cont == "y":
continue
else:
break
else:
print("It's a tie!!")
cont=input("Would you like to play again?(y/n): ")
if cont == "y":
continue
else:
break
``````

Heres how its suppose to look.

I would use a dictionary with the move as the key and the value as the item that beats it. You could do this the other way around too.

``````def score(player1, player2):
game_dict = {'rock': 'scissors', 'paper': 'rock', 'scissors':'paper'}
if game_dict[player1] == player2:
return "Player 1 wins!!"
elif game_dict[player2] == player1:
return "Player 2 wins!!"
else:
return "It's a tie!!"

def engine():
while True:
player1 = input("Player 1: ").lower()
player2 = input("Player 2: ").lower()

print(score(player1, player2))

if input("Would you like to play again?(y/n): ") == 'n':
break

if __name__ == "__main__":
engine()
``````

Usually, when I’m looking to optimize my code, the first thing I look for is repeated blocks. Right away you could reduce your code by moving the `cont` item out of each if block and adding it to the end, since it is not dependent on the outcome of the game.

Moving forward I would definitely use functions as a way to compartmentalize your code in logical segments. As for features, try to add a variable to keep score for each player and print that after every round!

Good luck!