""" craps.py Simulate games of craps and give the probability of winning. 1. Ask how many games. 2. Do the simulation. 3. Print how many times won and average. in class project on Oct 24 2019 """ from random import randint from sys import exit DEBUG = False def debug_print(message): if DEBUG: print(message) def roll_die(sides=6): """ Return result from rolling one die >>> roll_die() in (1, 2, 3, 4, 5, 6) True """ return randint(1, sides) def two_dice(): """ Return the sum of two six sided dice >>> two_dice() in range(2, 13) # i.e. 2 through 12 True """ return roll_die() + roll_die() def win_craps(): """ Return True if we win this simulated game of craps """ first_roll = two_dice() debug_print("First roll is {}".format(first_roll)) if first_roll in (2, 3, 12): return False elif first_roll in (7, 11): return True else: while True: next_roll = two_dice() if next_roll == first_roll: return True elif next_roll == 7: return False else: debug_print("keep rolling ...") def count_wins(n_games): """ Return number of wins out of n_games played """ wins = 0 for i in range(n_games): if win_craps(): wins = wins + 1 return wins def get_n_games(): """ Ask user for number of games and return it """ while True: try: n = int(input("How many games? (^d to exit) ")) if n > 0: return n except ValueError: print("That isn't a positive number. Try again.") except EOFError: print("\nBye ...") exit() def main(): print("-- Compute winning probability for craps --") n_games = get_n_games() n_wins = count_wins(n_games) # Looked up "python format decimal" and used an answer from StackOverflow : # stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points print("You won {} games out of {} which is an average of {:.4f}".format( n_wins, n_games, n_wins/n_games)) if __name__ == '__main__': import doctest doctest.testmod() main()