Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # volleyball.py
- from random import random
- def printIntro():
- # Add code to complete the introduction, briefly explaining the two types
- # of game simulated. (See racquetball example, from pages 348-350.)
- print("This program simulates volleyball games between two")
- def getInputs():
- a = float(input("What is the prob. player A wins a serve? "))
- b = float(input("What is the prob. player B wins a serve? "))
- n = int(input("How many games to simulate? "))
- return a, b, n
- def normalGameOver(scoreA, scoreB):
- return scoreA == 25 or scoreB == 25
- def rallyGameOver(scoreA, scoreB):
- # Replace this with code to correctly determine whether the game is over;
- # return True if it is, False if it isn't.
- return (scoreA >= 15 and scoreA - scoreB >= 2) or (scoreB >= 15 and scoreB - scoreA >= 2)
- def simOneGame(probA, probB, scoring):
- #a different shorter way of achieving same result would be?:
- """
- if random()*probA > random()*probB:
- scoreA = scoreA + 1 # scoreA is higher than scoreB
- else:
- scoreB = scoreB + 1 # scoreB is the higher value
- """
- serving = "A"
- scoreA = 0
- scoreB = 0
- if scoring == "normal":
- while not normalGameOver(scoreA, scoreB):
- if serving == "A":
- if random() < probA:
- scoreA = scoreA + 1
- else:
- serving = "B"
- else: # B serving
- if random() < probB:
- scoreB = scoreB + 1
- else:
- serving = "A"
- else: # if scoring == "rally"
- while not rallyGameOver(scoreA, scoreB):
- if serving == "A":
- if random() < probA:
- scoreA = scoreA + 1
- else:
- serving = "B"
- else: # B serving
- if random() < probB:
- scoreB = scoreB + 1
- else:
- serving = "A"
- return scoreA, scoreB
- def simNGames(n, probA, probB, scoring):
- winsA = winsB = 0
- for i in range(n):
- scoreA, scoreB = simOneGame(probA, probB, scoring)
- if scoreA > scoreB:
- winsA = winsA + 1
- else: # (Tie not possible.)
- winsB = winsB + 1
- return winsA, winsB
- def printSummary(winsA, winsB):
- n = winsA + winsB
- print("\n Games simulated:", n)
- print(f" Wins for A: {winsA} ({(winsA / n):0.1%})")
- print(f" Wins for B: {winsB} ({(winsB / n):0.1%})")
- def main():
- printIntro()
- probA, probB, n = getInputs()
- print()
- print("Normal Scoring".center(30))
- print("-" * 30)
- winsA, winsB = simNGames(n, probA, probB, "normal")
- printSummary(winsA, winsB)
- print()
- print("Rally Scoring".center(30))
- print("-" * 30)
- winsA, winsB = simNGames(n, probA, probB, "rally")
- printSummary(winsA, winsB)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement