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

조회 수: 13(최근 30일)
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;
while(sum < 22)
A = input("stand or hit: ");%fix error
if A == stand
if A == hit
%give another card
%display win or lose

채택된 답변

Geoff Hayes
Geoff Hayes 2021년 4월 28일
편집: Geoff Hayes 2021년 4월 28일
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')
elseif strcmpi(A,'hit')
%give another card
% invalid input, re-ask question
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)
% etc.
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.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by