同じバッチのコードについて少し前に質問しましたが、今回は別の問題です。その別の問題について得たヒントを使用して、JavaScriptブラックジャックゲームのスコア関数であるこの問題を解決しようとしました。私のスコア関数は、Mozilla Scratchpadでテストすると、NaNを出力し続けます。リターンを微調整し、2つのforループをマージし、deal関数の変数の名前を変更して、他の変数と混同しないようにしましたが、それでも何も起こりません。誰かが尋ねた同様の質問がありましたが、それは私の問題を解決しませんでした。
function Card (s, n) {
var suit = s;
var number = n;
this.getNumber = function () {
return number;
};
this.getSuit = function () {
return suit;
};
this.getValue = function () {
if (number > 10) {
return 10;
} else if (number === 1) {
return 11;
} else {
return number;
}
};
}
var cardNames = {1:"Ace", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8", 9:"9", 10:"10", 11:"Joker", 12:"Queen", 13:"King"};
var suitNames = {1:"Clubs", 2:"Diamonds", 3:"Hearts", 4:"Spades"};
var deal = function () {
var s = Math.floor(Math.random() * 4 + 1);
var n = Math.floor(Math.random() * 13 + 1);
return new Card(s, n);
};
function Hand(){
var cards = [];
var card1 = deal();
var card2 = deal();
cards = [card1, card2];
this.getHand = function () {
return cards;
};
this.score = function () {
var points;
for (i = 0; i < cards.length; i++) {
points = points + cards[i].getValue();
}
for (i = 0; i < cards.length; i++) {
if (points > 21 && cards[i].getValue() === 11) {
points = points - 10;
}
} return points;
};
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
} return hand;
};
this.hitMe = function () {
cards.push(deal());
};
}
var playAsDealer = function () {
var playDealer = new Hand();
while (playDealer.score() < 17) {
playDealer.hitMe();
}
this.printHand = function () {
return playDealer.printHand();
};
this.score = function () {
return playDealer.score();
};
return playDealer;
};
var playAsUser = function () {
var playUser = new Hand();
var decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
for (i = 0; decision !== false; i++) {
playUser.hitMe();
decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
}
this.printHand = function () {
return playUser.printHand();
};
this.score = function () {
return playUser.score();
};
return playUser;
};
var declareWinner = function (userHand, dealerHand) {
if ((userHand.score < dealerHand.score) || userHand.score > 21) {
alert("You lose.");
} else if (userHand.score > dealerHand.score) {
alert("You win.");
} else {
alert("You tied.");
}
};
var playGame = function () {
user = playAsUser();
dealer = playAsDealer();
declareWinner(user, dealer);
alert("User got " + user.printHand() + " for a total score of " + user.score());
alert("Dealer got " + dealer.printHand() + " for a total score of " + dealer.score());
};
playGame();