Currently, I am learning how to build a Blackjack game with Javascript on Codecademy.
I'm struggling to figure out what code to write inside the for-loop. The task at hand is to create a "score" method within the Hand constructor. This method should iterate over all the cards in the Hand, add up the values obtained from the "getValue" function call for each card, and finally return the total sum.
If anyone could lend me a helping hand, I would greatly appreciate it. Thank you in advance.
Below is my attempt, involving the relevant code located within the for-loop at the end:
// Card Constructor
function Card(s, n) {
var suit = s;
var number = n;
this.getSuit = function() {
return suit;
};
this.getNumber = function() {
return number;
};
this.getValue = function() {
if (number >= 10) {
return 10;
} else if (number === 1) {
return 11;
} else {
return number;
}
};
};
//deal function
var deal = function() {
var randNum = Math.floor(Math.random() * 13) + 1;
var randSuit = Math.floor(Math.random() * 4) + 1;
console.log(randNum, randSuit);
return new Card(randSuit, randNum);
};
function Hand() {
var handArray = [];
handArray[0] = deal();
handArray[1] = deal();
this.getHand = function () {
return handArray;
};
this.score = function() {
var sum;
for (var i = 0; i < handArray.length; i++) {
sum += handArray[i].getValue();
return sum;
}
};
};