Breaking a tie in python rock/paper/scissors with recursive function call

Viewed 42

I haven't seen a thread quite like this for python, specifically a recursive solution without human input. I have a network structure agent based model and the agents travel around the network, playing R/P/S when they meet. That part is fine.

What isn't working is having them play again upon a tie. My function for R/P/S:

def rps(a, b): 
    moves = ['rock','paper','scissors']
    winner = 0
    a_c = random.choice(moves) # choice for a
    b_c = random.choice(moves) # choice for b
    while winner == 0: # Attempt to keep it going until a non-tie scenario
        if a_c == 'rock' and b_c == 'scissors':
            winner = a
        if a_c == 'rock' and b_c == 'paper':
            winner = b
        if a_c == 'rock' and b_c == 'rock':
            winner = rps(a,b) # Attempt at recursive call
        if a_c == 'scissors' and b_c == 'paper':
            winner = a
        if a_c == 'scissors' and b_c == 'rock':
            winner = b
        if a_c == 'scissors' and b_c == 'scissors':
            winner = rps(a,b)
        if a_c == 'paper' and b_c == 'rock':
            winner = a
        if a_c == 'paper' and b_c == 'scisssors':
            winner = b
        if a_c == 'paper' and b_c == 'paper':
            winner = rps(a,b)

    return winner

Originally I did not have the while loop and had ties set winner = 0, in which case the agents didn't move. However, forcing continued games within the function seemed easy conceptually. I tried testing with the following:

for i in range(50):
    print(rps(1,2))

But upon the first tie, the loop is stuck. Help? I know this is a n00b question. I don't have a formal coding background and am learning as I go. Thank you very much for any explanation for what I'm inevitably doing wrong.

1 Answers
if a_c == 'paper' and b_c == 'scisssors':

contains an extra s in the condition checking b_c. If a_c is 'paper' and b_c is 'scissors', then none of the cases will match, and your code will loop infinitely.

Instead, use:

if a_c == 'paper' and b_c == 'scissors':

(As an aside, you don't need the while loop, because you're using recursion to play another round on a tie.)

Related