from random import random
def printInfo():
print(114)
print('This program simulates a game between two')
print('There are two players, A and B')
print('Probability(a number between 0 and 1)is used')
def getInputs():
a = eval(input('What is the prob.player A wins? (0-1):'))
b = eval(input('What is the prob.player B wins? (0-1):'))
n = eval(input('How many games to simulate? :'))
return a, b, n
def gameOver(a, b):
if a >= 15 and b >= 15 and abs((a - b)) > 2:
return True
def simOneGame(probA, probB):
scoreA, scoreB, winA, winB = 0, 0, 0, 0
serving = 'A'
if winA < 2 and winB < 2:
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
if scoreA > scoreB:
winA += 1
else:
winB += 1
if winA == 2:
return 1, 0
else:
return 0, 1
def simNGames(n, probA, probB):
winsA, winsB = 0, 0
for i in range(n):
winA, winB = simOneGame(probA, probB)
if winA > winB:
winsA += 1
else:
winsB += 1
return winsA, winsB
def printSummary(n , winsA, winsB):
print('Games simulated:{}'.format(n))
print('wins for A:{}({:.2f}%)'.format(winsA, winsA / n * 100))
print('wins for B:{}({:.2f}%)'.format(winsB, winsB / n * 100))
def main():
printInfo()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(n, winsA, winsB)
if __name__ == '__main__':
main()