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()
 

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

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值