Python的Craps模拟器

2024-10-01 17:38:28 发布

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

问题是要模拟一些垃圾游戏。你掷两个6面骰子。如果掷骰加起来是2、3或12,则该玩家将输掉该游戏。如果掷骰加起来是7或11,则玩家获胜。如果掷骰加起来是其他数字,玩家会重新掷骰,直到上一个掷骰量再次掷骰,或者掷到7。如果先掷7分,这场比赛算胜利。如果先前的掷骰数量是第一次掷骰,游戏将被视为失败。我们应该显示赢的数量和占总数的百分比。在

我不太确定我有什么错-获胜的百分比应该在50%左右,但是当我运行这个程序时,我通常会得到1-3%的成功率。编辑:实际上我不确定概率是否应该是50%,但我很确定它不应该是1-3%。。。在

from random import *

def craps():
printIntro()
n=getInput()
winCount=simRoll(n)
printResults(n, winCount)


def printIntro():

print('This program simulates the popular casino game "craps." A player rolls a pair of normal six-sided dice.')
print('If the initial roll is a 2, 3, or 12, the player loses. If the initial roll is a 7 or 11, the player wins.')
print('Any other initial roll causes the player to "roll for point." The player keeps rolling the dice until either rolling')
print('a 7 or re-rerolling the value of the initial roll. If the player re-rolls the initial value before rolling a 7, it is a win.')
print('If the player rolls a 7 first, it is a loss.')
print('\nThis program simulates n games of craps and calculates the percent of games won.')


def getInput():

n=eval(input("Input the amount of games of craps to simulate: "))
return n


def simRoll(n):
rollCount=0
winCount=0
PointForRoll=0

while rollCount < n:

        rollCount=rollCount+1

        randomRoll=randrange(1,7) + randrange (1,7)

        if randomRoll == 2 or randomRoll == 3 or randomRoll == 12:
            winCount = winCount + 0

        if randomRoll == 7 or randomRoll == 11:
            winCount = winCount + 1

        else:

            while PointForRoll != 7 or PointForRoll != randomRoll:

                PointForRoll = randrange(1,7) + randrange(1,7)

                if PointForRoll == randomRoll:
                    winCount=winCount

                if PointForRoll == 7:
                    winCount=winCount+1

                return PointForRoll

return winCount


def printResults(n, winCount):

print('\nFor', n, 'games of craps simulated,', winCount, 'games were wins, giving a success rate of '+ str(100*(winCount/n)) + '%.')


if __name__ == '__main__': craps()

谢谢你!在


Tags: oroftheifdefgamesinitialplayer
2条回答
if randomRoll == 2 or randomRoll == 3 or randomRoll == 12:
    winCount = winCount + 0
if randomRoll == 7 or randomRoll == 11:
    winCount = winCount + 1
else:

第二个if应该是elif。如果掷骰是2、3或12,您不希望输入else。在

^{pr2}$

or应该是and。当掷骰子不是7并且掷骰子不是重点。在

if PointForRoll == randomRoll:
    winCount=winCount
if PointForRoll == 7:
    winCount=winCount+1

这是倒退。掷7分是一种损失。抓住要点就是胜利。您应该在第一个if中递增获胜计数。在

return PointForRoll

删除此行。您不应该从此循环返回。在

while PointForRoll != 7 and PointForRoll != randomRoll:
    ...

最后,在这个循环结束后,您永远不会重置PointForRoll。在循环之前或之后添加PointForRoll = 0。在

所有这些改变,我得到了一个50%左右的成功率。在

现在,如果你掷出2,3或11,你的程序仍然会试图说明问题。而不是:

if randomRoll == 2 or randomRoll == 3 or randomRoll == 12:
   ....

if randomRoll == 7 or randomRoll == 11:
  ...

else:
  ...

你想试试吗

^{pr2}$

这样,2、3和12的骰子就不会在你最后的“else”中使用代码

相关问题 更多 >

    热门问题