by **ceeilly32** » Sun Nov 17, 2013 2:06 am

I am trying to simulate games and print the results of how many serves each 4 player served, and also I changed the winning rule for each game so that if the difference between scores of the teams is more than 5 then the leading team wins that particular game. I believe I did that correctly, but I am unsure. Also, I am trying to show the progress of my program with animation later and I am having trouble finding a function that does that. May you guys help a new beginning programmer? I am kind of lost about what I should do. Thanks!

- Code: Select all
`from random import random`

from random import randrange

def gameOver(a, b):

if(a > 5 or b > 5):

return 1

else:

return 0

def simOneGame(probA_1, probA_2, probB_1, probB_2):

choose_serve = randrange(1,5)

if(choose_serve == 1):

serving = "A_1"

elif(choose_serve == 2):

serving = "A_2"

elif(choose_serve == 3):

serving = "A_3"

else:

serving = "A_4"

scoreA = 0

scoreB = 0

while not gameOver(scoreA, scoreB):

if serving == "A_1":

if random() < probA_1:

scoreA = scoreA + 1

else:

serving = "B_1" or "B_2"

elif serving == "A_2":

if random() < probA_2:

scoreA = scoreA + 1

else:

serving = "B_1" or "B_2"

elif serving == "B_1":

if random() < probB_1:

scoreB = scoreB + 1

else:

serving = "A_1" or "A_2"

else:

if random() < probB_2:

scoreB = scoreB + 1

else:

serving = "A_1" or "A_2"

return scoreA, scoreB

def simNGames(n, probA_1, probA_2, probB_1, probB_2):

winsA = winsB = 0

for i in range(n):

scoreA, scoreB = simOneGame(probA_1, probA_2, probB_1, probB_2)

if scoreA > scoreB:

winsA = winsA + 1

else:

winsB = winsB + 1

return winsA, winsB

def printSummary(winsA, winsB):

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))

def getInputs():

a_1 = eval(input("What is the prob. player A_1 wins a serve? "))

a_2 = eval(input("What is the prob. player A_2 wins a serve? "))

b_1 = eval(input("What is the prob. player B_1 wins a serve? "))

b_2 = eval(input("What is the prob. player B_2 wins a serve? "))

n = eval(input("How many games to simulate? "))

return a_1, a_2, b_1, b_2, n

def printIntro():

print("This program simulates a game of racquetball between four")

print('players called "A_1", "A_2", "B_1", and "B_1", repsectively. The abilities of each player is')

print("indicated by a probability (a number between 0 and 1) that")

print("the player wins the point when serving. Player A always")

print("has the first serve.")

def main():

printIntro()

probA_1, probA_2, probB_1, probB_2, n = getInputs()

winsA, winsB = simNGames(n, probA_1, probA_2, probB_1, probB_2)

printSummary(winsA, winsB)

main()

Last edited by

Yoriz on Sun Nov 17, 2013 2:14 am, edited 1 time in total.

**Reason:** *First post lock*