模拟体育竞技乒乓球

from random import random
def printIntro():
    print("这个程序模拟两个选手A和B的兵乓球比赛")
    print("程序运行需要A和B选手的能力值(以0到1之间的小数表示)")
def getInput():
    probA=eval(input("请输入选手A的能力值(0-1):"))
    probB=eval(input("请输入选手B的能力值(0-1):"))
    n=eval(input("模拟比赛场次:"))
    return probA,probB,n
def simGames(n,probA,probB):     #比赛双方各自胜利的场次数
    winsA,winsB=0,0
    for i in range (n):
        c=simGame(probA,probB)
        if c=='A':
           winsA+=1
        else:
               winsB+=1
    return winsA,winsB
def simGame(probA,probB):         #判断一场比赛的胜方
    winsA1,winsB1=0,0
    for i in range(7):
        scoreA,scoreB=simoneGame(probA,probB)
        if scoreA>scoreB:
             winsA1+=1
        else:
             winsB1+=1      
        if winsA1>=4:
           return 'A'
           return 'B'
def simoneGame(probA,probB):     #统计一场比赛下来的各自得分数
    scoreA,scoreB=0,0
    serving="A"
    while not gameOver(scoreA,scoreB):
         x=random()
         if serving=="A":
            if x < probA:
                 scoreA+=1
            else:
                 serving="B"
         else:
            if x < probB:
                 scoreB+=1
            else:
                 serving="A"
    return scoreA,scoreB
def gameOver(a,b):            
    if (a>=11 and b<11) or (b>=11 and a<11) or (a>9 and b>9 and ((a-b)>=2 or (b-a)>=2)):
        return True
    return False
def printsummary(winsA,winsB):
     n=winsA+winsB
     print("竞技开始分析,共模拟了{}场比赛".format(n))
     print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA,winsA/n))
     print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB,winsB/n))
     print("分析人:Yong No.2")
def main():
    printIntro()
    probA,probB,n=getInput()
    winsA,winsB=simGames(n,probA,probB)
    printsummary(winsA,winsB)
main()

  

 

posted @ 2020-11-16 20:05  dt_1005  阅读(86)  评论(0)    收藏  举报