Created
November 24, 2020 12:20
-
-
Save vinimonteiro/4fbd62cef8166d8967553f54d5131a88 to your computer and use it in GitHub Desktop.
Monte Carlo Simulation in Basketball - Take the three or quick two, considering away from the ball foul
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
trials = 10000 | |
three_pc = 25 | |
two_pc = 60 | |
opp_two_pc = 65 | |
opp_ft_pc = 80 | |
opp_bad_ft_pc = 40 | |
time_to_shoot_two = 5 | |
time_to_foul = 5 | |
offense_rb_pc = 25 | |
ft_rb_pc = 15 | |
overtime_win_pc = 50 | |
bad_ft_shooter_with_ball = 50 | |
def sim_take_three(): | |
if three_pc >= random.randint(0, 100): | |
if overtime_win_pc >= random.randint(0, 100): | |
return True # Winning | |
return False # Either missed the three or lost in overtime | |
def sim_take_two(): | |
have_ball = True | |
points_down = 3 | |
time_left = 30 | |
while time_left > 0: | |
if have_ball: | |
# If down by 3 or more, make quick two. | |
# If down by 2 or less, run down the clock | |
if points_down >= 3: | |
time_left -= time_to_shoot_two | |
else: | |
time_left = 0 | |
if two_pc >= random.randint(0, 100): | |
points_down -= 2 | |
have_ball = False | |
else: | |
if offense_rb_pc >= random.randint(0, 100): | |
have_ball = False | |
else: | |
if points_down > 0: #Only if still losing that it tries to foul. Else, it just tries to contest the shot / NO foul | |
time_left -= time_to_foul | |
if bad_ft_shooter_with_ball >= random.randint(0,100): | |
if opp_bad_ft_pc >= random.randint(0,100): | |
points_down += 1 | |
if opp_bad_ft_pc >= random.randint(0,100): | |
points_down += 1 | |
have_ball = True | |
elif ft_rb_pc >= random.randint(0,100): | |
have_ball = True | |
else: | |
# RULE: one free throw and no option for rebound and the ball remains with winning team. | |
if opp_ft_pc >= random.randint(0,100): | |
points_down += 1 | |
else: #Else, it just tries to contest the shot / NO foul | |
if opp_two_pc >= random.randint(0,100): | |
points_down += 2 | |
time_left = 0 | |
if points_down > 0: | |
return False | |
elif points_down < 0: | |
return True | |
else: | |
if overtime_win_pc >= random.randint(0,100): | |
return True | |
else: | |
return False | |
def simulate(): | |
wins_taking_three = 0 | |
wins_taking_two = 0 | |
for trial in range(trials): | |
if sim_take_three(): | |
wins_taking_three+=1 | |
if sim_take_two(): | |
wins_taking_two+=1 | |
print(f'Wins taking the three: {wins_taking_three}') | |
print(f'Wins taking the two: {wins_taking_two}') | |
simulate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment