Rock Paper Scissors
I had a test for my comp sci class and one of the questions was to make a rock paper scissors game, if winner 1 won, it would return -1, if player won 2, it would return 1. and if it was a draw it would return 0. I did my program and ran and it worked, but according to my professor, he said it wasn't.
def rps(x,y):
player1 = -1
player2 = 1
tie = 0
'R'>'S'
'P'>'R'
'S'>'P'
if x>y:
return player1
if x<y:
return player2
else:
return tie
I don't see what's wrong with that? If you do rps ("R", "P") then it will return -1 because x = player1 and because Rock hits Paper. Can anyone help me find out if my code is wrong?
source to share
There are several problems in your code:
1. The following lines do nothing. You cannot set a character R
greater than a character S
:
'R' > 'S'
'P' > 'R'
'S' > 'P'
2. Reason for section 1, yours if x>y:
doesn't do what you think. It just checks if the content is x
before the content y
in the alphabet. (Assume content x
and y
are characters)
Your code is difficult to fix, I would recommend that you approach this problem from a completely different angle.
The solution here is completely different from yours, but it works. It just uses a lot of checks if
to get the result.
def rps(p1, p2):
if p1 == p2:
return 0
elif (p1 == "R" and p2 == "S")\
or (p1 == "S" and p2 == "P")\
or (p1 == "P" and p2 == "R"):
return -1
else:
return 1
I replaced x, y
with p1, p2
as they represent the best player options, but if you need to use x
and y
, just change them.
You asked:
Can someone help me see if my code is wrong?
Yes, it’s wrong. That's why.
If you run rps('R','S')
, you should get 1
it because rock beats paper. Likewise, I rps('R','P')
have to give -1
, because paper hits rock. They both work in your code.
However, if you run rps('S','P')
, you should get 1
because the scissors hit the paper, but you don't - your code returns -1
, which is wrong.
As Emumi pointed out in the comments, three lines
'R'>'S'
'P'>'R'
'S'>'P'
which I assume you think is the defining application to use, is not really doing anything.
source to share