标签:turn random lse ima one 技术 开始 结果 game
from random import *
#定义一个Info类,功能是打印介绍性信息,并且获得用户输入的两队伍能力值,模拟场次
class Info:
def __init__(self):
print(‘这个程序是模拟两支队伍A和B的排球比赛‘)
print(‘程序运行需要A和B的能力值(以0到1之间的小数表示)‘)
def GetInput(self):
A = eval(input(‘请输入队伍A的能力值(0-1):‘))
B = eval(input(‘请输入队伍B的能力值(0-1):‘))
N = eval(input(‘模拟比赛场次:‘))
return A, B, N
#定义了一个OneGame类,功能是用来完成一场5局3胜制的比赛
class OneGame:
def simOneGame(self, probA, probB):
A_win, B_win, count = 0, 0, 1
while not (A_win == 3 or B_win == 3):
serving = choice([‘A‘, ‘B‘]) #这里我选择的是随机开球方
scoreA, scoreB = 0, 0
while not OneGame.Gameover(count, scoreA, scoreB):
if serving == ‘A‘:
if random() < probA:
scoreA += 1
else:
serving = ‘B‘
else:
if random() < probB:
scoreB += 1
else:
serving = ‘A‘
if scoreA > scoreB :
A_win += 1
else:
B_win += 1
if count == 5:
count = 1
count += 1
return A_win, B_win
@classmethod
def Gameover(self, count, scoreA, scoreB): #这个函数是用来判断比赛是否结束
if count < 5:
return (scoreA >= 25 or scoreB >= 25) and abs(scoreA - scoreB) >= 2
else:
return (scoreA >= 15 or scoreB >= 15) and abs(scoreA - scoreB) >= 2
#定义了一个NGame类,继承了OneGame的属性和方法,功能是完成N场5局3胜制比赛
class NGame(OneGame):
def simNGames(self, n, A, B):
winsA, winsB = 0, 0
for i in range(n):
win_numA, win_numB = self.simOneGame(A, B)
if win_numA > win_numB:
winsA += 1
else:
winsB += 1
return winsA, winsB
#定义了一个PrintSummary类,功能是打印比赛结果
class PrintSummary:
def __init__(self, N, winA, winB):
print(‘竞技分析开始,共模拟{}场比赛‘.format(N))
print(‘队伍A获胜{}场比赛,占比{:.2f}%‘.format(winA, winA/N * 100))
print(‘队伍B获胜{}场比赛,占比{:.2f}%‘.format(winB, winB/N * 100))
def main():
match_info = Info() #创建一个Info对象
A, B, N = match_info.GetInput() #使用Info类的GetInput方法获得能力值和场次
match = NGame() #创建一个NGame对象
A_win, B_win = match.simNGames(N, A, B) #获得A, B两队获胜的比赛场数
PrintSummary(N, A_win, B_win) #打印比赛结果
input("please input any key to exit!")
main()

标签:turn random lse ima one 技术 开始 结果 game
原文地址:https://www.cnblogs.com/hshjdkdmdklflcll/p/14021750.html