write code for the game blackjack in matlab

Here is a basic implementation of Blackjack game in MATLAB:

main.m
function Blackjack
% Function to play Blackjack in MATLAB

% Initialize deck of cards and shuffle
deck = Shuffle(1:52);

playerCards = deck(1:2); % First two cards of player
dealerCards = deck(3:4); % First two cards of dealer

playerSum = GetSum(playerCards); % Get sum of player cards
dealerSum = GetSum(dealerCards); % Get sum of dealer cards

fprintf('Player cards: ');
PrintCards(playerCards);
fprintf('Dealer card: (hidden) \n');

if playerSum == 21 % Player has Blackjack
    fprintf('Blackjack! You win.\n');
    return;
end

while true
    % Ask player for hit or stay
    choice = input('Do you want to hit or stay? (h/s) ', 's');
    if lower(choice) == 'h' % Player wants to hit
        playerCards(end+1) = deck(5); % Add a new card to player
        playerSum = GetSum(playerCards); % Get new sum of player cards
        fprintf('Player card: ');
        PrintCards(playerCards(end));
        if playerSum > 21 % Player has gone bust
            fprintf('Bust. You lose.\n');
            return;
        elseif playerSum == 21 % Player has Blackjack
            fprintf('Blackjack! You win.\n');
            return;
        end
    elseif lower(choice) == 's' % Player wants to stay
        break;
    else
        fprintf('Invalid input. Please enter h or s.\n');
    end
end

% Dealer's turn
fprintf('Dealer cards: ');
PrintCards(dealerCards);
while dealerSum < 17 % Dealer hits until sum is at least 17
    dealerCards(end+1) = deck(length(playerCards)+length(dealerCards)+1);
    dealerSum = GetSum(dealerCards);
    fprintf('Dealer card: ');
    PrintCards(dealerCards(end));
    if dealerSum > 21 % Dealer has gone bust
        fprintf('Dealer bust. You win!\n');
        return;
    end
end

% Compare sum of player and dealer cards
if playerSum > dealerSum
    fprintf('You win!\n');
elseif playerSum < dealerSum
    fprintf('You lose.\n');
else
    fprintf('It is a tie.\n');
end

end

function sumCards = GetSum(cards)
% Function to get the sum of cards
sumCards = sum(min(10, mod(cards - 1, 13) + 1));

end

function PrintCards(cards)
% Function to print the cards
for i = 1:length(cards)
    if mod(cards(i), 13) == 0
        fprintf('K ');
    elseif mod(cards(i), 13) == 1
        fprintf('A ');
    elseif mod(cards(i), 13) == 11
        fprintf('J ');
    elseif mod(cards(i), 13) == 12
        fprintf('Q ');
    else
        fprintf('%d ', mod(cards(i), 13));
    end
end
fprintf('\n');
end

function shuffledDeck = Shuffle(deck)
% Function to shuffle the deck of cards
n = length(deck);
for i = 1:n-1
    j = i + randperm(n-i+1,1)-1;
    deck([i j]) = deck([j i]);
end
shuffledDeck = deck;
end
2627 chars
102 lines

To play the game, simply call the function Blackjack(). The game will prompt the player to enter "h" to hit or "s" to stay. The game then proceeds with the dealer's turn until the game is finished.

related categories

gistlibby LogSnag