【发布时间】:2014-06-06 05:25:12
【问题描述】:
我们正在尝试制作一个 python 程序来模拟掷骰子游戏并显示获胜的概率。我已经缩小了while循环的答案,正如标题所示,当它到达循环时它不会退出。据我所知,循环应该退出,而只是返回和无休止的“假”列车。这是带有 cmets 的整个程序的代码,我将在底部输入掷骰子的规则(就我们在程序中使用的而言)。
import random
def craps()
roll = random.randint(1,6) + random.randint(1,6)
if (roll == 7 or roll == 11): #Tests if the player should win. If so it adds a 1 to the win counter
return 1
elif (roll == 2 or roll == 3 or roll == 12): #Tests if player should lose. If so adds 0
return 0
else:
roll2 = 0 #initializes roll2 for the while
while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll
roll2 == random.randint(1,6) + random.randint(1,6) #Rolls the dice
if (roll2 == roll): #Tests if the player should win
return 1
elif (roll2 == 7): #Tests if the player should lose
return 0
win = 0 #Start the win counter at 0
games = int(input("Enter the amount of games you want played: ")) #Accept how many games will be played
for i in range (games):
win = win + craps() #adds a 1 or a 0 depending on if a game was won
print ("The probability of winning is:", win, "/", games, " =", float(win)/games) #print the probability of winning
我们使用的基本规则是:玩家掷出 2 个六面骰子,如果初始掷出的是 7 或 11,则玩家获胜(第 4 行)。如果玩家掷出 2、3 或 12,则玩家输掉(第 6 行) 如果玩家没有得到任何结果,他们将继续滚动,直到与初始掷骰相符或掷出 7。如果与初始掷骰相符,则获胜,如果他们得到一个 7 他们输了(第 10-15 行)。我们的程序应该模拟并显示玩家获胜的概率。
这是我第一次使用这个网站,所以如果我将来搞砸了任何事情,请告诉我。感谢您的帮助!
【问题讨论】:
-
大概 def 语句(需要冒号)延伸到 win=0 行?
标签: python random while-loop