模拟体育竞技

一.体育竞技分析的IPO模式:

  输入I(input):两个球员的能力值,模拟比赛的次数(其中,运动员的能力值,可以通过发球方赢得本回合的概率来表示,

                一个能力值为0.8的球员,在他发球时,有80%的可能性赢得1分)

  处理P(process):模拟比赛过程

  输出O(output):两个球员获胜的概率


  自顶向下的设计是一种解决复杂问题的行之有效的方法。其步骤如下:

 

  

 

  自顶向下设计的基本思想,如下图:

 

 

 

二.模拟乒乓球的比赛

  比赛规则:再一局比赛中,先得11分的一方为胜方;10平后,先多得两分的一方为胜方

  单打赛程序如下:

函数名称 函数说明
printInfo() 打印程序的介绍信息
getInputs() 获得用户输入的参数
simNGames(n, probA, probB) 模拟n场比赛
simOneGame(probA, probB) 模拟一场比赛
GameOver(a,b) 定义一局比赛的结束条件
printSummary( winsA, winsB) 输出模拟比赛的结果

 

 

# -*- coding: utf-8 -*-
"""
Created on Mon May 13 11:13:38 2019

@author: lzz
"""

#e15.1MatchAnalysis.py
from random import random
def printIntro():
    print("这个程序模拟两个选手A和B的某种竞技比赛")
    print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
def getInputs():
    a = eval(input("请输入选手A的能力值(0-1): "))
    b = eval(input("请输入选手B的能力值(0-1): "))
    n = eval(input("模拟比赛的场次: "))
    return a, b, n
def simNGames(n, probA, probB):
    winsA, winsB = 0, 0
    for i in range(n):
        scoreA, scoreB = simOneGame(probA, probB)
        if scoreA > scoreB:
            winsA += 1
            print("第{}场胜利的为A".format(int(i/3)))
        else:
            winsB += 1
            print("第{}场胜利的为B".format(int(i/3)))
    return winsA, winsB
def gameOver(a,b):
        if a<10 or b<10:
            return a==11 or b==11
        if a>=10 or b>=10:
            if abs(a-b)==2:
                return True
            else:
                return False
def simOneGame(probA, probB):
    scoreA, scoreB = 0, 0
    serving = "A"
    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
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 main():
    printIntro()
    probA, probB, n = getInputs()
    winsA, winsB = simNGames(n, probA, probB)
    printSummary(winsA, winsB)
main()

 

 

 

1000局的结果如下:

 

 

三.运用 pyinstaller 打包该程序为可执行文件:

  安装pyinstaller库

 

pip install pyinstaller

 

 

 

 

 输入代码文件路径

 

 

打包成功

 

 

运行结果

 

posted @ 2019-05-13 11:25  落尘一缕沙  阅读(129)  评论(0编辑  收藏  举报