def test_26_play_hand_simple_strategy_2(self): random.seed(5) correct_return = 2.0 deck = CardDecks(8, BlackJackCard) amount_bet, player_return = play_hand(deck, BlackJackHand.simple_strategy) self.assertTrue(is_within_epsilon(correct_return, player_return, 0.0001), 'Return from play_hand is not correct with simple strategy.')
def test_16_doubledown_strategy_3(self): # player == 11 player_cards = [BlackJackCard('2', 'C'), BlackJackCard('9', 'H')] dealer_cards = [BlackJackCard('3', 'S'), BlackJackCard('J', 'C')] deck = CardDecks(2, BlackJackCard) hand = BlackJackHand(deck) hand.set_initial_cards(player_cards, dealer_cards) self.assertEqual(hand.doubledown_strategy(), BlackJackHand.doubledown, doubledown_error_message % ( hand.doubledown_strategy(), get_printable_cards(player_cards), get_printable_cards(dealer_cards), BlackJackHand.doubledown)) # make sure the bet doubles when doubling down cards_to_deal = [BlackJackCard('9', 'D'), BlackJackCard('9', 'S'), *dealer_cards, *player_cards] mockdeck = MockCardDecks(4, BlackJackCard, cards_to_deal) hand = BlackJackHand(mockdeck, initial_bet=2.0) hand.set_initial_cards(player_cards, dealer_cards) initial_bet = hand.get_bet() self.assertEqual(initial_bet, 2.0, "Inaccurate initial bet, found %s, expected %s" % (initial_bet, 2.0)) def strategy(hand): if hand.deck.num_cards_left() == 2: return BlackJackHand.doubledown # trigger play_player_turn to double the bet else: return BlackJackHand.stand hand.play_player_turn(strategy) new_bet = hand.get_bet() self.assertEqual(new_bet, 4.0, "Your doubledown strategy did not double the current bet to %s, found %s" % (4.0, new_bet))
def test_23_play_hand_peek_strategy_1(self): random.seed(3) correct_return = 0 deck = CardDecks(1, BlackJackCard) amount_bet, player_return = play_hand(deck, BlackJackHand.peek_strategy) self.assertTrue(is_within_epsilon(correct_return, player_return, 0.0001), 'Return from play_hand is not correct with peek strategy.')
def run_simulation(strategy, bet=2.0, num_decks=8, num_hands=20, num_trials=100, show_plot=False): """ Runs a simulation and generates a box plot reflecting the distribution of player's rates of return across all trials. The box plot displays the distribution of data based on the five number summary: minimum, first quartile, median, third quartile, and maximum. We also want to show the average on the box plot. You can do this by specifying another parameter: plt.boxplot(results, showmeans=True) For each trial: - instantiate a new CardDeck with the num_decks and type BlackJackCard - for each hand in the trial, call play_hand and keep track of how much money the player receives across all the hands in the trial - calculate the player's rate of return, which is 100*(total money received-total money bet)/(total money bet) Parameters: strategy - function, one of the the 3 playing strategies defined in BlackJackHand (e.g. BlackJackHand.mimic_dealer_strategy) bet - float, the amount that the player bets each hand. (default=2) num_decks - int, the number of standard card decks in the CardDeck. (default=8) num_hands - int, the number of hands the player plays in each trial. (default=20) num_trials - int, the total number of trials in the simulation. (default=100) show_plot - bool, True if the plot should be displayed, False otherwise. (default=False) Returns: tuple, containing the following 3 elements: - list of the player's rate of return for each trial - float, the average rate of return across all the trials - float, the standard deviation of rates of return across all trials """ returnRate = [] #for each trial create a new deck and a counter for money bet and won for trial in range(num_trials): deck = CardDecks(num_decks,BlackJackCard) totalBet = 0.0 totalWon = 0.0 #play each hand and update the money counters for n in range(num_hands): totalBet += bet totalWon += play_hand(deck,strategy,bet) #add the rate of return to the list returnRate.append(100*(totalWon-totalBet)/totalBet) #create boxplot if show_plot: plt.figure() plt.boxplot(returnRate,showmeans=True) plt.title('Player ROI on Playing '+str(num_hands)+' Hands ('+strategy.__name__+')\n(Mean = '\ +str(sum(returnRate)/num_trials)+', SD = '+str(np.std(returnRate))+')') plt.ylabel('% Return') plt.xticks([]) return (returnRate,sum(returnRate)/num_trials,np.std(returnRate))
def test_28_play_hand_doubledown_strategy_2(self): random.seed(7) correct_return = 0.0 #@TODO give a mock deck to see return be 4x initial bet deck = CardDecks(8, BlackJackCard) amount_bet, player_return = play_hand(deck, BlackJackHand.doubledown_strategy) self.assertTrue(is_within_epsilon(correct_return, player_return, 0.0001), 'Return from doubledown strategy actual (%f) differs from expected (%f) too much' % (player_return, correct_return))
def test_27_play_hand_doubledown_strategy_1(self): random.seed(6) correct_return = 1.0 deck = CardDecks(8, BlackJackCard) amount_bet, player_return = play_hand(deck, BlackJackHand.doubledown_strategy) self.assertTrue(is_within_epsilon(correct_return, player_return, 0.0001), 'Return from doubledown strategy actual (%f) differs from expected (%f) too much' % (player_return, correct_return))
def test_15_doubledown_strategy_2(self): # player > 11 (has 17) player_cards = [BlackJackCard('9', 'C'), BlackJackCard('8', 'D')] dealer_cards = [BlackJackCard('3', 'S'), BlackJackCard('J', 'C')] deck = CardDecks(2, BlackJackCard) hand = BlackJackHand(deck, initial_bet=2.0) hand.set_initial_cards(player_cards, dealer_cards) self.assertEqual(hand.doubledown_strategy(), BlackJackHand.stand, doubledown_error_message % ( hand.doubledown_strategy(), get_printable_cards(player_cards), get_printable_cards(dealer_cards), BlackJackHand.stand))
def test_13_simple_strategy_2(self): # player == 17 player_cards = [BlackJackCard('7', 'C'), BlackJackCard('A', 'C')] dealer_cards = [BlackJackCard('3', 'S'), BlackJackCard('J', 'C')] deck = CardDecks(2, BlackJackCard) hand = BlackJackHand(deck) hand.set_initial_cards(player_cards, dealer_cards) self.assertEqual(hand.simple_strategy(), BlackJackHand.stand, simple_error_message % ( hand.simple_strategy(), get_printable_cards(player_cards), get_printable_cards(dealer_cards), BlackJackHand.stand))
def test_11_peek_strategy_3(self): # player > dealer, stand player_cards = [BlackJackCard('9', 'C'), BlackJackCard('A', 'C')] dealer_cards = [BlackJackCard('3', 'S'), BlackJackCard('J', 'C')] deck = CardDecks(2, BlackJackCard) hand = BlackJackHand(deck) hand.set_initial_cards(player_cards, dealer_cards) self.assertEqual(hand.peek_strategy(), BlackJackHand.stand, peek_error_message % ( hand.peek_strategy(), get_printable_cards(player_cards), get_printable_cards(dealer_cards), BlackJackHand.stand))
def test_09_peek_strategy_1(self): # player < dealer, hit player_cards = [BlackJackCard('9', 'C'), BlackJackCard('K', 'C')] dealer_cards = [BlackJackCard('K', 'S'), BlackJackCard('J', 'C')] deck = CardDecks(2, BlackJackCard) hand = BlackJackHand(deck) hand.set_initial_cards(player_cards, dealer_cards) self.assertEqual(hand.peek_strategy(), BlackJackHand.hit, peek_error_message % ( hand.peek_strategy(), get_printable_cards(player_cards), get_printable_cards(dealer_cards), BlackJackHand.hit))
def test_08_mimic_dealer_strategy_2(self): # 17, stand player_cards = [BlackJackCard('7', 'C'), BlackJackCard('K', 'C')] dealer_cards = [BlackJackCard('6', 'C'), BlackJackCard('3', 'C')] deck = CardDecks(2, BlackJackCard) hand = BlackJackHand(deck) hand.set_initial_cards(player_cards, dealer_cards) self.assertEqual(hand.mimic_dealer_strategy(), BlackJackHand.stand, dealer_error_message % ( hand.mimic_dealer_strategy(), get_printable_cards(player_cards), get_printable_cards(dealer_cards), BlackJackHand.stand))
def test_07_mimic_dealer_strategy_1(self): # less than 17, hit player_cards = [BlackJackCard('5', 'C'), BlackJackCard('K', 'C')] dealer_cards = [BlackJackCard('6', 'C'), BlackJackCard('3', 'C')] deck = CardDecks(2, BlackJackCard) hand = BlackJackHand(deck) hand.set_initial_cards(player_cards, dealer_cards) self.assertEqual(hand.mimic_dealer_strategy(), BlackJackHand.hit, dealer_error_message % ( hand.mimic_dealer_strategy(), get_printable_cards(player_cards), get_printable_cards(dealer_cards), BlackJackHand.hit))
def run_simulation(strategy, initial_bet=2.0, num_decks=8, num_hands=20, num_trials=4000, show_plot=False): """ Runs a simulation and generates a normal distribution reflecting the distribution of player's rates of return across all trials. The normal distribution is based on the mean and standard deviation of the player's rates of return across all trials. You should also plot the histogram of player's rates of return that underlies the normal distribution. For hints on how to do this, consider looking at matplotlib.pyplot scipy.stats.norm.pdf For each trial: - instantiate a new CardDeck with the num_decks and type BlackJackCard - for each hand in the trial, call play_hand and keep track of how much money the player receives across all the hands in the trial - calculate the player's rate of return, which is 100*(total money received-total money bet)/(total money bet) Parameters: strategy - function, one of the the four playing strategies defined in BlackJackHand (e.g. BlackJackHand.mimic_dealer_strategy) initial_bet - float, the amount that the player initially bets each hand. (default=2) num_decks - int, the number of standard card decks in the CardDeck. (default=8) num_hands - int, the number of hands the player plays in each trial. (default=20) num_trials - int, the total number of trials in the simulation. (default=100) show_plot - bool, True if the plot should be displayed, False otherwise. (default=False) Returns: tuple, containing the following 3 elements: - list of the player's rate of return for each trial - float, the average rate of return across all the trials - float, the standard deviation of rates of return across all trials MORE PLOTTING HINTS: y_values = stats.norm.pdf(x_values, avg, std), This function returns the y-values of the normal distribution make sure x_values passed in are sorted. avg and std can be calculated using some numpy functions. """ returns = [] for _ in range(num_trials): earnings_sum = 0 bet_sum = 0 deck = CardDecks(num_decks, BlackJackCard) #play_hand(deck, strategy, initial_bet=1.0) for _ in range(num_hands): result_tuple = play_hand(deck, strategy, initial_bet) earnings_sum += result_tuple[1] bet_sum += result_tuple[0] returns.append(100 * (earnings_sum - bet_sum) / bet_sum) # avg_returns = sum(returns) / num_trials #calculate standard deviation avg_returns = np.mean(returns) sdev = np.std(returns) # sigma = 0 # mean = sum(returns) / len(returns) # for i in returns: # sigma += (i - mean)**2 # sdev = ((sigma)/len(returns))**0.5 #plots #plot the distribution of rates of return using a normal distributions #x = np.arrange(0, 0); #y = stuff #plot.plot(x, y) if show_plot: x_values = range(-100, 110, 10) y_values = stats.norm.pdf(x_values, avg_returns, sdev) plt.title("Player ROI on playing " + str(num_hands) + " Hands (" + str(strategy.__name__) + ") \n (Mean = " + str(round(avg_returns, 2)) + "%, SD = " + str(round(sdev, 2)) + "%)") plt.xlabel("% Return") plt.legend() plt.hist(sorted(returns), bins=9, density=True) plt.plot(x_values, y_values) # plt.hist(y_values, bins=9) plt.show() return (returns, avg_returns, sdev)
def run_simulation(strategy, init_bet=2.0, num_decks=8, num_hands=20, num_trials=100, show_plot=False): """ Runs a simulation and generates a normal distribution reflecting the distribution of player's rates of return across all trials. The normal distribution is based on the mean and standard deviation of the player's rates of return across all trials. You should also plot the histogram of player's rates of return that underlies the normal distribution. For hints on how to do this, consider looking at matplotlib.pyplot scipy.stats.norm.pdf For each trial: - instantiate a new CardDeck with the num_decks and type BlackJackCard - for each hand in the trial, call play_hand and keep track of how much money the player receives across all the hands in the trial - calculate the player's rate of return, which is 100*(total money received-total money bet)/(total money bet) Parameters: strategy - function, one of the the four playing strategies defined in BlackJackHand (e.g. BlackJackHand.copy_dealer_strategy) init_bet - float, the amount that the player initially bets each hand. (default=2) num_decks - int, the number of standard card decks in the CardDeck. (default=8) num_hands - int, the number of hands the player plays in each trial. (default=20) num_trials - int, the total number of trials in the simulation. (default=100) show_plot - bool, True if the plot should be displayed, False otherwise. (default=False) Returns: tuple, containing the following 3 elements: - list of the player's rate of return for each trial - float, the average rate of return across all the trials - float, the standard deviation of rates of return across all trials MORE PLOTTING HINTS: y_values = stats.norm.pdf(x_values, avg, std), This function returns the y-values of the normal distribution make sure x_values passed in are sorted. avg and std can be calculated using some numpy functions. """ return_rates = [] #run trials for trial in range(num_trials): money_returned = 0 total_bet = 0 deck = CardDecks(num_decks, BlackJackCard) #new deck each trial for hand in range(num_hands): #play game for all hands result = play_hand(deck, strategy, init_bet) money_returned += result[1] total_bet += result[0] return_rates.append( 100 * (money_returned - total_bet) / (total_bet)) #add return rate of each trial to a list #calculate mean and standard deviation mean = np.mean(return_rates) std = np.std(return_rates) #plot histogram and normal curve if show_plot == True: x_vals = np.sort(return_rates) #sort the return rates on the axis y_vals = stats.norm.pdf(x_vals, mean, std) plt.hist(x_vals, bins=10, density=True) plt.plot(x_vals, y_vals) plt.xlabel("% Return") plt.title("Player ROI on Playing " + str(num_hands) + " Hands (" + str(strategy.__name__) + ") \n (Mean = " + str(mean) + "%, SD = " + str(std) + "%)") plt.show() return (return_rates, mean, std)
def run_simulation(strategy, bet=2.0, num_decks=8, num_hands=20, num_trials=100, show_plot=False): """ Runs a simulation and generates a box plot reflecting the distribution of player's rates of return across all trials. The box plot displays the distribution of data based on the five number summary: minimum, first quartile, median, third quartile, and maximum. We also want to show the average on the box plot. You can do this by specifying another parameter: plt.boxplot(results, showmeans=True) For each trial: - instantiate a new CardDeck with the num_decks and type BlackJackCard - for each hand in the trial, call play_hand and keep track of how much money the player receives across all the hands in the trial - calculate the player's rate of return, which is 100*(total money received-total money bet)/(total money bet) Parameters: strategy - function, one of the the 3 playing strategies defined in BlackJackHand (e.g. BlackJackHand.mimic_dealer_strategy) bet - float, the amount that the player bets each hand. (default=2) num_decks - int, the number of standard card decks in the CardDeck. (default=8) num_hands - int, the number of hands the player plays in each trial. (default=20) num_trials - int, the total number of trials in the simulation. (default=100) show_plot - bool, True if the plot should be displayed, False otherwise. (default=False) Returns: tuple, containing the following 3 elements: - list of the player's rate of return for each trial - float, the average rate of return across all the trials - float, the standard deviation of rates of return across all trials """ returns = [] totalbet = bet * num_hands for trial in range(num_trials): #Calculate the gains from every hand of a single trial and record rate of return earnHands = 0 deck = CardDecks(num_decks, BlackJackCard) for hand in range(num_hands): earnHands += play_hand(deck, strategy, bet) returns.append(100.0 * (earnHands - totalbet) / totalbet) #Calculate mean and standard deviation mean = np.mean(returns) std = np.std(returns) if show_plot: plt.boxplot(returns, showmeans=True) plt.title("Player ROI on Playing 20 Hands (" + strategy.__name__ + ")\n(mean = " + str(mean) + "%, SD = " + str(std) + "%)") plt.ylabel("% Returns") plt.xticks([1], [strategy.__name__]) plt.show() return (returns, mean, std)
def __init__(self, num_decks, card_type, cards_to_deal): CardDecks.__init__(self, num_decks, card_type) self.cards_to_deal = cards_to_deal
def run_simulation(strategy, initial_bet=2.0, num_decks=8, num_hands=20, num_trials=100, show_plot=False): """ Runs a simulation and generates a normal distribution reflecting the distribution of player's rates of return across all trials. The normal distribution is based on the mean and standard deviation of the player's rates of return across all trials. You should also plot the histogram of player's rates of return that underlies the normal distribution. For hints on how to do this, consider looking at matplotlib.pyplot scipy.stats.norm.pdf For each trial: - instantiate a new CardDeck with the num_decks and type BlackJackCard - for each hand in the trial, call play_hand and keep track of how much money the player receives across all the hands in the trial - calculate the player's rate of return, which is 100*(total money received-total money bet)/(total money bet) Parameters: strategy - function, one of the the four playing strategies defined in BlackJackHand (e.g. BlackJackHand.mimic_dealer_strategy) initial_bet - float, the amount that the player initially bets each hand. (default=2) num_decks - int, the number of standard card decks in the CardDeck. (default=8) num_hands - int, the number of hands the player plays in each trial. (default=20) num_trials - int, the total number of trials in the simulation. (default=100) show_plot - bool, True if the plot should be displayed, False otherwise. (default=False) Returns: tuple, containing the following 3 elements: - list of the player's rate of return for each trial - float, the average rate of return across all the trials - float, the standard deviation of rates of return across all trials MORE PLOTTING HINTS: y_values = stats.norm.pdf(x_values, avg, std), This function returns the y-values of the normal distribution make sure x_values passed in are sorted. avg and std can be calculated using some numpy functions. """ #nested for loop #if statement if plot is true #have a lsit to keep track of return rate #iterate through trials first, then through hands in each trial #for each hand in the trial, use same card deck #keep track of money bet and earned #counter = 0 return_rates = [] for trial in range(num_trials): # if counter%10000 == 0: # print("inf in outer for", counter) deck = CardDecks(num_decks, BlackJackCard) money_won_counter = 0 money_bet = 0 for i in range(num_hands): played_hand = play_hand(deck, strategy, initial_bet) money_won_counter += played_hand[1] money_bet += played_hand[0] # if counter%10000 == 0: # print("inf in innner for", counter) # counter+=1 return_rates.append(100 * (money_won_counter - money_bet) / (money_bet)) if show_plot: return_rates.sort() plt.title("Player ROI on Playing 20 Hands (" + strategy.__name__ + ") Mean = " + str(round(np.mean(return_rates), 2)) + "%" + ", SD = " + str(round(np.std(return_rates), 2))) fit = stats.norm.pdf(return_rates, np.mean(return_rates), np.std(return_rates)) plt.plot(return_rates, fit) plt.hist(return_rates, density=True) plt.ylabel("% Return") #plt.plot(stats.norm.pdf(return_rates, np.mean(return_rates), np.std(return_rates))) plt.show() return return_rates, np.mean(return_rates), np.std(return_rates)
def run_simulation(strategy, bet=2.0, num_decks=8, num_hands=20, num_trials=100, show_plot=False): """ Runs a simulation and generates a normal distribution reflecting the distribution of player's rates of return across all trials. The normal distribution is based on the mean and standard deviation of the player's rates of return across all trials. You should also plot the histogram of player's rates of return that underlies the normal distribution. For hints on how to do this, consider looking at matplotlib.pyplot scipy.stats.norm.pdf For each trial: - instantiate a new CardDeck with the num_decks and type BlackJackCard - for each hand in the trial, call play_hand and keep track of how much money the player receives across all the hands in the trial - calculate the player's rate of return, which is 100*(total money received-total money bet)/(total money bet) Parameters: strategy - function, one of the the 3 playing strategies defined in BlackJackHand (e.g. BlackJackHand.dealer_strategy) bet - float, the amount that the player bets each hand. (default=2) num_decks - int, the number of standard card decks in the CardDeck. (default=8) num_hands - int, the number of hands the player plays in each trial. (default=20) num_trials - int, the total number of trials in the simulation. (default=100) show_plot - bool, True if the plot should be displayed, False otherwise. (default=False) Returns: tuple, containing the following 3 elements: - list of the player's rate of return for each trial - float, the average rate of return across all the trials - float, the standard deviation of rates of return across all trials """ # Create a list to store roi values list_of_roi = [] # Run num_trials number of trials for t in range(num_trials): money_received = 0 deck = CardDecks(num_decks, BlackJackCard) for h in range(num_hands): money_received += play_hand(deck, strategy, bet) # Calculate ROI roi = 100 * (money_received - (bet * num_hands)) / (bet * num_hands) list_of_roi.append(roi) # Calculate average and standard deviation avg_roi = sum(list_of_roi) / num_trials std = np.std(np.array(list_of_roi)) # Plot if show_plot: plt.figure() plt.title("Player's ROI on Playing " + str(num_hands) + " hands (" + strategy.__name__ + ")\n" "Mean= " + str(avg_roi) + ", SD= " + str(std)) plt.hist(list_of_roi, density=True) plt.xlabel("% Return") list_of_roi.sort() plt.plot(list_of_roi, stats.norm.pdf(list_of_roi, avg_roi, std)) # Show plot plt.show() return (list_of_roi, avg_roi, std)