Python作业———预测球队比赛成绩
模拟乒乓球比赛
比赛规则:单打七局四胜,双打和团队采用五局三胜制。(团队赛采用五场三胜制:一、二、四、五场为单打,第三场为双打。单场采用三局两胜制)
代码:
1 from random import random 2 def printIntro(): 3 print("19信计2班10号模拟两只队伍A和B(个人、双人和团队)的乒乓球竞技比赛()") 4 print("程序运行需要A和B的综合能力值(以0到1之间的小数表示)") 5 6 def getInputsP(): #个人赛能力值输入 7 a = eval(input("请输入个人A的能力值(0-1): ")) 8 b = eval(input("请输入个人B的能力值(0-1): ")) 9 return a, b 10 def getInputsD(): #双打赛能力值输入 11 a = eval(input("请输入双打A的综合能力值(0-1): ")) 12 b = eval(input("请输入双打B的综合能力值(0-1): ")) 13 return a, b 14 15 16 def simNGames(probA, probB,n,m): # 进行N场比赛 17 WINSA,WINSB = 0,0 18 for i in range(n): 19 winsA, winsB = 0, 0 20 for j in range(m): #进行一次的比赛 21 scoreA, scoreB = simOneGame(probA, probB) 22 if scoreA > scoreB: 23 winsA += 1 24 else: 25 winsB += 1 26 if winsA > winsB: 27 WINSA += 1 28 else: 29 WINSB += 1 30 return WINSA, WINSB 31 32 def gameOver(a,b): 33 if a == 10 and b == 10: 34 return addgame(a,b) 35 else: 36 return a==11 or b==11 37 def addgame(a,b): 38 if abs(a-b) == 2: 39 return True 40 else: 41 return False 42 43 def simOneGame(probA, probB): #一局的比赛模拟 44 scoreA, scoreB = 0, 0 45 serving = "A" 46 while not gameOver(scoreA, scoreB): 47 if serving == "A": 48 if random() < probA: 49 scoreA += 1 50 else: 51 serving="B" 52 else: 53 if random() < probB: 54 scoreB += 1 55 else: 56 serving="A" 57 return scoreA, scoreB 58 59 60 61 def printSummary(WINSA, WINSB): 62 n = WINSA + WINSB 63 print("竞技分析开始,共模拟{}次比赛".format(n)) 64 print("A获胜{}场比赛,占比{:0.1%}".format(WINSA, WINSA/n)) 65 print("B获胜{}场比赛,占比{:0.1%}".format(WINSB, WINSB/n)) 66 67 def personGame(n,m): #个人赛 (n为模拟场次,m为一场进行局数) 68 probA,probB = getInputsP() 69 WINSA, WINSB = simNGames(probA, probB,n,m) 70 return WINSA,WINSB 71 72 73 def doubleGame(n,m): #双打 (n为模拟场次,m为一场进行局数) 74 probA,probB = getInputsD() 75 WINSA, WINSB = simNGames(probA, probB,n,m) 76 return WINSA,WINSB 77 78 79 def teamGame(n): 80 WINSA,WINSB = 0,0 81 print("第一场单打") 82 prA1,prB1 = getInputsP() 83 print("第二场单打") 84 prA2,prB2 = getInputsP() 85 print("第三场双打") 86 prA3,prB3 = getInputsD() 87 print("第四场单打") 88 prA4,prB4 = getInputsP() 89 print("第五场单打") 90 prA5,prB5 = getInputsP() 91 92 for i in range(n): 93 wiA1,wiB1 = simNGames(prA1,prB1,1,3) 94 wiA2,wiB2 = simNGames(prA2,prB2,1,3) 95 wiA3,wiB3 = simNGames(prA3,prB3,1,3) 96 wiA4,wiB4 = simNGames(prA4,prB4,1,3) 97 wiA5,wiB5 = simNGames(prA5,prB5,1,3) 98 if wiA1+wiA2+wiA3+wiA4+wiA5 > wiB1+wiB2+wiB3+wiB4+wiB5: 99 WINSA += 1 100 else: 101 WINSB += 1 102 103 return WINSA,WINSB 104 105 106 def main(): 107 printIntro() 108 chose = eval(input("请选择比赛类型(个人赛输入1,双打输入2,团队赛输入3):")) 109 n = eval(input("请输入模拟次数:")) 110 if chose == 1: 111 PA,PB = personGame(n,7) 112 printSummary(PA,PB) 113 elif chose == 2: 114 DA,DB = doubleGame(n,5) 115 printSummary(DA,DB) 116 else: 117 TA , TB = teamGame(n) 118 printSummary(TA,TB) 119 120 121 122 main()
运行结果:
用pyinstall库将程序封装
在控制台输入 —> pyinstaller -F D:\桌面\pytest\game.py
成功截图: