Reputation: 43
I'm making a blackjack game with js. It's still in development, but when the dealer or player draws an A(I'm doing dealer processing here), I want to decide the 'Ace' as 1 or 11 in favor of it. The dealer must keep drawing cards until the value is 17. If the dealer exceeds 21, it will burst. I want to get an advantageous value when A is drawn under this condition I want a vanilla js answer if you possible
Upvotes: 0
Views: 61
Reputation: 350781
First of all, I would advise not to mix I/O with game logic. Your function should focus only on working with the cards, not with document
. Let the function return whatever info is needed from it. The main program code should then deal with output.
For your example, the output should be 19, as the dealer will stop after getting 8+11, as that sum is at least 17. It may be more interesting to look at another example:
[4, 7, 6, 5, 1]
Here the sum should be first 11+5, but then when the 6 comes in, it should correct to 1+5+6, taking the 7 and then stop: 1+5+6+7=19
The following function will do that, using an extra boolean variable which will be true when an ace was used as value 11:
function drawDealerCard(cards) {
let dealerTotal = 0;
let hasEleven = false;
while (cards.length > 0 && dealerTotal < 17) {
let card = cards.pop();
if (card == 1 && !hasEleven) {
hasEleven = true;
card = 11;
}
dealerTotal += card;
if (dealerTotal > 21 && hasEleven) {
hasEleven = false;
dealerTotal -= 10;
}
}
return dealerTotal;
}
const deck = [4, 7, 6, 5, 1];
console.log(drawDealerCard(deck));
Upvotes: 1