Create a Deck of cards in Javascript

Create a Deck of cards in Javascript

Written by Dev Dojo on May 14th, 2016 Views Report Post

If you want to create a card game in Javascript you are going to need a way to build a deck of cards. In this quick tutorial we'll show you how to create a card object and a deck object and then we'll show you how to shuffle the deck of cards.

First thing is first, let's create a simple card object.

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

Above we have a new card object that will accept a value, name, and suit for each card. Ok, now that we've got our card object let's create a simple deck object that will return an array of 52 cards.


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

    return cards;
}

Now, let's create a new deck of cards and print it out in the consule.

var myDeck = new deck();
console.log(myDeck);

Now if we were to print it out in the console we would get an output of 52 cards. Let's create a window Onload function to add some HTML elements to the page to display the cards

window.onload = function() {

	for(var i=0; i < myDeck.length; i++){
		div = document.createElement('div');
		div.className = 'card';

		if(myDeck[i].suit == 'Diamonds'){
			var ascii_char = '♦';
		} else {
			var ascii_char = '&' + myDeck[i].suit.toLowerCase() + ';';
		}

		div.innerHTML = '' + myDeck[i].name + '' + ascii_char + '';
		document.body.appendChild(div);
	}

}

What we've done above is looped through each card and created a new div to be appended to the body. So, if we were to run all this code in an HTML page and include a little style to the page we would end up with the following output.

Great! But, as you can see all the cards are currently in order, and we may want to add a shuffle function that can shuffle the cards. Like so:


function shuffle(o) {
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

myDeck = shuffle(myDeck);

Putting it all together we we can display all the cards in a shuffled order:

Now, since you've learned how to display a deck and shuffle the deck you can continue creating your amazing card game :)

Comments (0)