-1

So I'm creating a Blackjack game via Javascript and what I'm trying to do is set up all the cards and add it to the deck. When I tried this and checked in the console, it did not work and I can't seem to find what I did wrong. Am I on the right track here? I'll post what I have. I'm just getting started. Any help would be appreciated. Thanks.

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;
}
Sarjan Desai
  • 3,675
  • 2
  • 17
  • 32

1 Answers1

2

Seeing you're new to javascript, I'd propose a design pattern change:

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);

Also, don't initialise functions using var if you can avoid it. Try this two code samples to see why:

  1. smile()
    function smile() {console.log(":)")};
    
  2. smile()
    var smile = function() {console.log(":)")};
    

Only #1 works.