More articles

How To Code Blackjack Using JavaScript

Written by
Filed under
Published on
Modified on
How To Code Blackjack Using JavaScript

Today I will be building a small BlackJack game in pure JavaScript in the hopes that you out there reading this can use it as a frame to build something much bigger. And if you're a beginner in the programming world, than perhaps this tutorial will help you get a much better idea of how function, objects and DOM manipulation works in JS.

While the following post won't be using any incredibly advanced topics in JavaScript, it is rather involved in what needs to go into a Blackjack game. I recommend the following book Web Design with HTML, CSS, JavaScript and jQuery for anybody that's somewhat relatively new to JavaScript and web development in general.

Separating the UI

In order to modularize the code more, I will be splitting each function into 2 parts. One will deal with data manipulation and logic, and the other will perform the UI functions, such as drawing the cards onto the screen and such.

BlackJack game rules

Most people should be familiar with the concept of the game BlackJack. But if not, here is a quick overview. Essentially, players are dealt a starting hand of 2 cards with the hopes of getting to the magical number of 21, or to get as close to 21 as possible. If a player gets 21 on his initial hand, it is called a "blackjack" or a "natural". The player wins, unless the house reaches blackjack as well. The other ways to win are to hold a higher sum of cards at the end of the play than the house, or to have the house go over 21.

The game area

How To Code Black Jack Using JavaScript

I'm going to be making as simple a game board as I can think of, in order to avoid an excessive amount of UI rendering code and such. And to keep everything focused on the logic as much as I can.

<div class="game">
     <div class="game">
            <h3>Blackjack</h3>
    
    <div class="game-body">
           <div class="game-options">
            <input type="button" id="btnStart" class="btn" value="start" onclick="startblackjack()">
            <input type="button" class="btn" value="hit me" onclick="hitMe()">
            <input type="button" class="btn" value="stay" onclick="stay()">
            </div>
    
                <div class="status" id="status"></div>
    
            <div id="deck" class="deck">
                <div id="deckcount">52</div>
            </div>
    
            <div id="players" class="players">
            </div>
    
            <div class="clear"></div>
    </div>
</div>

Build your deck

The first thing we're going to need in order to make our card game, are cards. And if you don't know how to make them, feel free to check out my post on How to build a card deck in JavaScript to see that process. But essentially, we'll be making a Deck array with 52 Card objects.


    var suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
    var values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
    var deck = new Array();

    function createDeck()
    {
        deck = new Array();
        for (var i = 0 ; i < values.length; i++)
        {
            for(var x = 0; x < suits.length; x++)
            {
                var weight = parseInt(values[i]);
                if (values[i] == "J" || values[i] == "Q" || values[i] == "K")
                    weight = 10;
                if (values[i] == "A")
                    weight = 11;
                var card = { Value: values[i], Suit: suits[x], Weight: weight };
                deck.push(card);
            }
        }
    }

The beauty of the Array is that it is stack by its nature. So we can pop cards off the top with the built in Array pop() method.

Shuffle

Here is a a very quick shuffle algorithm. For 1000 rounds we will be swapping two cards in random locations in the 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;
        }
    }

Create the players

For this example, I'll be working with 2 players only. The "House" and yourself. There are a few things that we'll want to keep track of for each player, such as an "Id" and their current "Score". An array for the players current Hand will also be added on to the player object.

    var players = new Array();
    function createPlayers(num)
    {
        players = new Array();
        for(var i = 1; i <= num; i++)
        {
            var hand = new Array();
            var player = { Name: 'Player ' + i, ID: i, Points: 0, Hand: hand };
            players.push(player);
        }
    }

That was the logic portion. And next up is the UI portion

    function createPlayersUI()
    {
        document.getElementById('players').innerHTML = '';
        for(var i = 0; i < players.length; i++)
        {
            var div_player = document.createElement('div');
            var div_playerid = document.createElement('div');
            var div_hand = document.createElement('div');
            var div_points = document.createElement('div');

            div_points.className = 'points';
            div_points.id = 'points_' + i;
            div_player.id = 'player_' + i;
            div_player.className = 'player';
            div_hand.id = 'hand_' + i;

            div_playerid.innerHTML = players[i].ID;
            div_player.appendChild(div_playerid);
            div_player.appendChild(div_hand);
            div_player.appendChild(div_points);
            document.getElementById('players').appendChild(div_player);
        }
    }

Start the game

