我正在开发一个简单的二十一点程序。我对 javascript 完全陌生,在调试我的程序时遇到了麻烦。我不断收到 TypeError: cannot call getNumber method of undefined ..... 而且我完全迷路了。我正在尝试获取为每张卡存储的数值,但似乎这就是我在类printHand()
内的方法中发生的错误Hand
。当打印出两张或多张牌的手牌时,我会遍历手牌中的每张牌,并调用每手牌的数组在cards[i].getNumber()
哪里。cards[]
我没有正确引用卡片 [] 吗?我仔细检查以确保我的方法和变量设置为公共,但我仍然无法弄清楚为什么getNumber()
在未定义的对象上被调用。我引用这个对象的方式有问题吗?
这是我的代码:
// Card Constructor
function Card (suit, number){
var the_suit = suit;
var the_number = number;
this.getNumber = function(){
return the_number;
};
this.getSuit = function(){
return the_suit;
};
this.getValue = function (){
// face cards
if(the_number > 10){
return 10;
// aces
} else if (the_number < 2){
return 11;
// other cards
} else {
return the_number;
}
};
}
function deal (){
// get card suit
var rand1 = Math.floor(Math.random ( ) * 4 + 1);
// get car number
var rand2 = Math.floor(Math.random ( ) * 13 + 1);
var newCard = new Card(rand1, rand2);
}
function Hand (){
// create two cards for initial hand
var card1 = deal();
var card2 = deal();
// store cards in array
var cards = [card1,card2];
// getter
this.getHand = function (){
return cards;
};
// get the score
this.score = function(){
var length = cards.length;
var score = 0;
var numAces = 0;
for(i = 0; i < length; i++){
if (cards[i].getValue() === 11 ){
numAces++;
}
score += cards[i].getValue();
}
while(score > 21 && numAces !== 0){
sum -= 10;
numAces--;
}
};
this.printHand = function(){
var length = cards.length;
for(i=0; i< length; i++){
var string = string + cards[i].getNumber() + " of suit " + cards[i].getSuit() + ", ";
}
return string;
};
this.hitMe = function(){
var newCard = deal();
cards.push(newCard);
}
}
function playAsDealer(){
var newHand = new Hand();
while(newHand.score < 17){
newHand.hitMe();
}
return newHand;
}
function playAsUser(){
var newHand = new Hand();
var choice = confirm("Current hand: "+ newHand.printHand() + ": Hold (Ok) or Stand(Cancel)");
while(choice){
newHand.hitMe();
choice = confirm("Current hand: "+ newHand.printHand() + ": Hold (Ok) or Stand(Cancel)");
}
}
function declareWinner(user, dealer){
//user wins case
if (user.score > dealer.score){
console.log("You are the Champion!");
}
// tie game
else if(user.score===dealer.score){
console.log("Tied!");
}
else{
console.log("Loser!!");
}
}
function playGame (){
var user = playAsUser();
var dealer = playAsDealer();
console.log("User's Hand: " + user.printHand());
console.log("Dealer's Hand: " + dealer.printHand());
declareWinner();
}
playGame();