【问题标题】:Dice rolling program with counter带计数器的掷骰子程序
【发布时间】:2020-09-18 00:53:42
【问题描述】:

我是编程新手,我有一个自己无法完成的任务。

任务是编写一个程序,让您决定掷多少个骰子,从 1 到 5,并检查您是否输入错误。 每次滚动后,将显示骰子的数量和到目前为止的总数。 如果骰子掷出 6,则它不包括在总数中,您将获得更多的掷骰。这就是我卡住的地方。如果骰子变成 6,我希望我的程序重新启动循环,并且仅将 2 掷到 sumDices 并继续循环,但我无法让它工作。

这是我的代码:

import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
    while True:
        numDices=int(input("How many dices to throw? (1-5) "))
        if numDices<1 or numDices>5:
            print("Wrong input, try again")
            break
        while True:
            if reset==True:
                break
            for i in range(numDices):
                dicesArray = list(range(numDices))
                dicesArray[i] = random.randint(1, 6)
                print(dicesArray[i])
                total += dicesArray[i]
                if dicesArray[i] == 1:
                    print("You rolled a one, the total is: ",str(total))
                elif dicesArray[i] == 2:
                    print("You rolled a two, the total is: ",str(total))
                elif dicesArray[i] == 3:
                    print("You rolled a three, the total is: ",str(total))
                elif dicesArray[i] == 4:
                    print("You rolled a four, the total is: ",str(total))
                elif dicesArray[i] == 5:
                    print("You rolled a five, the total is: ",str(total))
                elif dicesArray[i] == 6:
                    total-=6
                    numDices+=2
                    print("You rolled a six, rolling two new dices")
                    reset=True
        print("The total sum is",str(total),"with",numDices,"number of rolls.")
        print()
        restart=(input("Do you want to restart press Enter, to quit press 9. "))
        if restart=="9":
            exit=True
            break
        else:
            print()
            break
    if exit==True:
        break

【问题讨论】:

  • 你遇到了什么错误?
  • 我没有收到错误,问题是如果骰子掷出六,它不会再掷两次,它只是加到总和中并从总数中减去,而不掷两次更多次。如果骰子掷出六,则需要再掷两次,加上原来的掷数。对不起我的英语不好
  • 为什么是第 35 行 total-=6
  • 因为如果骰子掷出六,那不应该计入总数,而是多掷两次。新卷应添加到总数中,除非其中之一是六,然后重新滚动计数。

标签: python python-3.x list random dice


【解决方案1】:

您可以通过以下方式进行操作,稍微修改您的代码,计算可用的骰子。我也减少了那里的嵌套循环

import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
start = True
while start:
    numDices=int(input("How many dices to throw? (1-5) "))
    if numDices<1 or numDices>5:
        print("Wrong input, try again")
        break
    total = 0
    dices_counter = 0
    while numDices > 0 :
        eyes = random.randint(1, 6)
        dices_counter+=1 
        total += eyes
        if eyes == 1:
            print("You rolled a one, the total is: ",str(total))
            numDices-=1
        elif eyes == 2:
            print("You rolled a two, the total is: ",str(total))
            numDices-=1
        elif eyes == 3:
            print("You rolled a three, the total is: ",str(total))
            numDices-=1
        elif eyes == 4:
            print("You rolled a four, the total is: ",str(total))
            numDices-=1
        elif eyes == 5:
            print("You rolled a five, the total is: ",str(total))
            numDices-=1
        elif eyes == 6:
            total-=6
            numDices+=2
            print("You rolled a six, rolling two new dices")
    print("The total sum is",str(total),"with",dices_counter,"number of rolls.")
    print()
    start=(input("Do you want to restart press Enter, to quit press 9. "))
    if start=="9":
        break
    else:
        print()
        start = True

【讨论】:

  • 感谢您的大力帮助!
  • 很高兴它有帮助。如果某个答案解决了您的问题,您可以用答案左侧的灰色复选标记标记相关答案
【解决方案2】:

为了解决你的问题,我会用 while 循环替换你当前的 for 循环

此外,我在您的代码中看到很多不必要的东西,我将尝试列出它们:

  • 你为什么用这么多“while True”?

  • 为什么不直接使用 exit() 函数退出而不是使用 变量?

  • 是否真的需要所有 if 部分,你不能只打印 号码?