Now we're ready to start the game. You can use the following function to begin the game and create all of the required objects.

    function startblackjack()
    {
        document.getElementById('btnStart').value = 'Restart';
        document.getElementById("status").style.display="none";
        // deal 2 cards to every player object
        currentPlayer = 0;
        createDeck();
        shuffle();
        createPlayers(2);
        createPlayersUI();
        dealHands();
        document.getElementById('player_' + currentPlayer).classList.add('active');
    }

Deal the hand

As mentioned above, the game starts with a quick shuffle. And then the hands are dealt.

    function dealHands()
    {
        // alternate handing cards to each player
        // 2 cards each
        for(var i = 0; i < 2; i++)
        {
            for (var x = 0; x < players.length; x++)
            {
                var card = deck.pop();
                players[x].Hand.push(card);
                renderCard(card, x);
                updatePoints();
            }
        }

        updateDeck();
    }

We'll be using the handy pop() method for this one, which returns to us the top most item in the stack. We'll push the cards to each players hands and then render the cards.

Render the cards

This is the UI portion of card dealing. Once a card is dealt to a particular it will need to be added to their 'hand'.

    function renderCard(card, player)
    {
        var hand = document.getElementById('hand_' + player);
        hand.appendChild(getCardUI(card));
    }

    function getCardUI(card)
    {
        var el = document.createElement('div');
        el.className = 'card';
        el.innerHTML = card.Suit + ' ' + card.Value;
        return el;
    }

Hit me

Now we're ready to start the game. This will pop a Card right out of our stack and will sum the Card value to the current users Total score.

    var currentPlayer = 0;
    function hitMe()
    {
        // pop a card from the deck to the current player
        // check if current player new points are over 21
        var card = deck.pop();
        players[currentPlayer].Hand.push(card);
        renderCard(card, currentPlayer);
        updatePoints();
        check();
    }

    function check()
    {
        if (players[currentPlayer].Points > 21)
        {
            document.getElementById('status').innerHTML = 'Player: ' + players[currentPlayer].ID + ' LOST';
        }
    }

The check() method will run after each card is dealt in order to determine if the player has lost the game.

Stay

If a player chooses to keep his hand, then the stay method will check if there are any more players in action, and if so, will transfer control over to them by updating the currentPlayer variable. If however, there are no players left, then the end method is called and points will be tallied up.

    function stay()
    {
        // move on to next player, if any
        if (currentPlayer != players.length-1) {
            document.getElementById('player_' + currentPlayer).classList.remove('active');
            currentPlayer += 1;
            document.getElementById('player_' + currentPlayer).classList.add('active');
        }

        else {
            end();
        }
    }

    function end()
    {
        var winner = -1;
        var score = 0;

        for(var i = 0; i < players.length; i++)
        {
            if (players[i].Points > score && players[i].Points < 22)
            {
                winner = i;
            }

            score = players[i].Points;
        }

        document.getElementById('status').innerHTML = 'Winner: Player ' + players[winner].ID;
    }

A winner?

And as the game is so aptly titled, ye who gets closer to 21 without going over will be the victor. The gameplay logic itself is very straightforward and no more than a hundred lines of code. UI however is another story, which is why I broke the code up into elements of both. Feel free to keep the logic and update the UI to your liking. Down below is the game in action. Again, it's a very rudimentary example, but it gives a general idea of how a few method calls and objects can make for a quick card game.

In Action

Blackjack

52

Full Source

Land your next big coding job. Search through 1000's of job listings.

Discussion / Comments / Questions

j
jess
11/16/2017 10:19:51 PM
Hello, Thank you for the explanation however; this code does not work. I cannot even see it in action on your page. Can you please help me?
Walter G.
11/17/2017 7:13:49 AM
Hey there. Seems to work for me! Sent you a message!
M
Mark
12/16/2017 6:16:39 PM
Is there anyway to make the second player the dealer? I've tried to create a dealer instead of a second player and now I nothing is working. Would greatly appreciate some help because your game is awesome.
Walter G.
12/22/2017 8:11:31 PM
Hey Mark, thanks for the comment! I would say that you can handle the dealer role automatically if you update the following function:

    function stay()
        {
            // move on to next player, if any
            if (currentPlayer != players.length-1) {
                document.getElementById('player_' + currentPlayer).classList.remove('active');
                currentPlayer += 1;
                document.getElementById('player_' + currentPlayer).classList.add('active');
            }

            else {
                end();
            }
        }

So once a player decides to "stay" and we check for the last player, if it is indeed the last player, then we can maybe do something like the following: * Have "hitme()" return true or fall. Whether the player lost or not * and in a loop, call hitme() until the player loses pretty much There are only 2 small changes you need to make. Have the "check()" function return true or false Have the hitme function stop once a false is detected.

