-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathrball.py
67 lines (59 loc) · 2.2 KB
/
rball.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from random import random
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)
def printIntro():
print("This program simulates a game of racquetball between two")
print('players called "A" and "B". The abilitites of each player is')
print("indicated by a probability (a number between 0 and 1) that")
print("reflects the likelihood of a player winning the serve.")
print("Player A has the first serve.")
def getInputs():
#Returns the three simulation parameters
a = eval(input("What is the prob. player A wins a serve? "))
b = eval(input("What is the prob. player B wins a serve? "))
n = eval(input("How many games to simulate? "))
return a, b, n
def simNGames(n, probA, probB):
#Simulates n games of racquetball between players whos
# abilities are represented by the probability of winning a serve.
#Returns number of wins for A and B
winsA = winsB = 0
for i in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
winsA = winsA + 1
else:
winsB = winsB + 1
return winsA, winsB
def simOneGame(probA, probB):
#Simulates a single game of racquetball between players whoe
# abilities are represented by the probability of winning a serveself.
#Returns final scores for A and B
serving = "A"
scoreA = 0
scoreB = 0
while not gameOver(scoreA, scoreB):
if serving == "A"
if random() < probA:
scoreA = scoreA + 1
else:
serving = "B"
elif serving == "B"
if random() < probB:
scoreB = scoreB + 1
else:
serving = "A"
return scoreA, scoreB
def gameOver(a, b):
#a and b represent scores for a racquetball game
#Returns True if the game is over, False otherwise
return a==15 or b==15
def printSummary(winsA, winsB, n):
# Prints a summary of wins for each players
print("\nGames simulated: ", n)
print("Wins for A: {0} ({1:0.1%})".format(winsA, winsA/n))
print("Wins for B: {0} ({1:0.1%})".format(winsB, winsB/n))
if __name__ == '__main__': main()