''' DS2000 Fall 2024 October 8, 2024 Starter code for class -- let's call a function we've never seen before. Given name, parameters, and return type we can call ANY function! Two functions to practice calling: - name: point_result - parameters: int for sum of dice rolls, 3 strings for w/l/d - returns: one of our three strings (w, l, or d) - name: generate_craps - parameters: int, number of times to roll two dice - returns: list of sums of two-dice rolls Examples of calling these functions: - outcome = point_result(7, "win", "lose", "draw") - lst = generate_craps(18) ''' import random import matplotlib.pyplot as plt WIN = "win!" LOSE = "lose:(" DRAW = "draw" def point_result(point, w, l, d): ''' Parameters: sum of two dice (int), called the "point", strings for w/l/d Returns: a string (win, lose, or draw) Does: determines whether the point wins, loses, or ties ''' if point == 7 or point == 11: return w elif point == 2 or point == 3 or point == 12: return l else: return d def generate_craps(num_rolls): ''' Parameters: number of times to roll two six-sided dice Returns: a list of ints (sums) Does: Rolls two 6-sided dice the given number of times and appends their sums to a list ''' sums = [] for i in range(num_rolls): roll1 = random.randint(1, 6) roll2 = random.randint(1, 6) sums.append(roll1 + roll2) return sums def main(): # part one: gather data by rolling two dice and seeing if we won the round roll1 = random.randint(1, 6) roll2 = random.randint(1, 6) sum_roll = roll1 + roll2 outcome = point_result(sum_roll, WIN, LOSE, DRAW) # sanity check print to see what happened print("rolls were", roll1, roll2) print("outcome was:", outcome) # Let's roll a bunch of times lst = generate_craps(18) # sanity-check our lst of sums print("Rolled two dice 18 times, and got these sums:", lst) # How many times did we win? winners = 0 for result in lst: outcome = point_result(result, WIN, LOSE, DRAW) if outcome == WIN: winners = winners + 1 print("I won the point", winners, "times") # FOR FUNSIES :) # Let's look at the first 7 outcomes (lucky in dice!) # This is called list slicing # lst[:x] goes from 0 to x-1, so the first x elements first_seven = lst[:7] print("first seven results:", first_seven) # Examples to see more plotting, could be helpful for hw3 :) # Put the sums in a bar plot, so we see each sum as the height of a bar # lst variable is the y values # we need to generate a list of x values, let's make them [0, 2, 4, ... x_pos = [] for i in range(len(lst)): x_pos.append(i * 2) plt.bar(x_pos, lst, color = "pink", width = 1.5) # Mess around with the xticks, with the same list of x-positions # and a new list of labels x_labels = [] for i in range(len(lst)): x_labels.append(i + 1) plt.xticks(x_pos, x_labels) # Finish off the plot with title and labels plt.title("Example bar plot with the sums of all dice rolls") plt.xlabel("Round Number") plt.ylabel("Sum of Two Dice") plt.show() main()