MATLAB: Blackjack how to define cards as their value

blackjack

Hey everybody, I am trying to write a very simple blackjack code where the player either hits 21 and wins, or busts and loses. So far i have this,
function card = dealcard;
%This program will allow someone to draw a card at random from a full deck
and see what that card would be. you can go through the whole deck
persistent dec; %persistent makes it so matlab stores this variable
if length(dec)<53
dec=[1:52]; %one deck of cards
dec=dec(randperm(length(dec))); %this shuffles the cards
end;
card=dec(end);
I do not know how to define the cards as being an ace, 2,3,…queen, and king. If anyone could help me with this that would be great. Thank you.

Best Answer

  • You don't need to make it persistent. Just pass the dec in. And to keep track of both the card number, and the card's value, you'll need a 2 D array.
    cardNumbers = [1:52];
    cardValues = [1:13, 1:13, 1:13, 1:13];
    dec = [cardNumbers', cardValues']
    % Now shuffle
    shufflingOrder = randperm(size(dec, 1));
    dec = dec(shufflingOrder, :)
    % Prepare your output
    cardNumber = dec(end, 1);
    cardValue = dec(end, 2);