I am currently experimenting with a basic BlackJack game using JavaScript. Below are some snippets of my code:
function card(suit, face) {
this.suit = suit;
this.face = face;
switch (face) {
case "A":
this.faceValue = 11;
break;
case "J":
case "Q":
case "K":
this.faceValue = 10;
break;
default:
this.faceValue = parseInt(face);
break;
}
};
const player = {
cards: [],
handValue: 0
}
const dealOneCardToPlayer = () => {
tempCard = deck.cards.splice(0, 1);
player.cards.push(tempCard);
player.handValue = countHandValue(player.cards);
}
I am facing an issue with the countHandValue method where I'm unable to obtain the faceValue of Cards for the player object. I have attempted various types of for loops but haven't been successful so far. Once I can access the faceValue, I will be able to calculate and assign it to the handValue property.
const countHandValue = (cardsOnHand) => {
for (const key of cardsOnHand) {
console.log(key.faceValue);
}
for (const key in cardsOnHand) {
console.log(key.faceValue);
}
}
[Code Edited]I came across this sample code that allows me to retrieve the faceValue property, although I believe there is unnecessary complexity in the code:
const countHandValue = (cardsOnHand) => {
let sum = 0;
for (var key in cardsOnHand) {
var arr = cardsOnHand[key];
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
for (var prop in obj) {
if (prop === "faceValue") {
console.log(prop + " = " + obj[prop]);
sum = sum + obj[prop];
}
}
}
}
return sum;
}