Python中的赌博游戏
我正在尝试模拟n局掷骰子游戏。代码看起来没问题,但结果总是不对。例如,当我输入n = 5,也就是五局游戏时,赢和输的总和却大于5。
这个游戏的规则是这样的:如果第一次掷骰子的结果是2、3或12,玩家就输了。如果结果是7或11,玩家就赢了。其他的结果则需要再掷一次。玩家会一直掷骰子,直到他掷出7或者第一次掷出的那个数字。如果在掷出7之前,玩家又掷出了第一次的那个数字,那就是赢了。如果先掷出7,那就是输了。
from random import randrange
def roll():
dice = randrange(1,7) + randrange (1,7)
return dice
def sim_games(n):
wins = losses = 0
for i in range(n):
if game():
wins = wins + 1
if not game():
losses = losses + 1
return wins, losses
#simulate one game
def game():
dice = roll()
if dice == 2 or dice == 3 or dice == 12:
return False
elif dice == 7 or dice == 11:
return True
else:
dice1 = roll()
while dice1 != 7 or dice1 != dice:
if dice1 == 7:
return False
elif dice1 == dice:
return True
else:
dice1 = roll()
def main():
n = eval(input("How many games of craps would you like to play? "))
w, l = sim_games(n)
print("wins:", w,"losses:", l)
5 个回答
1
别这么做
for i in range(n):
if game():
wins = wins + 1
if not game():
losses = losses + 1
这样做一点也不好。
3
在这段代码中
for i in range(n):
if game():
wins = wins + 1
if not game():
losses = losses + 1
你调用了 game()
两次,这样就玩了两局游戏。你想要的是一个 else 块:
for i in range(n):
if game():
wins = wins + 1
else:
losses = losses + 1
顺便说一下,你可以用 in
来简化逻辑:
def game():
dice = roll()
if dice in (2,3,12):
return False
if dice in (7,11):
return True
# keep rolling
while True:
new_roll = roll()
# re-rolled the initial value => win
if new_roll==dice:
return True
# rolled a 7 => loss
if new_roll == 7:
return False
# neither won or lost, the while loop continues ..
这段代码实际上就是你描述的内容。
5
问题出在
if game():
wins = wins + 1
if not game():
losses = losses + 1
而应该是
if game():
wins = wins + 1
else:
losses = losses + 1
在你的代码中,你实际上是在模拟两个游戏,而不是一个(因为你调用了 game()
两次)。这样会产生四种可能的结果,而不是两种(赢/输),导致整体结果不一致。