首页 > 解决方案 > 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

标签: pythonpython-3.xprobabilitydice

解决方案


在你的else街区,改变

score+=dice_value

turn_score += dice_value

您永远不会在循环中的任何点增加 turn_score,因此 while 循环仅在它滚动 1 并命中break语句时才会结束。此外,在这条线到位后,您将增加score可能会退出的转弯,这是不应该发生的。


推荐阅读