In this post, I will be going over how to build a deck of cards in JavaScript. The deck can be used for future projects or future games, such as this JavaScript Blackjack game which I made a while back.
This is a super quick implementation, and can typically be done with less than 100
lines of code. I will be implementing other card related
functions/features as well, such as shuffling the deck, grabbing a card
from the top or bottom and creating multiple decks of cards.
If you are brand new to JavaScript, then I recommend the following book Web Design with HTML, CSS, JavaScript and jQuery, which can get you up and running pretty quickly with JavaScript.
Overview
A traditional deck of 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. In total that consists of 52 different cards.
The deck in this tutorial will consist of an Array of card objects which we will create dynamically.
Variable declarations
Declare the following variables in order to get started.
var suits = ["spades", "diamonds", "clubs", "hearts"];
var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
The variable suits is an array of card suites that we will use as a lookup table. And the 2nd variable values 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 that object will be added that to the deck array.
The getDeck() function will return this brand new deck to the caller.
function getDeck()
{
let deck = new Array();
for(let i = 0; i < suits.length; i++)
{
for(let x = 0; x < values.length; x++)
{
let card = {Value: values[x], Suit: suits[i]};
deck.push(card);
}
}
return deck;
}
This function will populate the deck array with 52 card objects in total, which will resemble the following at the end.
var deck = [{Value: 'A', Suit: 'Spades'}, {Value: 'A', Suit: 'Diamonds'}, {Value: 'A', Suit: 'Clubs'}...]
Shuffling the card deck
Next up we need a function to shuffle the deck. For this, we will need to come up with a shuffling algorithm. We are going to pick 2 random locations on the deck, and then switch their values around. We will be doing this about 1000 times per shuffle, which should be good enough to generate a seemingly random deck.
function shuffle(deck)
{
// for 1000 turns
// switch the values of two random cards
for (let i = 0; i < 1000; i++)
{
let location1 = Math.floor((Math.random() * deck.length));
let location2 = Math.floor((Math.random() * deck.length));
let tmp = deck[location1];
deck[location1] = deck[location2];
deck[location2] = tmp;
}
}
At this point, the 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.
The render function will iterate through each card object in the deck Array and will create the DOM elements on the webpage using the createElement function.
All of the card elements will get added to a primary <div id="deck"> root node on the page.
function renderDeck(deck)
{
document.getElementById("deck").innerHTML = "";
for(let i = 0; i < deck.length; i++)
{
let card = document.createElement("div");
let value = document.createElement("div");
let 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);
}
}
For this example, our card will simply be a <div> element with a particular class specifying its suit. It will use the following sprite image to actually render the proper suit.
The following CSS will render the design accordingly.
.deck .card
{
border: solid 1px #aaa;
border-radius: 9px;
width: 95px;
height: 150px;
float:left;
background-color: white;
padding: 3px 3px 3px 3px;
margin: 5px;
}
.card2
{
width: 50px;
padding: 10px;
border: solid 1px #808080;
background-color: white;
display: inline-block;
border-radius: 10px;
font-size: 22px;
text-align: center;
margin: 3px;
border:solid 3px;
}
.card .value{
font-size:15pt;
font-family: sans-serif;
}
.card .suit
{
background-image: url('https://www.thatsoftwaredude.com/images/post/0f631eeb-6c4a-4bfd-9f86-e0a08ae8584b.png');
height: 100px;
width: 90px;
}
.card .diamonds
{
background-position-y: 100px;
}
.card .hearts
{
background-position-x: 90px;
}
.card .clubs
{
background-position-x:90px;
background-position-y:100px;
}
And you can use the following standard HTML boilerplate as well.
<html>
<head>
<link rel="stylesheet" href="main.css">
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div class="deck">
<h1>A Deck of Cards</h1>
<a href="javascript:void(0)" class="btn" onclick="shuffle()">Shuffle</a>
<div id="deck"></div>
</div>
</body>
</html>
At this point, we have the functions to create a new deck of cards, shuffle them, and draw them out onto the screen. It looks something like the following.
Version 2: Rendering
Another way to render the cards is a method that I used in my blackjack game, in which I use HTML entities instead of images.
function renderDeck(deck)
{
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='&hearts';
else if (deck[i].Suit == 'spades')
icon = '&spades';
else if (deck[i].Suit == 'diamonds')
icon = '&diams';
else
icon = '&clubs';
card.innerHTML = deck[i].Value + '' + icon;
card.className = 'card';
document.getElementById("deck").appendChild(card);
}
}
6
?
K
?
A
?
9
?
Q
?
7
?
7
?
10
?
4
?
3
?
10
?
5
?
A
?
9
?
6
?
10
?
Q
?
4
?
Q
?
K
?
2
?
7
?
6
?
7
?
Q
?
6
?
3
?
3
?
2
?
2
?
A
?
4
?
5
?
8
?
J
?
5
?
8
?
3
?
A
?
10
?
8
?
8
?
J
?
K
?
5
?
J
?
4
?
9
?
J
?
2
?
9
?
K
?
2
?
4
?
K
?
J
?
2
?
Q
?
K
?
3
?
5
?
9
?
6
?
5
?
8
?
6
?
K
?
A
?
7
?
10
?
A
?
4
?
4
?
2
?
Q
?
9
?
8
?
10
?
J
?
9
?
8
?
9
?
10
?
7
?
3
?
4
?
8
?
Q
?
5
?
3
?
Q
?
A
?
J
?
3
?
A
?
2
?
10
?
6
?
K
?
7
?
7
?
J
?
6
?
5
?
Creating multiple decks
The getDeck() function created above will return a brand new 52-card deck whenever you need one. You can store that in a local variable (or global) depending on your project.
var deck1 = getDeck();
var deck2 = getDeck();
Once the decks are created they can be passed into the remaining helper functions as needed.
var deck1 = getDeck();
shuffle(deck1);
renderDeck(deck1);
Now that the decks are created, we can work at dealing cards out.
Deal a card
Once shuffled, most decks are dealt from the top down, like a stack. And that means that we can levarage the Array's pop() method in order to deal cards.
function dealCard(deck){
return deck.pop();
}
let card = dealCard(deck1);
console.log(card);
The pop() method in JavaScript will remove the last item added to an Array and will return that item back to the caller, which is the exact scenario we have here.
Full source and downloads
Download full source code
Fork on Codepen.io