Play Blackjack in your Browser Console! ♠️♥️♦️♣️

November 6, 2024 (4mo ago)

How to Play:

Instructions:

  1. Open your browser's developer tools (right-click → Inspect or press F12).
  2. Go to the "Console" tab.
  3. Copy and paste the following code to start a blackjack game!
(function() {
  function getCard() {
    const cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11];
    return cards[Math.floor(Math.random() * cards.length)];
  }
 
  function handTotal(hand) {
    let total = hand.reduce((a, b) => a + b, 0);
    hand.filter(card => card === 11).forEach(() => {
      if (total > 21) total -= 10;
    });
    return total;
  }
 
  function playBlackjack() {
    let playerHand = [getCard(), getCard()];
    let dealerHand = [getCard(), getCard()];
 
    function showHands() {
      console.log(`Your hand: ${playerHand.join(", ")} (Total: ${handTotal(playerHand)})`);
      console.log(`Dealer's hand: ${dealerHand[0]}, ?`);
    }
 
    showHands();
 
    while (true) {
      const action = prompt("Type 'hit' to draw another card or 'stand' to hold your hand:");
      if (action.toLowerCase() === 'hit') {
        playerHand.push(getCard());
        console.clear();
        showHands();
        if (handTotal(playerHand) > 21) {
          console.log("Bust! You went over 21. Dealer wins!");
          return;
        }
      } else if (action.toLowerCase() === 'stand') {
        break;
      } else {
        console.log("Invalid input. Please type 'hit' or 'stand'.");
      }
    }
 
    while (handTotal(dealerHand) < 17) {
      dealerHand.push(getCard());
    }
 
    console.clear();
    console.log(`Your final hand: ${playerHand.join(", ")} (Total: ${handTotal(playerHand)})`);
    console.log(`Dealer's final hand: ${dealerHand.join(", ")} (Total: ${handTotal(dealerHand)})`);
 
    const playerTotal = handTotal(playerHand);
    const dealerTotal = handTotal(dealerHand);
 
    if (dealerTotal > 21 || playerTotal > dealerTotal) {
      console.log("Congratulations! You win!");
    } else if (playerTotal === dealerTotal) {
      console.log("It's a tie!");
    } else {
      console.log("Dealer wins!");
    }
  }
 
  playBlackjack();
})();