Python 模拟掷 6 面骰子并将每次掷骰结果相加直到掷出 1 的程序

Python program that simulates rolling a 6 sided die and adds up the result of each roll till you roll a 1

所以这是我写的代码,试图回答标题中的问题:

import random
print("Well, hello there.")
while True:
    a = random.randint(1,6)
    sum = 0
    if(a==1): #If a one is indeed rolled, it just shows rolled a 1 and 'Pigs out' and makes the score equal to 0(player score that is) and is a sort of a GameOver
        print("Pigged out!")
        break #To get out of the loop
    else:
        while(sum<=20): 
            sum += a
            print(sum)

程序应该保持分数直到达到 20(或更多)并显示它。它本质上代表 'Pig' 的单圈。我无法弄清楚我哪里出了问题?任何建议都会有所帮助。

示例输出示例:

-rolled a 6 -rolled a 6 -rolled a 5 -rolled a 6 -Turn score is 23

如果你只想显示大于 20 的总和,你不应该取消 print(sum) 向左缩进吗?本质上:

while(sum<=20): 
    sum += a
print(sum)

如果您能说明您希望输出的内容以及当前正在做什么,那就太好了。

总和超过20就应该分手了

else:
    while(sum<=20): 
        sum += a
        print(sum)
    break

编辑:

import random
print("Well, hello there.")
while True:
    a = random.randint(1,6)
    sum = 0
    if(a==1): #If a one is indeed rolled, it just shows rolled a 1 and 'Pigs out' and makes the score equal to 0(player score that is) and is a sort of a GameOver
        print("Pigged out!")
        break #To get out of the loop
    else:
        if not SumWasReached:
           while(sum<=20): 
               a = random.randint(1,6)
               sum += a
               print(sum)
           SumWasReached ==True:
        else:
            while(a!=1):
               a = random.randint(1,6)
            break

这是你想要的吗?

import random
print("Well, hello there.")
sum=0
while True:
    a = random.randint(1,6)
    sum+=a
    if(a==1): #If a one is indeed rolled, it just shows rolled a 1 and 'Pigs out' and makes the score equal to 0(player score that is) and is a sort of a GameOver
        print("Pigged out!")
        break #To get out of the loop
    else:
        if sum<=20: 
            sum += a
            print(sum)
        else:
            print(sum,'limit reached')
            break

如果我理解正确,那么你可以简化很多,像这样:

import random
print("Well, hello there.")
score = 0
while score < 20:
    a = random.randint(1,6)
    print("A {} was rolled".format(a))
    score += a
    if a == 1:
        print("Pigged out!")
        score = 0
        break
print("Turn score is {}".format(score))