预测球队比赛成绩

模拟乒乓球竞赛

1.乒乓球比赛规则:

(1)一局比赛:
在一局比赛中,先得11分的一方为胜方;10平后,先多得2分的一方为胜方。
(2)一场比赛:
单打的淘汰赛采用七局四胜制,双打淘汰赛和团体赛采用五局三胜制。

2.代码如下:

import random 
from math import *
def printIntro():#打印程序的介绍性信息
    print("模拟乒乓球竞赛")
    print("学号31")
    print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
    
 
def getInputs():#获得用户输入的参数
    a = eval(input("请输入选手A的能力值(0-1): "))
    b = eval(input("请输入选手B的能力值(0-1): "))
    h= eval(input("请输入一场要打几局:"))
    n = eval(input("模拟比赛的场次: "))
    return a, b, h,n
 
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))
def gameOver(scoreA, scoreB):
     g=scoreA-scoreB
     if (abs(g)==2 and  scoreA> 10 and scoreB> 10) or (g> 0 and scoreA==11) or (g<0 and scoreB==11):
        return scoreA,scoreB
        
    
def simOneGame(probA, probB,h):#模拟一场比赛
    for i in range(h): #模拟七局四胜或五局三胜为一场
        serving = "A"
        roundA =roundB=0  #分别为队伍A和B的赢得的比赛的局次
        scoreA, scoreB = 0, 0
        while not gameOver(scoreA, scoreB): #模拟一局比赛
            roundA=roundB=0
            if serving == "A":
                if random.random() < probA:
                    scoreA += 1             
                else:
                    serving = "B"
            else:
                if random.random() < probB:
                    scoreB += 1
              
                else:
                    serving = "A"
        if scoreA>scoreB:
            roundA += 1
        else:
            roundB += 1
    return roundA,roundB
    
 
def simNGames(n ,probA, probB,h):#利用A,B的的能力值模拟N场比赛
    winsA, winsB = 0, 0
    for i in range(n):
        roundA , roundB = simOneGame(probA, probB,h)
        if roundA >roundB:
            winsA += 1
        else:
            winsB += 1
    return winsA, winsB
 
def main():
    printIntro()
    probA, probB, h,n = getInputs()#分别为队伍A和B的能力值,一场的局数,比赛的场次
    winsA, winsB = simNGames(n, probA, probB,h)#分别为队伍A和B的赢得的比赛的场次
    printSummary(winsA, winsB)
    if h==7:
        print('此次模拟单打淘汰赛')
    else:
        print('此次模拟双打淘汰赛或者是团体淘汰赛')
main()

4.结果:

 

posted @ 2019-05-14 23:18    阅读(168)  评论(0编辑  收藏  举报