""" A craps simulation, along the lines of the material in Zelle's textook, chapter 9. Jim Mahoney and the Python programming class Oct 16 2008 GPL """ debugPrint = False def d6(n): """ Roll n 6-sided dice and return the sum. """ from random import randrange sum = 0 for i in range(n): sum = sum + randrange(1,7) return sum def test_die_roll(die, low, high, dice_count=1): """ Return true if rolls of die(1) are between low and high. >>> test_die_roll(d6, 1, 6) True >>> test_die_roll(d6, 2, 12, 2) True """ number_of_rolls = (high - low + 1) * 100 for i in range(number_of_rolls): roll = die(dice_count) if roll < low: return False if roll > high: return False return True def craps(): """ Simulate one game of craps. Return True for a win, False for a loss. """ first_roll = d6(2) if debugPrint: print "first roll : ", first_roll if first_roll in [7, 11]: return True elif first_roll in [2, 3, 12]: return False else: while True: next_roll = d6(2) if debugPrint: print "next roll : ", next_roll if next_roll == first_roll: return True elif next_roll == 7: return False def count_wins(n_games): """ Return number of wins when playing n_games of craps. """ wins = 0 for i in range(n_games): if craps(): wins = wins + 1 return wins def minmax_series(n_series, n_games): """ Return min and max found from count_wins(n_games) done n_series times. """ highest = 0 lowest = 2*n_games for i in range(n_series): n_wins = count_wins(n_games) if n_wins > highest: highest = n_wins if n_wins < lowest: lowest = n_wins return (lowest, highest) def main(): print "--- Estimated odds of winning at craps ---" n_games = input("How many games would you to simulate? ") print "Simulating %i games..." % n_games n_wins = count_wins(n_games) print "done." print "Number of simulated wins: %i" % n_wins print "Estimated odds of winning: %.2f" % (float(n_wins)/n_games) print print "--- Estimated error ---" n_series = input("How many times would you like to repeat that series of %i games? " % n_games) (lowest, highest) = minmax_series(n_series, n_games) low_odds = (float(lowest)/n_games) hi_odds = (float(highest)/n_games) print "Lowest estimated odds: %.2f" % low_odds print "Highest estimated odds: %.2f" % hi_odds print "Error range = (high - low) = %.4f " % (hi_odds - low_odds) if __name__ == "__main__": import doctest doctest.testmod() main()