I'm doing a card game as an assignment and I'm stuck at the last hurdle. The problem I have is that I need a condition control to see and determine the value of a card dependent of the outcome. The ACE in this game could be worth 1 or 14 dependant on what is most beneficial for the outcome. The game is some sort of black jack but each card has its face value apart from the ACE which can be worth both 1 and 14. I can check and set the value to either 1 or 14 if the sum of the picked cards is 7 or less. 7+14=21 and most beneficial for the game. But I can't get the code correct for the opposite: if the first card is an ACE and its value set to 14 and the second card is a 9 then the result will be 23 and the player is busted. I need the ACE to be worth 1 then... The default value of an ACE is 1. The code I have so far is:
this.dealCard = function () {
this.dealedHand.push(shuffledDeck.shift())
let sum = 0
this.dealedHand.forEach(function (card) {
if (card.value === 1 && sum <= 7) {
card.value = 14
} //Another condition clause to reverse that and let the ACE be 1 again...
sum = sum + card.value
})
this.dealedHandSum = sum
}
for (let i = 0; i < 2; i++) {
this.dealCard()
}
while (this.dealedHandSum < player.stopAtValue) {
this.dealCard()
}
This is a function to sum the cards shifted in to the Hand.
Everything else is working as it should but I want to prevent this from happening:
Johanna: A♠ K♣ 27
Johanna got 27 and is busted!
Just count aces at their highest value, then reduce them if the player is busted. This means you have to keep track of how many aces they have, but that's not too hard:
this.dealCard = function () {
this.dealedHand.push(shuffledDeck.shift())
let sum = 0
let aces = [] // Keep track of each ace in the hand
this.dealedHand.forEach(function (card) {
if (/* Card is Ace */) {
card.value = 14 // Count each ace at its highest value
aces.push(card)
}
sum = sum + card.value
})
while (aces.length && sum > 21) { // If busted, and we have aces, reduce their value
sum -= 13
let ace = aces.shift()
ace.value = 1
}
this.dealedHandSum = sum
}