python - 骰子游戏模拟
问题描述
我有一个作业问题:
你的朋友设计了一个有两个玩家的游戏。两个玩家,称为 A 和 B,轮流掷一个普通的六面骰子,A 是第一个掷的。
第一个掷出 6 的玩家赢得游戏。您和您的朋友不同意 A 赢得游戏的概率,因此您决定用计算机模拟游戏。
因此:编写一个 Python 程序,执行 10 次试验,每次试验由 10000 场比赛组成,每次试验打印玩家 A 赢得的比赛的分数。
这是我到目前为止得到的代码,它每次只返回一个 1667 左右的数字。我主要想知道如何区分A或B赢得比赛。
任何帮助,将不胜感激!
编辑代码
import random
def rollDie():
return random.choice([1,2,3,4,5,6])
def roll_first():
if random.choice([0,1]) == 0:
return 'A'
else:
return 'B'
def rollSim():
while True:
turn = roll_first()
numTrials = 10
numThrows = 10000
totalThrows = numTrials*numThrows
game_on = True
winsA = 0
winsB = 0
while game_on:
for n in range(numTrials):
games = 0
for i in range(numThrows):
throw = rollDie()
if turn == 'A':
if throw == 6:
winsA += 1
games += 1
break
else:
turn = 'B'
else:
if throw == 6:
winsB += 1
games += 1
break
else:
turn = 'A'
return winsA/totalThrows
解决方案
您实际上只需要计算玩家 A 的获胜次数。由于您每次尝试玩 10000 场比赛,如果您知道 A 赢得的比赛次数,您就知道其他比赛肯定是 B 赢得的,并且 A+B=10000。
你似乎随机决定谁先轮,但任务规定应该始终是玩家 A 轮到第一轮。
您可以使用布尔值isPlayerA
来知道轮到谁了。从 开始,isPlayerA = True
然后用 切换它isPlayerA = not isPlayerA
。
以下是你如何编码它:
import random
def rollDie():
return random.choice([1,2,3,4,5,6])
def winFraction(): # Perform one trial of 10000 games and return fraction of wins for A
winsA = 0 # only count wins for A
for numTrow in range(10000):
isPlayerA = True # Player A always takes the first turn
throw = rollDie()
while throw != 6: # While the game is not over yet:
isPlayerA = not isPlayerA # Switch to the other player
throw = rollDie()
if isPlayerA:
winsA += 1 # Only count the wins for player A
return winsA/10000.0 # This is the fraction: we know the number of played games
def sim():
for trial in range(10): # Perform 10 trials
print(winFraction()) # Print the result of the trial
sim() # Start the simulation
推荐阅读
- c# - C# - 读取、编辑和保存 FixedLength 文件
- angular - 如何修复:ExtremeMap 操作符的 HTTP 请求仅工作一次
- spring-security - 如果 CORS 标头“Access-Control-Allow-Origin”为“*”,则不支持 SPRING-SECURITY 凭据
- sshj - 打开文件时出错:java.lang.ArrayIndexOutOfBoundsException:arraycopy:destination index -4 out of bounds for byte[256]
- java - Android离线模式(应用上线时同步数据)
- spacy - spaCy模型sm,md,lg之间的区别
- java - 为什么 netty FastThreadLocal 的基准测试结果并不比 ThreadLocal 快多少?
- python-3.x - 如何优化以下代码以使其运行更快?
- java - Azure 的 Key Vault 是否支持 PGP 密钥加密?
- django - Django 测试用例中的 IntegrityError