function check()
        {
            if (players[currentPlayer].Points > 21)
            {
                document.getElementById('status').innerHTML = 'Player: ' + players[currentPlayer].ID + ' LOST';
                return false;
            }

            return true;
        }

And then essentially, for the dealer turn do something like the following:

while (hitme())
{
}

It's essentially an infinite loop, until the check() function return false. Hope that helps!
J
John
4/5/2018 12:38:00 PM
It keeps giving me unexpected identifier at line 12...
J
John
4/5/2018 12:39:25 PM
To clarify that's this code: "if (values[i] == "J" || values[i] == "Q" || values[i] == "K") {" I put them in seperate files :)
Walter G.
12/26/2018 10:53:26 AM
Got it. Check your email!
Walter G.
12/26/2018 10:53:56 AM
See reply!
M
Michael
4/28/2018 9:34:44 AM
Hey Walt, nice game! I was dealt two aces and automatically lost because I wasn't able to split the aces. I'm fairly new to JS, but this might be a nice challenge to try to push my skills. I'll send it your way if I get it.
Walter G.
4/29/2018 10:11:21 AM
Hey there Michael, many thanks for the words. And I did not think of that use case! haha. For sure send it on over if you do!
R
Raisa Shafiyyullah
5/14/2018 9:54:21 PM
Hi, nice tutorial! Thanks!
Walter G.
10/31/2018 7:00:53 PM
Many thanks!
B
Ben
7/24/2018 10:54:58 AM
Thanks for the great tutorials. I went through you deck of cards, and then this Blackjack post, and learned a lot from them! Your final source code at the end of this post doesn't include the icons for suits or the styling of your final project. It also is missing the "restart" button. Any chance you could share the final code? Thanks!
Walter G.
8/3/2018 9:54:32 PM
Many thanks for the words Ben! And I will definitely update the final source code! The tutorial has gone through a few revisions in order to improve readability, and sometimes the final source gets outdated. Thanks for letting me know!
I
IVAN
8/22/2018 4:54:35 AM
Ivan By mistacke i put this comment in the wrong post, but it should go here. 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.
Walter G.
8/22/2018 8:37:56 PM
Ah, no need to return the deck in this example, because I only had one single deck really. I've gone ahead and updated the full source code however, which you can find at the bottom of the page in a zip file!
B
Blake Harris
10/3/2018 7:36:13 PM
I'm making a blackjack game as well. A little different with the code style, however, same outcome. I cannot figure out how to change the Ace to a 1 in certain situations. If i have an Ace-5, it can be 6 or 16. But when I hit it, it doesn't render all the time. Sometimes it'll bust, sometimes it'll change the Ace's value.
Walter G.
10/31/2018 7:11:51 PM
Thanks for the comment Blake. You'll need a special case for the 'Ace'. Just check if it is an Ace and over 21, then increment by +1 instead. So you'll be doing 2 checks. One for an 'Ace' and another for if > 21. Hope that helps!
D
David
1/20/2019 3:20:25 PM
Hey I wanted to try out your program for myself on sandbox in codehs. What would be in the start function of the program and would I use console JavaScript for the program
Walter G.
1/20/2019 9:50:37 PM
Hey there David! Thanks for the comment. I have updated the code with the start() function, and you can also download the full source at the link right below the post! The full HTML/CSS and JavaScript will be there in a zip file!
B
B H
1/28/2019 10:55:09 PM
In the tutorial and the Full Source, the 'players' variable is set to 'new Array()' when the variable is declared and then again when it is first used in the 'createPlayers' function. Is there a reason for setting the value to an empty array both times?
Walter G.
1/30/2019 9:15:27 AM
Ah, good question. When I declared the variable, I set it as a new Array so that I can see the data type immediately. And in the createPlayers function, I'm pretty much just clearing out the array before I add any new players to it.
L
Lawrence
2/6/2019 3:05:55 AM
Thanks Walt for this post. I wanna ask on the dealHands() if i want the players to have specific cards rather than assign them randomly. How do i go about it?
Walter G.
2/7/2019 9:52:39 AM
Many thanks Lawrence. That is an interesting addition to it. I would say, create a new function to deal the card that you want, so something like: function deal(suit, value) { ... similar to the random logic, but instead looking for suit - value specified and pushing/popping that card specifically } And that way ,all you would need to do is just to replace that one function and it should work! Hope that made sense!
L
Lynda
11/13/2019 6:03:11 PM
Hey, the code that you provided only displays the first initial set up without any user or user cards! Could you please email me the latest full source? Thank you.
Walter G.
11/18/2019 12:16:49 PM
Hey there Lynda! Check your inbox really soon 👍

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post comment