Python 模拟完整的单人猪游戏的程序,从总分 0 开始,一回合接一回合地玩,直到达到 100 分

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

所以这是一个示例输出: - 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

下面是我尝试解决它的方法:

`    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)`

我尝试做的是首先制作一个将掷骰子的内部循环,添加值(除非出现 1,在这种情况下回合分数将为 0)并将其作为回合分数显示。

然后我想把它作为一个整体循环,直到达到>=100的总回合分数。

谁能解释一下我哪里错了?

这是我 运行 时得到的输出: 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

在您的 else 块中,更改

score+=dice_value

turn_score += dice_value

您永远不会在循环中的任何一点递增 turn_score,因此 while 循环只会在它掷出 1 并命中 break 语句时才结束。此外,有了这条线,您将添加到 score 转弯处,这不应该发生。