采用乒乓球规则模拟比赛(python)

假设乒乓球的规则有:

①乒乓球规则是一局比赛中先得 11 分为胜,10 平时,先得 2 分为胜

②一场比赛采用三局两胜,当每人各赢一局时,最后一局为决胜局

代码两次运行结果参考如下,因随机因素所以结果不尽相同。
采用乒乓球规则模拟比赛(python)_第1张图片
采用乒乓球规则模拟比赛(python)_第2张图片
代码如下:

from random import random

def printTntro():
    print("模拟比赛")
    print("需要A和B的能力值(以0到1之间的小数表示)")
def getInputs():
    a = eval(input("请输入A的能力值(0-1):"))
    b = eval(input("请输入B的能力值(0-1):"))
    return a,b

def printSummary(winsA,winsB):
    if winsA==2:
        print("A获胜")
    else:
        print("B获胜")

def gameOver(a,b):
    return a==11 or b==11

def simOneGame(probA,probB):
    scoreA,scoreB = 0,0
    s1,s2 = 0,0
    serving = 'A'
    while not gameOver(scoreA,scoreB):
        if scoreB==scoreA and scoreA==10:
            while not s1==2 or s2==2:
                if serving == 'A':
                    if random()<probA:
                        s1+= 1
                    else:
                        serving = 'B'
                else:
                    if random()<probB:
                        s2 += 1
                    else:
                        serving='A'
         	 break
        if serving == 'A':
            if random()<probA:
                scoreA += 1
            else:
                serving = 'B'
        else:
            if random()<probB:
                scoreB += 1
            else:
                serving='A'
    if s1==2:
        s2=0
    else:
        s1=0
    return scoreA+s1,scoreB+s2

def simNGames(probA,probB):
    winsA,winsB = 0,0
    for i in range(3):
        scoreA,scoreB = simOneGame(probA,probB)
        print("第{}局".format(i+1))
        print("{} --- {}".format(scoreA,scoreB))
        if scoreA>scoreB:
            winsA += 1
            if winsA==2:
                break
        else:
            winsB += 1
            if winsB==2:
                break
    return winsA,winsB

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


你可能感兴趣的:(采用乒乓球规则模拟比赛(python))