python——体育竞技
一、体育竞技分析
基本规则
两个球员,交替用球拍击球
发球权,回合
未能进行一次击打回合结束
首先达到15分赢得比赛
1、自顶向下的设计
1 #7_game_2.py 2 from random import * 3 4 def main(): 5 printIntro()#介绍程序信息 6 probA,probB,n = getInputs()#输入参数 7 winsA, winsB = simNGames(n,probA,probB)#获胜场数 8 PrintSummary(winsA, winsB) 9 10 def printIntro(): 11 print('This program simulates a game between two') 12 print('There are two players, A and B') 13 print('Probability(a number between 0 and 1)is used') 14 15 def getInputs(): 16 a = eval(input('What is the prob.player A wins?'))#eval()将str转换为数字型 17 b = eval(input('What is the prob.player B wins?')) 18 n = eval(input('How many games to simulate?')) 19 return a,b,n 20 21 def simNGames(n,probA,probB): 22 winsA = 0 23 winsB = 0 24 for i in range(n): 25 scoreA,scoreB = simOneGame(probA,probB)#得分情况 26 if scoreA >scoreB: 27 winsA = winsA + 1 28 else: 29 winsB = winsB + 1 30 return winsA,winsB 31 def simOneGame(probA,probB): 32 scoreA = 0 33 scoreB = 0 34 serving = "A"#开始循环的初始标志 35 while not gameOver(scoreA,scoreB): 36 if serving == "A": 37 if random() < probA: 38 scoreA = scoreA + 1 39 else: 40 serving = "B" 41 else: 42 if random() < probB: 43 scoreB = scoreB + 1 44 else: 45 serving = "A" 46 return scoreA,scoreB 47 48 def gameOver(a,b):#循环结束的标志 49 return a==15 or b==15 50 51 def PrintSummary(winsA, winsB): 52 n = winsA + winsB 53 print('\nGames simulated:%d'%n) 54 print('Wins for A:{0}({1:0.1%})'.format(winsA,winsA/n)) 55 print('Wins for B:{0}({1:0.1%})'.format(winsB,winsB/n)) 56 57 if __name__ == '__main__': 58 main()
载入程序,对各个函数分别测试
整个过程反映了,由顶至下的设计和由下至上的运行,整个编程的思路就是这样。
(2)程序简化
1 import random 2 3 def onegame(probA,probB): 4 scoreA=0 5 scoreB=0 6 mark="A" 7 while mark=="A": 8 a=random.random() 9 b=random.random() 10 a=a*probA 11 b=b*probB 12 if a>b: 13 scoreA+=1 14 else: 15 scoreB+=1 16 if scoreA==15 or scoreB==15: 17 mark="B" 18 return scoreA,scoreB 19 20 def Ngame(n,probA,probB): 21 numA=0 22 numB=0 23 for i in range(n): 24 scoreA,scoreB=onegame(probA,probB) 25 if scoreA>scoreB: 26 numA+=1 27 else: 28 numB+=1 29 return numA,numB 30 31 32 33 def main(): 34 probA=eval(input("probA is :")) 35 probB=eval(input("probB is :")) 36 n=eval(input("num is :")) 37 38 numA,numB=Ngame(n,probA,probB) 39 print('Games simulated:%d'%n) 40 print('Wins for A:{0}({1:0.1%})'.format(numA,numA/n)) 41 print('Wins for B:{0}({1:0.1%})'.format(numB,numB/n)) 42 43 if __name__ == "__main__": 44 main()