Skip to content Skip to sidebar Skip to footer

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 that if player 1 won it would return -1, if player 2 won it would return 1 and if

Solution 1:

You can do following:

defrps(p1,p2):
    retval= {
        'R':{'R': 0, 'S':-1, 'P': 1},
        'S':{'R': 1, 'S': 0, 'P':-1},
        'P':{'R':-1, 'S': 1, 'P': 0}
    }
    return retval[p1][p2]

Solution 2:

You asked:

Can anyone help me see if my code is wrong?

Yes, it is wrong. Here's why.

If you run rps('R','S') you should get 1, because rock beats paper. Similarly rps('R','P') should give -1 because paper beats rock. Both of these work in your code.

However, if you run rps('S','P') you should get 1, because scissors beats paper, but you don't - your code returns -1, which is wrong.

As eumiro pointed out in the comments, the three lines

'R'>'S''P'>'R''S'>'P'

which I assume you think are defining the ordering to be used, don't actually do anything.

Solution 3:

defrps(x,y):
    return [0, -1, 1]['RPS'.index(x) - 'RPS'.index(y)]

Or if you want an interactive program:

from random import randint
['Tie', 'I win', 'You win'][randint(0, 2) - 'RPS'.index(raw_input("Enter R, P, or S: "))]

Solution 4:

defrps(x,y):
    d = {'R': 1, 'S': 2, 'P': 3}
    return ((d[x] - d[y]) + 1) % 3 - 1for p1 in'RPS':
    for p2 in'RPS':
        print p1, p2, rps(p1, p2)

prints

R R 0
R P1
R S -1P R -1PP0P S 1
S R 1
S P -1
S S 0

Post a Comment for "Rock Paper Scissors"