1 #羽毛球比赛预测 2 from random import random 3 def printTips(): 4 print("本人学号:2019310143143") 5 print("这个程序模拟两轮乒乓球单打比赛,第二轮为晋级赛") 6 print("每轮比赛均采取七局四胜制") 7 print("程序运行需要每位参赛选手的能力值(以0到1之间的小数表示)") 8 def getInputs(): 9 a = eval(input("请输入选手A的能力值(0-1): ")) 10 b = eval(input("请输入选手B的能力值(0-1): ")) 11 c = eval(input("请输入选手C的能力值(0-1): ")) 12 d = eval(input("请输入选手D的能力值(0-1): ")) 13 return a,b,c,d 14 def ModelNGames(powerA, powerB): #一场比赛七局四胜 15 winsA, winsB = 0, 0 16 for i in range(7): 17 scoreA, scoreB = ModelOneGame(powerA, powerB) 18 if scoreA > scoreB: 19 winsA += 1 20 else: 21 winsB += 1 22 return winsA, winsB 23 def gameOver(a,b): #一局比赛胜利的判断 24 if a>10 or b>10: 25 if abs(a-b)>1: 26 return True 27 else: 28 return False 29 def judge(winsA,winsB): #一场比赛胜利的判断 30 if winsA>=4 or winsB>=4: 31 return True 32 else: 33 return False 34 def ModelOneGame(powerA, powerB):#一局比赛 35 scoreA, scoreB = 0, 0 36 serving = "A" 37 while not gameOver(scoreA, scoreB): 38 if serving == "A": 39 if random() < powerA: 40 scoreA += 1 41 else: 42 serving="B" 43 else: 44 if random() < powerB: 45 scoreB += 1 46 else: 47 serving="A" 48 return scoreA, scoreB 49 def printResult1(winsA, winsB):#第一轮第一场的结果 50 if winsA > winsB: 51 print("A和B比分是{}:{},选手A获胜,晋级成功".format(winsA, winsB)) 52 else: 53 print("A和B比分是{}:{},选手B获胜,晋级成功".format(winsA, winsB)) 54 def printResult2(winsA, winsB):#第一轮第二场的结果 55 if winsA > winsB: 56 print("C和D比分是{}:{},选手C获胜,晋级成功".format(winsA, winsB)) 57 else: 58 print("C和D比分是{}:{},选手D获胜,晋级成功".format(winsA, winsB)) 59 def printResult3(winsE,winsF,winner):#输出二轮结果 60 if winsE > winsF: 61 print("比分是{}:{},选手{}获得冠军".format(winsE,winsF,winner)) 62 else: 63 print("比分是{}:{},选手{}获得冠军".format(winsE,winsF,winner)) 64 def main(): 65 printTips() 66 powerA, powerB,powerC,powerD= getInputs() 67 winsA, winsB = ModelNGames(powerA, powerB) 68 printResult1(winsA, winsB) 69 winsC,winsD=ModelNGames(powerC,powerD) 70 printResult2(winsC,winsD) 71 E=max(winsA,winsB) 72 F=max(winsC,winsD) 73 powerE,powerF=0,0 74 if E==winsA and F==winsC:#找到晋级的两个人的能力值 75 powerE=powerA 76 powerF=powerC 77 elif E==winsB and F==winsC: 78 powerE=powerB 79 powerF=powerC 80 elif E==winsA and F==winsD: 81 powerE=powerA 82 powerF=powerD 83 elif E==winsB and F==winsD: 84 powerE=powerB 85 powerF=powerD 86 winsE,winsF=ModelNGames(powerE,powerF) 87 if winsE>winsF: #找到冠军 88 if powerE==powerA: 89 winner='A' 90 else : 91 winner='B' 92 else : 93 if powerF==powerC: 94 winner='C' 95 else : 96 winner='D' 97 printResult3(winsE,winsF,winner) 98 main()
注:这段代码只适合两场(A和B,C和D)双人单打的晋级赛,可以判断冠军。