Create a JavaScript BlackJack Game

The code you provided is for a simple Blackjack game in HTML and JavaScript. It creates a basic game interface with buttons to start a new game, hit, and stay. When the game starts, the dealer and player are each dealt two cards. The dealer’s second card is hidden, so the player only knows the value of one of the dealer’s cards. The player can then choose to hit (receive another card) or stay (end their turn). If the player’s score exceeds 21, they bust and lose the game. If the player’s score is closer to 21 than the dealer’s score, the player wins. If the player’s score is the same as the dealer’s score, the game is a tie.

The code uses a number of helper functions to make the game logic easier to read and understand. These functions include:

  • createDeck(): This function creates a new deck of cards.
  • shuffleDeck(): This function shuffles the deck of cards.
  • getCardString(): This function returns a string representation of a card.
  • getCardNumericValue(): This function returns the numeric value of a card.
  • getScore(): This function calculates the score of a hand.
  • updateGameMessage(): This function updates the game message in the text area.
  • updateScores(): This function updates the dealer’s and player’s scores.
  • checkForEndOfGame(): This function checks if the game has ended.
  • newGameButton.addEventListener(): This function adds an event listener to the New Game button.
  • hitButton.addEventListener(): This function adds an event listener to the Hit button.
  • stayButton.addEventListener(): This function adds an event listener to the Stay button.
  • shuffleDeck(): This function shuffles the deck of cards.
  • getNextCard(): This function gets the next card from the deck.
  • showStatus(): This function shows the current game status.
  • init(): This function initializes the game.

The code is well-organized and easy to read. The comments help to explain the purpose of each section of code. The code is also modular, which makes it easy to understand and modify.

Overall, the code is a well-written implementation of a simple Blackjack game. It is a good example of how to use HTML, JavaScript, and helper functions to create a functional and engaging game.

<!DOCTYPE html>
<html>

<head>
    <title>Blackjack</title>
    <style>
        body {
            text-align: center;
            font-family: Arial, sans-serif;
        }

        h1 {
            color: #333;
        }

        #text-area {
            margin: 20px auto;
            width: 400px;
            height: 200px;
            border: 1px solid #333;
            padding: 10px;
            overflow-y: scroll;
            background-color: #f7f7f7;
        }

        button {
            display: inline-block;
            margin: 10px;
            padding: 10px 20px;
            font-size: 16px;
        }

        #new-game-button {
            display: inline;
        }

        #text-area::-webkit-scrollbar {
            width: 5px;
        }

        #text-area::-webkit-scrollbar-track {
            background-color: #f7f7f7;
        }

        #text-area::-webkit-scrollbar-thumb {
            background-color: #888;
        }

        #text-area::-webkit-scrollbar-thumb:hover {
            background-color: #555;
        }
    </style>
</head>

