mikki
mikki

Reputation: 13

Why does my recursive function unwind and return the first score instead of the last score?

I am making a simple dice game where if you throw a double, you get a second go and I am trying to use recursion to do this, but the takeTurn() function always returns the scores of the first throw, never the sum of the first and second scores together.

So, if a player throws a 4 and a 4, followed by a 3 and a 2, I expect the score to be 13, but instead it returns 8.

Here is the takeTurn() function which expects the players name and current score:

def takeTurn(player, score):
    print("Get ready to play",player)
    throw=input("Press return key to throw a dice")
    throw1=diceThrow()
    print(" You threw a ", throw1)
    throw=input("Press return to throw a dice")
    throw2=diceThrow()
    print(" You threw a ", throw2)
    score=score+throw1+throw2
    print(player,"your score inside takeTurn function is",score)
    if throw1==throw2:
        print(player,"You threw a double so go again")
        takeTurn(player,score)
    print(player,"your score inside takeTurn function is now",score)
    return score

Here is where I initialise scores and call it:

player1Score=0
player2Score=0
players=playerNames()
player1=players[0]
player2=players[1]
player1Score=takeTurn(player1,player1Score)
print(player1, "Your score is",player1Score)
player2Score=takeTurn(player2,player2Score)
print(player2, "Your score is ",player2Score)

Here is the output I get showing the function unwinding - but I was expecting to get 13 returned.

Get ready to play Bob
Press return key to throw a dice
 You threw a  4
Press return to throw a dice
 You threw a  4
Bob your score inside takeTurn function is 8
Bob You threw a double so go again
***************************************
Get ready to play Bob
Press return key to throw a dice
 You threw a  3
Press return to throw a dice
 You threw a  2
Bob your score inside takeTurn function is 13
Bob your score inside takeTurn function is now 13
Bob your score inside takeTurn function is now 8
Bob Your score is 8

Upvotes: 0

Views: 155

Answers (2)

Ballistic_Beagle
Ballistic_Beagle

Reputation: 11

You don't do anything with the returned score from the inside takeTurn. You would likely want to do something to the effect of

if throw1==throw2:
        print(player,"You threw a double so go again")
        return takeTurn(player,score)

Upvotes: 0

MEE
MEE

Reputation: 2412

You forgot to update the outer-scope score with the nested takeTurn result. Change to:

    if throw1 == throw2:
        ...
        score = takeTurn(player, score)

Upvotes: 1

Related Questions