New programmer here. I am writing a rock, paper scissors game, so far I have managed to get it working, however I'm wondering how I could make it more efficient. I'd be very grateful for any suggestions :)
import random
choices = ['rock', 'paper', 'scissors']
result1 = random.choice(choices)
result2 = random.choice(choices)
print('player one has chosen ' result1)
print('player two has chosen ' result2)
if result1 == result2:
print('draw!')
In particular does anyone know if the code below can be simplified?
elif result1 == choices[0] and result2 == choices[1]:
print('player two wins!')
elif result1 == choices[0] and result2 == choices[2]:
print('player one wins!')
elif result1 == choices[1] and result2 == choices[2]:
print('player two wins!')
elif result1 == choices[1] and result2 == choices[0]:
print('player two wins!')
elif result1 == choices[2] and result2 == choices[0]:
print('player one wins!')
elif result1 == choices[2] and result2 == choices[1]:
print('player one wins!')
CodePudding user response:
One way to do it is to define the possible wins, for example using a dictionary,
import random
choices = ['rock', 'paper', 'scissors']
wins = {'rock': 'scissors',
'paper': 'rock',
'scissors': 'paper'}
result1 = random.choice(choices)
result2 = random.choice(choices)
print('player one has chosen ' result1)
print('player two has chosen ' result2)
if result1 == result2:
print('draw!')
elif result1 == wins[result2]:
print('player two wins')
else:
print('player one wins')
Example:
player one has chosen scissors
player two has chosen rock
player two wins
generalization
This makes it easy to generalize to a more complex situation, for instance rock/paper/scissors/lizard/Spock:
import random
wins = {'rock': set(['scissors', 'lizard']),
'paper': set(['rock', 'spock']),
'scissors': set(['paper', 'lizard']),
'lizard': set(['spock', 'paper']),
'spock': set(['rock', 'scissors'])
}
choices = list(wins)
result1 = random.choice(choices)
result2 = random.choice(choices)
print('player one has chosen ' result1)
print('player two has chosen ' result2)
if result1 == result2:
print('draw!')
elif result1 in wins[result2]:
print('player two wins')
else:
print('player one wins')
Example:
player one has chosen spock
player two has chosen scissors
player one wins
CodePudding user response:
You can use the or
operator -
elif (result1 == choices[1] and result2 == choices[2]) or (result1 == choices[1] and result2 == choices[0]) or (result1 == choices[0] and result2 == choices[1]):
print('player two wins!')
elif (result1 == choices[2] and result2 == choices[0]) or (result1 == choices[2] and result2 == choices[1]) or (result1 == choices[0] and result2 == choices[2]):
print('player one wins!')