<body>
    <h1>Blackjack</h1>
    <div id="text-area"></div>
    <button id="new-game-button">New Game</button>
    <button id="hit-button">Hit</button>
    <button id="stay-button">Stay</button>
    <script>
        // Card variables
        const suits = ["Hearts", "Clubs", "Diamonds", "Spades"];
        const values = [
            "Ace", "King", "Queen", "Jack", "Ten",
            "Nine", "Eight", "Seven", "Six", "Five",
            "Four", "Three", "Two"
        ];

        // DOM variables
        const textArea = document.getElementById("text-area");
        const newGameButton = document.getElementById("new-game-button");
        const hitButton = document.getElementById("hit-button");
        const stayButton = document.getElementById("stay-button");

        // Game variables
        let gameStarted = false;
        let gameOver = false;
        let playerWon = false;
        let dealerCards = [];
        let playerCards = [];
        let dealerScore = 0;
        let playerScore = 0;
        let deck = [];

        // Helper function to create a deck of cards
        function createDeck() {
            return suits.flatMap(suit => values.map(value => ({ suit, value })));
        }

        // Helper function to get the string representation of a card
        function getCardString(card) {
            return `${card.value} of ${card.suit}`;
        }

        // Helper function to get the numeric value of a card
        function getCardNumericValue(card) {
            switch (card.value) {
                case "Ace":
                    return 1;
                case "Two":
                    return 2;
                case "Three":
                    return 3;
                case "Four":
                    return 4;
                case "Five":
                    return 5;
                case "Six":
                    return 6;
                case "Seven":
                    return 7;
                case "Eight":
                    return 8;
                case "Nine":
                    return 9;
                default:
                    return 10;
            }
        }

        // Helper function to calculate the score of a hand
        function getScore(hand) {
            let score = hand.reduce((sum, card) => sum + getCardNumericValue(card), 0);
            let hasAce = hand.some(card => card.value === "Ace");

            if (hasAce && score + 10 <= 21) {
                score += 10;
            }

            return score;
        }

        // Helper function to update the game message in the text area
        function updateGameMessage(message) {
            let dealerHand = dealerCards.map(getCardString).join("\n");
            textArea.innerText = `${message}\n\nDealer has:\n${dealerHand}`;
        }

        // Helper function to update the dealer's and player's scores
        function updateScores() {
            dealerScore = getScore(dealerCards);
            playerScore = getScore(playerCards);
        }

        // Helper function to check if the game has ended
        function checkForEndOfGame() {
            updateScores();

            if (gameOver) {
                while (dealerScore < 17 && dealerScore <= playerScore && playerScore <= 21) {
                    dealerCards.push(getNextCard());
                    updateScores();
                }

                if (playerScore > 21) {
                    playerWon = false;
                } else if (dealerScore > 21) {
                    playerWon = true;
                } else if (dealerScore > playerScore) {
                    playerWon = false;
                } else if (dealerScore < playerScore) {
                    playerWon = true;
                } else {
                    playerWon = false; // Tie goes to the dealer
                }
            }

            if (playerScore > 21) {
                playerWon = false;
                gameOver = true;
            }
        }

        // Event listener for the New Game button
        newGameButton.addEventListener("click", function () {
            gameStarted = true;
            gameOver = false;
            playerWon = false;

            deck = createDeck();
            shuffleDeck(deck);
            dealerCards = [];
            playerCards = [];

            dealerCards.push(getNextCard());
            dealerCards.push(getNextCard());
            playerCards.push(getNextCard());
            playerCards.push(getNextCard());

            newGameButton.style.display = "none";
            hitButton.style.display = "inline";
            stayButton.style.display = "inline";
            showStatus();
        });

        // Event listener for the Hit button
        hitButton.addEventListener("click", function () {
            playerCards.push(getNextCard());
            checkForEndOfGame();
            showStatus();
        });

        // Event listener for the Stay button
        stayButton.addEventListener("click", function () {
            gameOver = true;
            checkForEndOfGame();
            showStatus();
        });

        // Helper function to shuffle the deck of cards
        function shuffleDeck(deck) {
            for (let i = deck.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [deck[i], deck[j]] = [deck[j], deck[i]];
            }
            return deck;
        }

        // Helper function to get the next card from the deck
        function getNextCard() {
            return deck.shift();
        }

        // Function to show the current game status
        function showStatus() {
            if (!gameStarted) {
                updateGameMessage("Welcome to Blackjack!");
                return;
            }

            let dealerCardString = `${getCardString(dealerCards[0])}\n-----`;
            let playerCardString = playerCards.map(getCardString).join("\n");

            updateGameMessage(
                `Dealer has:\n${dealerCardString}\n\n` +
                `Player has:\n${playerCardString} (score: ${playerScore})\n\n`
            );

            if (gameOver) {
                if (playerWon) {
                    updateGameMessage("You win!");
                } else {
                    updateGameMessage("Dealer wins!");
                }
                newGameButton.style.display = "inline-block";
                hitButton.style.display = "none";
                stayButton.style.display = "none";
            }
        }

        // Initialize the game
        function init() {
            newGameButton.style.display = "inline-block";
            hitButton.style.display = "none";
            stayButton.style.display = "none";
            showStatus();
        }

        // Call init function when the page loads
        window.addEventListener("load", init);

    </script>
</body>

</html>