I am trying out a simple BlackJack game with JS. Here are some of my codes:
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 stuck with countHandValue method which I couldn't get the faceValue of Cards for player object. I try with several types of for loop but with no success still. Once I can get the faceValue, then I can sum it up and assign to 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 searched and found this code which i can retrieve my faceValue property but I believe there are much extra 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;
}