blackjack adding another number to a vector in a while loop & input words for a if loop

1 view (last 30 days)
im trying to make a simple vertion of blackjack and im not sure how to give another card to the players hand on a hit i am also having difficulty having a word input turn into a if loop for the game any help would be greatly appreciated
spade = 1:13;
diamond = 1:13;
heart = 1:13;
clubs = 1:13;
cards = [clubs heart diamond spade];
suffledcards = cards(randperm(numel(cards)));
playerhand = suffledcards(1:2);
dealerhand = round(13*rand()+8);
sum = 0;
for i=1:length(playerhand)
sum = playerhand;
end
while(sum < 22)
disp(sum)
A = input("stand or hit: ");%fix error
if A == stand
break
end
if A == hit
%give another card
end
end
%display win or lose

Accepted Answer

Geoff Hayes
Geoff Hayes on 28 Apr 2021
Edited: Geoff Hayes on 28 Apr 2021
Liam - since you are asking the user to enter in the command to "stand" or "hit", then you should be using the strcmpi to compare the input against the conditions. Note also the addition of 's' to indicate string input. For example,
A = input('stand or hit: ', 's');%fix error
if strcmpi(A,'stand')
break;
elseif strcmpi(A,'hit')
%give another card
else
% invalid input, re-ask question
continue;
end
Also, do not create variable names which are identical to MATLAB functions. In this case, the variable sum conflicts with the sum function. Rename this variable to something that represents what it is: the player hand value. You can also simplify this value as
playerHandValue = sum(playerhand);
while(playerHandValue < 22)
disp(playerHandValue)
% etc.
end
As for drawing a new card from the deck, you will need to keep track of which cards have already been drawn (into the player hand and maybe dealer hand) and then draw the next one from suffledcards. Since two cards have already been drawn from this deck, you could either remove those two cards or just draw the next card using the number of cards that have already been drawn into the player hand
nextDrawnCard = suffledcards(length(playerhand) + 1);
You would then insert the nextDrawnCard into the playerhand and calculate the new sum.

More Answers (0)

Categories

Find more on Card games in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!