Problem of the Day
A new programming or logic puzzle every Mon-Fri

Blackjack Dealer

Today's goal is to build the AI for a blackjack dealer. A blackjack dealer has the following rules (taken from Wikipedia): "The dealer has to take hits until his or her cards total 17 or more points. (In some casinos, the dealer also hits on a "soft" 17—e.g., an initial ace and six.)". In our case we will be hitting on soft 17. Good luck!

Permalink: http://problemotd.com/problem/blackjack-dealer/

Comments:

  • bumbleguppy - 10 years, 2 months ago

    Funny enough, I have been working on a javascript/HTML card game. This is adapted from what I have so far.

        var CARD_DECK = [2,3,4,5,6,7,8,9,10,11,12,13,14,2,3,4,5,6,7,8,9,10,11,12,13,14,2,3,4,5,6,7,8,9,10,11,12,13,14,2,3,4,5,6,7,8,9,10,11,12,13,14];
    var HIGH_CARD = 14;
    
    //shuffles array, stolen from underscore.js
    function shuffle(array) {
      var length = array.length;
      var i = 0;
      var shuffled = new Array(length);
      var rnd = Math.random;
      var floor = Math.floor;
      var rand = 0;
      for (; i < length; ++i) {
        rand = floor(rnd() * i);
        if (rand !== i) shuffled[i] = shuffled[rand];
        shuffled[rand] = array[i];
      }
      return shuffled;
    }
    
    function getBlackJackHandValue(faces) {
      var sum = 0;
      var ace = 0;
      var i = faces.length;
      while(i--) {
        if (faces[i] === HIGH_CARD) {
          ++ace;
          ++sum;
        } else {
          sum += faces[i] < 11 ? faces[i] : 10;
        }
      }
      while (ace--) {
        if (sum + 10 <= 21) {
          sum += 10;
        }
      }
      return sum;
    }
    
    function scoreHand(hand, lastDealt) {
      var score = getBlackJackHandValue(hand);
      var soft17 = (score === 17 && hand.indexOf(HIGH_CARD) > -1);
      var i = lastDealt;
    
      while (score < 17 || soft17) {
        ++i;
        hand.push(CARD_DECK[i]);
        score = getBlackJackHandValue(hand);
        soft17 = false;
      }
    
      return score;
    }
    
    function getDealerScore() {
      shuffle(CARD_DECK);
      var dealerHand = [CARD_DECK[0], CARD_DECK[1]];
      var result = scoreHand(dealerHand, 1);
      return result;
    }
    
    console.log(getDealerScore());
    

    reply permalink

Content curated by @MaxBurstein