模拟一场骰子游戏1000次

2024-06-16 10:51:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中使用random来模拟一个垃圾游戏。然后我模拟游戏n次,看看玩家打败庄家的频率。我有一个带有种子的测试文件来检查我的代码,但是我的数字有点偏差。我认为错误出在结构上,但似乎搞不清到底是什么。在

掷骰子

def quietRoll():
    return random.randrange(1,7) + random.randrange(1,7)

垃圾模拟

^{pr2}$

运行垃圾n次

def testCraps(n):
    count = 0
    playerWin = 0
    while count <= n:
        if quietCraps() == 1:
            playerWin += 1
            count += 1
        else:
            count += 1
return playerWin/n

预期输出

Failed example:

random.seed(5)
testCraps(1000)

Expected:
    0.497
Got:
    0.414

Tags: 文件游戏returndefcount玩家random种子
1条回答
网友
1楼 · 发布于 2024-06-16 10:51:37
newDice = quietRoll()
while newDice not in (7, firstRoll):
    newDice = quietRoll()
    if newDice == firstRoll:
        return 1
    if newDice == 7:
        return 0

如果newDice第一次落在7firstRoll上,则在没有命中return语句的情况下从函数的末尾掉下来,并且该函数默认返回None。在

由于return语句结束函数(停止该函数可能正在执行的任何循环并跳过该函数的任何剩余代码),因此可以通过在循环之前使循环为while True而不初始化{}来解决此问题:

^{pr2}$

或者,您可以将if检查移出循环,这样只要骰子落在7或{}上,它们就会发生,而不管它是在循环内部还是在循环外部:

newDice = quietRoll()
while newDice not in (7, firstRoll):
    newDice = quietRoll()
if newDice == firstRoll:
    return 1
if newDice == 7:
    return 0

相关问题 更多 >