二十一点Javascript:试图将所有卡片添加到卡座中(我是否正确地执行了此操作?)

时间:2015-10-16 15:08:54

标签: javascript

所以我正在通过Javascript创建一个二十一点游戏,而我正在尝试做的就是设置所有卡并将其添加到卡组中。当我尝试这个并在控制台中检查时,它不起作用,我似乎无法找到我做错了什么。我在这里走在正确的轨道上吗?我会发布我的内容。我刚开始。任何帮助,将不胜感激。感谢。

var card = function(value, name, suit) {
  this.value = value;
  this.name = name;
  this.suit = suit;
}

var deck = function() {
  this.names = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
  this.suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs'];
  this.values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11];
  var cards = [];
  for (var s = 0; s < this.suits.length; s++) {
    for (var n = 0; n < this.name.length; n++) {
      cards.push((this.values[n], this.names[n], this.suits[s]));
    }
  }
  return cards;
}

1 个答案:

答案 0 :(得分:2)

看到你是javascript的新手,我建议改变设计模式:

function Card(value, name, suit){
    this.value = value;
    this.name = name; 
    this.suit = suit;
}
// Allows to print nice card name
Card.prototype.toString = function() {
    if(this.value==11 && this.suit == "Spades")
        return "Ace of spades";
    else
        return this.suit+" "+this.name;
}


function Deck() {
     this.cards = [];
}

Deck.prototype.createAllCards = function() {
     for (var s = 0; s < Deck.suits.length; s++) {
         for (var n = 0; n < Deck.names.length; n++) {
            this.cards.push(new Card(Deck.values[n], Deck.names[n], Deck.suits[s]));
         }
     }
}
// These are so called static properties on OOP
// We can just assign those values to Deck() function
// Because they never ever change
Deck.names = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
Deck.values = [2,   3,   4,   5,   6,   7,   8,   9,   10,   10,  10,  10,  11];
Deck.suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']; 


// Initialise

var deck = new Deck();
deck.createAllCards();
console.log(deck.cards);

另外,如果可以避免,请不要使用var初始化函数。试试这两个代码示例来了解原因:

  1. smile()
    function smile() {console.log(":)")};
    
  2. smile()
    var smile = function() {console.log(":)")};
    
  3. 只有#1有效。