In this post, I will be building a deck of cards in JavaScript, that can hopefully be used for future projects or future games, such as Blackjack. It's a super quick project, and can be done in less than 100 lines of code. I will be implementing as many card related functions as I can, such as shuffling a deck, grabbing a card from the top or bottom and grabbing a new deck of cards.

If you are new to JavaScript, I highly recommend Web Design with HTML, CSS, JavaScript and jQuery, which can definitely get you up and running pretty quickly with JavaScript.

Deck of Cards

Project: Deck of cards
Language: JavaScript
Estimated Completion: 1 hour

Overview

A deck of traditional playing cards is composed of 4 sets of 13 sequential numbered cards. A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, and K. Each card in the set belongs to a particular suit: Hearts, Spades, Clubs and Diamonds. Sounds simple enough. I'll be using JavaScript as I mentioned, and my deck will consist of an Array of objects with a function to render each card graphically.

Let's Start

Declare the following variables in order to get started.


var deck = new Array();
var suits = ["spades", "diamonds", "clubs", "hearts"];
var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

The first variable is an array that will hold our card objects. The second variable is simply an array of card suites that we will use as a lookup table essentially. And our 3rd variable will hold all the possible values that a card can have.

Create The Deck

In order to create the deck, we're going to pair up each suit from the array above, with each possible value also from the array declared above. We're going to create a new card object with the corresponding value and suit and we'll be adding that to our empty deck array.


function getDeck()
{
	var deck = new Array();

	for(var i = 0; i < suits.length; i++)
	{
		for(var x = 0; x < values.length; x++)
		{
			var card = {Value: values[x], Suit: suits[i]};
			deck.push(card);
		}
	}

	return deck;
}

At this point we should have our Deck array from above populated with 52 card objects.

Shuffle Time

Next up I need a function to shuffle up the deck. For this, I'm going to pick 2 random locations on the deck, and then switch their values around. I'm going to do this about 1000 times per shuffle, which is way more than I could do manually, so it should be good enough to generate seemingly random deck.


function shuffle()
{
	// for 1000 turns
	// switch the values of two random cards
	for (var i = 0; i < 1000; i++)
	{
		var location1 = Math.floor((Math.random() * deck.length));
		var location2 = Math.floor((Math.random() * deck.length));
		var tmp = deck[location1];

		deck[location1] = deck[location2];
		deck[location2] = tmp;
	}
}

At this point, my deck array should contain 52 objects in a random order. But it's funner to see it than to hear me talk about it, so my next trick, I'm going to make the cards appear.


function renderDeck()
{
      document.getElementById("deck").innerHTML = "";

	for(var i = 0; i < deck.length; i++)
	{
		var card = document.createElement("div");
		var value = document.createElement("div");
		var suit = document.createElement("div");
		card.className = "card";
		value.className = "value";
		suit.className = "suit " + deck[i].Suit;

		value.innerHTML = deck[i].Value;
		card.appendChild(value);
		card.appendChild(suit);

		document.getElementById("deck").appendChild(card);
	}
}

I gave each card a child with the className of its corresponding suit. And used the following sprite to grab the icons from.

So at this point, I have the functions to create a new deck of cards, shuffle them, and draw them out onto the screen. And that actually took less time than I had anticipated. It looks something like the following.

Version 2: Rendering

A cleaner way render the cards (at least to me) is a method that I used in my blackjack game, in which I use HTML entities instead of images.

 function renderDeck()
{
	document.getElementById('deck').innerHTML = '';

	for(var i = 0; i < deck.length; i++)
	{
		var card = document.createElement("div");
		var icon = '';
		if (deck[i].Suit == 'hearts')
		icon='?';
		else if (deck[i].Suit == 'spades')
		icon = '?';
		else if (deck[i].Suit == 'diamonds')
		icon = '?';
		else
		icon = '?';

		card.innerHTML = deck[i].Value + '' + icon;
		card.className = 'card';
	document.getElementById("deck").appendChild(card);
	}
}

Version1.zip Version2.zip

Suggest the next blog post

Walter Guevara

Walter G. is a software engineer with over 10 years of professional experience. When he isn't blogging or being a CTO he enjoys coding randomly complex things that he hopes many people will get a chance to use one day.

Question or comment? (10)

M
Mads B√łtker Andersen
Thanks for this! It helped me get started on a small (potentially, big and fun) project! I Have run into a problem where the cards render twice.. which is weird.. :D
10/23/2017 11:24:00 AM
Walt
Many thanks! If you have any questions on it, feel free to shoot me a message and I'll gladly help out!
10/23/2017 8:45:11 PM
c
chris
can you send me the source code?
11/28/2018 3:33:23 AM
k
kaye
what do I do if I need 4 decks?
1/22/2018 11:18:01 AM
Walt
Hey there Kaye!

You can definitely do it without too much extra effort. The getDeck() function returns a whole deck, so essentially you can keep calling it for as many decks as you may need.


var deck1 = getDeck();
var deck2 = getDeck();

And if you are going to do that, then you should definitely pass in the 'deck' object that you are targeting to the shuffle() and to the render methods().

The code will be updated to reflect that to give better clarity!

1/24/2018 11:58:23 PM
I
Ivan
In the deck code shown here you have array outside the function and no return on deck, comparing that the one that you have in the deck tutorial. Also When i put the function in the console i have no results.
8/22/2018 4:52:45 AM
Walt
Both are slightly different implementations!
10/31/2018 10:40:18 PM
B
Bob
Hey! I appreciate the code you shared. It is really helpful. Do you happen to have the css or html document so I know or can see how the cards were created?
10/22/2018 6:41:46 PM
Walt
Hey there Bob, thanks for the kind words. If you check at the bottom of the post, I have the source zipped up and ready to download for both versions of the code!
10/22/2018 8:51:20 PM
J
Josh Dean
Walter, thank you for this. I was able to extend your examples and images for each card using their unicode values. Seemingly all 52+ cards are available. https://en.wikipedia.org/wiki/Playing_cards_in_Unicode I've implemented it for a simple addition game here: http://thejoshdean.com/citc-2375/lab6/
11/1/2018 8:10:13 AM

Add a comment

Send me your weekly newsletter filled with awesome ideas
Start
Score: 0
Use the following controls:
snake left
snake up
snake down
snake right