编程语言
首页 > 编程语言> > 2019-05-12 Python之模拟体育竞赛

2019-05-12 Python之模拟体育竞赛

作者:互联网

from random import random

def printIntro():
    print("这个程序模拟两个选手A和B的某种竞技比赛")
    print("程序运行需要A和B的能力值(以0到1之间的小数表示)")


def getInputs():
    #获取数据

    a = 0.45
    b = 0.5
    n = 5
    '''
    a = eval(input("请输入a选手的能力值:"))
    b = eval(input("请输入b选手的能力值:"))
    n = eval(input("模拟比赛场次:"))
'''
    return a,b,n

def simNGames(n,probA,probB):
    print("竞技分析开始,共模拟{}场比赛".format(n))
    winsA, winsB = 0,0
    for i in range(1, int(n/2)+2): #n为比赛场数
        scoreA, scoreB=simOneGame(int(n/2)+1, probA, probB) #模拟比赛过程
        print("第{}场比赛得分情况,A:{},B:{}".format(i, scoreA, scoreB))
        if scoreA>scoreB:
            winsA+=1
        else:
            winsB+=1
    return winsA, winsB

def gameover(a, b):
    return a==25 or b==25 and (a>=b-2 or b>=a-2)   #单场比赛结束条件

def last_gameover(a, b):
    return a == 15 or b == 15 and (a >= b - 2 or b >= a - 2)

def simOneGame(i, probA, probB): #单场比赛过程
    scoreA, scoreB = 0,0
    serving = 'A'
    global k
    k += 1
    if k!=i: #不是最终局
        while not gameover(scoreA, scoreB): #如果未达到单场结束条件
            if serving == 'A':
                if random()<probA:
                    scoreA += 1
                else:
                    serving='B'
            else:
                if random()<probB:
                    scoreB += 1
                else:
                    serving='A'
    else:
        while not last_gameover(scoreA, scoreB):
            if serving == 'A':
                if random()<probA:
                    scoreA += 1
                else:
                    serving='B'
            else:
                if random()<probB:
                    scoreB += 1
                else:
                    serving='A'
    return scoreA, scoreB

def printSummary(winsA, winsB):
    n = winsA + winsB

    print("选手A获胜{}场比赛,占比例{:0.2%}".format(winsA, winsA/n))
    print("选手B获胜{}场比赛,占比例{:0.2%}".format(winsB, winsB/n))

def main():
    printIntro()
    probA, probB, n = getInputs()
    winsA, winsB = simNGames(n, probA, probB)
    printSummary(winsA, winsB)

k = 0
main()

 

标签:12,return,scoreA,scoreB,05,Python,print,def,比赛
来源: https://www.cnblogs.com/ymzm204/p/10853842.html