%blackjack simulation
%bet one dollar on each hand; start with $100
my_money = 100;
iwin=0;%counter for number of wins
ilose = 0;%counter for number of losses
ties = 0;%counter for number of ties
hand = 0;%counter for number of hands played.
my_stay_value = 14; %don't take another card if hand is worth 14 or more.

%deal cards from 2 decks
for i = 1:100
%note 11= jack, 12 = queen, 13 = king, and 14 = ace.
d1 = [2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 10 10 10 10 11 11 11 11 12 12 12 12 13 13 13 13 14 14 14 14];
deck = [d1 d1];
numcards = size(deck,2);
bigindexset = 1:numcards; 
permuted_indices = bigindexset(randperm(numcards));
shuffled_cards = deck(permuted_indices);


%One game (of two decks)
card_counter = 1; 
while card_counter < numcards - 10%dont let deck run out!
   %new hand
   hand = hand +1;
   my_count = 0;
   dealer_count = 0;
   
   %make initial deal of two cards to Player and Dealer.
   my_count = my_card_value(card_counter, shuffled_cards, my_count);
   card_counter = card_counter+1;%advance deck index
   dealer_count = dealer_card_value(card_counter, shuffled_cards, dealer_count);
   card_counter = card_counter+1;
   my_count = my_card_value(card_counter, shuffled_cards, my_count);
   card_counter = card_counter+1;
   dealer_count = dealer_card_value(card_counter, shuffled_cards, dealer_count);
   card_counter=card_counter+1;
   
   while my_count < my_stay_value  & card_counter < numcards
      my_count = my_card_value(card_counter, shuffled_cards, my_count);
      card_counter = card_counter +1;
   end
   
   while dealer_count < 17  & card_counter < numcards & my_count < 22
      dealer_count = dealer_card_value(card_counter, shuffled_cards, dealer_count);
      card_counter = card_counter +1;
   end

%who wins?   
   if my_count > 21% I am bust
      my_money = my_money - 1;
      ilose = ilose +1;
   elseif dealer_count > 21%dealer is bust
      my_money = my_money + 1;
      iwin = iwin +1;
   elseif my_count == dealer_count
      %push--my winnings don't change
      ties = ties +1;
   elseif my_count > dealer_count
      my_money = my_money +1;
      iwin = iwin +1;
   else
      my_money = my_money -1;
      ilose = ilose + 1;
   end%if
   %construct an array that computes a running fraction of losses   
   perclose(hand) = ilose/(iwin+ilose+ties);
   end%while
end%for
   
   iwin
   ilose
   ties
   plot(perclose)
   my_money