这是我的建议:

import random
remaining_dices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()

while True:
    remaining_dices=int(input("How many dices to throw? (1-5) "))
    if remaining_dices<1 or remaining_dices>5:
        print("Wrong input, try again")
        break
    dicesArray = list()
    while remaining_dices>0:
        dice_value = random.randint(1, 6)
        dicesArray.append(dice_value)
        print(dice_value)
        total += dice_value
        remaining_dices -= 1
        if(dice_value == 6):
            total-=6
            remaining_dices +=2
            print("You rolled a 6, rolling two new dices")
        else:
            print("You rolled a " + str(dice_value) + ", the total is : " +str(total))

    restart=(input("Do you want to restart press Enter, to quit press 9. "))
    if restart=="9":
        exit()
    else:
        print()

【讨论】:

  • 对编程非常陌生,并且没有很多好的教学。非常感谢您的意见。谢谢!
【解决方案3】:
for i in range(numDices):

您的 for 循环会在评估/执行 range(numDices) 后立即限制迭代次数。当您尝试使用 numDices+=2 增加迭代次数时,它没有任何效果,因为 range(numDices) 只被评估一次。

如果您希望能够更改迭代次数,请使用另一个 while 循环并使用 i 作为计数器。类似的东西。

i = 0
while i <= numDices:
    ...
    ...
    if ...:
        ...
    elif ...:
    ...
    i += 1

那么在elif dicesArray[i] == 6: 的套件中,numDices += 2 语句将有效地增加迭代次数。


我看到了另一个你没有提到的问题。您从基于 numDices 的原始值的固定长度列表开始,并使用 i 作为该列表的索引。

dicesArray = list(range(numDices))`
...
dicesArray[i]
...

如果i 可能大于原始 numDices(大于len(dicesArray)),您最终会收到IndexError。您可能应该从一个空列表开始并附加到它。要获取最近的掷骰子,请使用 dicesArray[-1] 而不是 dicesArray[i]

...
dicesArray = []
i = 0
while i <= numDices:
    dicesArray.append(random.randint(1, 6))
    total += dicesArray[-1]
    if dicesArray[-1] == 1:
        ...
    ...

6.3.2. Subscriptions

【讨论】:

  • 哇,真的是教学帮助。谢谢!
【解决方案4】:

使用递归函数

import random

total = 0
diceRollList = []

# Define dice rolling function
def rollDice():
    rollResult = random.randint(1, 6)
    if rollResult == 6:
        # If 6 Rolled run two more rolls and sum the results
        print("Rolled a 6 Rolling 2 more")
        return sum([rollDice() for _ in range(2)])
    # If 6 not rolled return the result
    print(f"Rolled a {rollResult}")
    return rollResult

while True:

    numberOfDice = int(input("How many Die to throw: "))

    if numberOfDice not in range(1, 6):
        print("Number of dice should be between 1 and 5")
        break

    for dice in range(numberOfDice):
        print(f"Rolling Dice {dice}")
        # Add result to the total
        total += rollDice()
        print(f"Running Total: {total}")

【讨论】:

    【解决方案5】:

    这个跟踪它滚动了多少:

    import random
    
    a = int(0)
    b = int(0)
    c = int(0)
    d = int(0)
    e = int(0)
    f = int(0)
    limit = 101
    count = 0
    
    while True:
        g = (random.randint(1, 6))
        print(g)
        count += 1
        if g == 1:
            a += 1
        elif g == 2:
            b += 1
        elif g == 3:
            c += 1
        elif g == 4:
            d += 1
        elif g == 5:
            e += 1
        elif g == 6:
            f += 1
        if count > limit:
            break
    
    print(f"There are {a} 1's")
    print(f"There are {b} 2's")
    print(f"There are {c} 3's")
    print(f"There are {d} 4's")
    print(f"There are {e} 5's")
    print(f"There are {f} 6's")
    

    【讨论】:

    • int(0) == 0 在 Python 中
    • 为什么还要使用需要维护count 变量和breakwhile 循环?为什么不只是for _ in range(limit):
    猜你喜欢
    • 2019-03-04
    • 2014-04-21
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多