DEV Community

Cover image for Racquetball Win Simulation
Scott Gordon
Scott Gordon

Posted on • Edited on

1

Racquetball Win Simulation

Console Output

# racquetball.py
#   This program simulates the game of racquetball between two players
#   called "A" and "B". The ability of each player is indicated by a
#   probability (between 0 and 1) that the player wins the point when
#   serving. Player A always has the first move.
#   (Derived from: Python Programming an Introduction to Computer Science)
# by: Scott Gordon

from random import random


def main():
    print_intro()
    prob_a, prob_b, n = get_inputs()
    wins_a, wins_b = sim_n_games(n, prob_a, prob_b)
    print_summary(wins_a, wins_b)


def print_intro():
    print('''This program simulates a game of racquetball between two
        players called "A" and "B". The ability of each player is
        indicated by a probability (a number between 0 and 1) that
        the player wins the point when serving. Player A always has
        the first move.
        ''')


def get_inputs():
    a = float(input("What is the probability player A wins the serve? "))
    b = float(input("What is the probability player B wins the serve? "))
    n = int(input("How many games to simulate? "))
    return a, b, n


def sim_n_games(n, prob_a, prob_b):
    wins_a = wins_b = 0
    for i in range(n):
        score_a, score_b = sim_one_game(prob_a, prob_b)
        if score_a > score_b:
            wins_a = wins_a + 1
        else:
            wins_b = wins_b + 1
    return wins_a, wins_b


def sim_one_game(prob_a, prob_b):
    serving = "A"
    score_a = 0
    score_b = 0
    while not game_over(score_a, score_b):
        if serving == "A":
            if random() < prob_a:
                score_a += 1
            else:
                serving = "B"
        else:
            if random() < prob_b:
                score_b += 1
            else:
                serving = "A"
    return score_a, score_b


def game_over(a, b):
    # Return True if game is over False otherwise
    return a == 15 or b == 15


def print_summary(wins_a, wins_b):
    n = wins_a + wins_b
    print('\nGames simulated:', n)
    print(f'Wins for A: {wins_a} {wins_a/n:0.1%}')
    print(f'Wins for B: {wins_b} {wins_b/n:0.1%}')


if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Photo by Thomas Park on Unsplash

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay