python模拟体育竞技

  • 一局比赛最低要求比赛双方都要达到15分,如果双方都达到15分,并且分差大于2分,可以认为一句比赛结束
  • 一次比赛三局两胜定胜负
    上代码:
from random import random


def printInfo():    
    print('This program simulates a game between two')
    print('There are two players, A and B')
    print('Probability(a number between 0 and 1)is used') 

 
def getInputs():   
    a = eval(input('What is the prob.player A wins? (0-1):'))
    b = eval(input('What is the prob.player B wins? (0-1):'))
    n = eval(input('How many games to simulate? :'))
    return a, b, n


def gameOver(a, b):
    if a >= 15 and b >= 15 and abs((a - b)) > 2:
        return True

    
def simOneGame(probA, probB):    
    scoreA, scoreB, winA, winB = 0, 0, 0, 0
    serving = 'A'        
    if winA < 2 and winB < 2:      
        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'
            return scoreA, scoreB
            
        if scoreA > scoreB:
            winA += 1
        else:
            winB += 1
    
    if winA == 2:
        return 1, 0
    else:
        return 0, 1
    
 
def simNGames(n, probA, probB):   
    winsA, winsB = 0, 0    
    for i in range(n):
        winA, winB = simOneGame(probA, probB)
        if winA > winB:
            winsA += 1
        else:
            winsB += 1
    return winsA, winsB

 
def printSummary(n , winsA, winsB):    
    print('Games simulated:{}'.format(n))
    print('wins for A:{}({:.2f}%)'.format(winsA, winsA / n * 100))
    print('wins for B:{}({:.2f}%)'.format(winsB, winsB / n * 100))


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

if __name__ == '__main__':
    main()
 

运行截图:
在这里插入图片描述
今天就到这里,拜拜。

发布了15 篇原创文章 · 获赞 12 · 访问量 222

猜你喜欢

转载自blog.csdn.net/weixin_45116096/article/details/105442955
今日推荐