Search code examples
pythonpython-3.xprobabilitydice

Python program that simulates a full one player game of pig, starting at a totalscore of 0 and playing turn after turn until it reaches 100 points


So here is a sample output: - rolled a 2 - rolled a 1 Pigged out! Turn score = 0 New total score = 0 - rolled a 1 Pigged out! Turn score = 0 New total score = 0 - rolled a 6 - rolled a 6 - rolled a 6 - rolled a 5 Turn score = 23 #So on New total score = 90 - rolled a 6 - rolled a 6 - rolled a 3 Turn score = 15 New total score = 105

And here is how I tried to solve it:

`    import random
     print("Well, hello there.")
     score = 0
     while(score<=100):
         turn_score=0
         while (turn_score<=20):
             dice_value=random.randint(1,6)
             if (dice_value==1):
                 print("Pigged out! Better luck next time!")
                 turn_score=0
                 break #to get out of the loop in case a roll rolls up
             else:
                 print("-rolled a ",dice_value)
                 score+=dice_value 
                 print("Score is  ",turn_score)
        score+=turn_score
        print("Final score is: ",score)`

What I tried doing is first making an inner loop that will roll the dice, add the values(except if a 1 comes up, in which case the turn score would be 0) and present it as the turn score.

Then I thought of looping it as a whole till a total turn score of >=100 is reached.

Can someone explain where I went wrong here?

Here is the output I get when I run it: Well, hello there. -rolled a 3 Score is 0 -rolled a 2 Score is 0 -rolled a 6 Score is 0 Pigged out! Better luck next time! Final score is: 11 -rolled a 6 Score is 0 -rolled a 4 Score is 0 -rolled a 5 Score is 0 -rolled a 2 Score is 0 -rolled a 2 Score is 0 -rolled a 4 Score is 0 -rolled a 2 Score is 0 -rolled a 3 Score is 0 -rolled a 4 Score is 0 -rolled a 4 Score is 0 Pigged out! Better luck next time! Final score is: 47 -rolled a 6 Score is 0 -rolled a 5 Score is 0 -rolled a 6 Score is 0 -rolled a 5 Score is 0 -rolled a 6 Score is 0 Pigged out! Better luck next time! Final score is: 75 -rolled a 3 Score is 0 -rolled a 2 Score is 0 -rolled a 6 Score is 0 -rolled a 6 Score is 0 -rolled a 4 Score is 0 -rolled a 2 Score is 0 Pigged out! Better luck next time! Final score is: 98 -rolled a 6 Score is 0 -rolled a 4 Score is 0 -rolled a 2 Score is 0 -rolled a 3 Score is 0 Pigged out! Better luck next time! Final score is: 113


Solution

  • In your else block, change

    score+=dice_value
    

    to

    turn_score += dice_value
    

    You're never incrementing turn_score at any point in the loop, so the while loop is only ever ending when it rolls a 1 and hits the break statement. Additionally, with that line in place, you're adding to score on turns that would pig out, which isn't supposed to happen.