-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPE4.py
68 lines (59 loc) · 2.15 KB
/
PE4.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
68
from random import random
# volleyball.py
# this time use rally scoring: both server or non-server get the score when win the rally
def main():
printlntro ()
probA, probB, n = getlnputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)
def printlntro():
print("This program simulates a game of volleyball between two")
print('teams called "A" and "B", using rally scoring. ')
print('The ability of each player is')
print("indicated by a probability (a number between 0 and 1) that")
print("the team wins the point when serving. Team A always")
print("has the first serve.")
def getlnputs():
# Returns the three simulation parameters
a = float(input("What is the prob. Team A wins a serve? "))
b = float(input("What is the prob. Team B wins a serve? "))
n = int(input("How many games to simulate? "))
return a, b, n
def simNGames(n, probA, probB):
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):
serving = "A"
scoreA = 0
scoreB = 0
while not gameOver(scoreA, scoreB):
if serving == "A" :
if random() < probA:
scoreA = scoreA + 1
else:
serving = "B"
scoreB = scoreB + 1
else:
if random() < probB:
scoreB = scoreB + 1
else:
serving = "A"
scoreA = scoreA + 1
return scoreA, scoreB
def gameOver(a, b):
# a and b represent scores for a volleyball game
# Returns True if the game is over, False otherwise.
return (a>= 25 or b>= 25) and ((a-b > 2) or (b-a > 2))
def printSummary(winsA, winsB):
# Prints a summary of wins for each team, using two scoring system
n = winsA + winsB
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))
main()