1

The PHP blackjack script is simple, I have an array of cards and I select a random one and add it and it's also pretty easy to keep the count the hard part comes in with the aces.

Is there any efficient method to counting them except bruteforcing? Theoretically it would be possible (although highly unlikely) to get 4 aces in a row, how would I make it count as 14 and not 44, 34, 24 etc? (closest to 21 without getting over it)

David B
  • 2,688
  • 18
  • 25
Madmadmax
  • 79
  • 3
  • 10
  • 4
    it would be nice to see your code. – Adi Jul 26 '12 at 14:37
  • One could be: always choose the largest one, if exceeded 21 subtract by 10 for a maximum of the number of aces. 4xAces=44->34->24->14 – Alvin Wong Jul 26 '12 at 14:39
  • 1
    Duplicate, for the answer see: http://stackoverflow.com/questions/837951/is-there-an-elegant-way-to-deal-with-the-ace-in-blackjack?rq=1 – Ben Ruijl Jul 26 '12 at 14:41

2 Answers2

2

Something like this to handle the aces:

$total = 0;
// Sort in a way that the aces are last, handle other cards FIRST
foreach($cards as $card)
{
    switch($card)
    {
        case "king":
        case "queen":
        case "jack":
        case "10":
            $total += 10;
            break;

        // Etc, other cards

        case "ace":
            if($total >= 11)
            {
                $total += 1;
            }
            else
            {
                $total += 11;
            }
            break;
    }
}
Richard de Wit
  • 7,102
  • 7
  • 44
  • 54
  • You might want to tweak this slightly, for example, given this 3 card draw: 5, A, 7; you'd bust; when it should really be 13. Of course, if you sort your list so that you're always applying aces last; you'll be OK. – Jim B Jul 26 '12 at 14:54
  • Code does not work properly because $total+=11 executes every time the card isn't an ace but the psuedocode is good and I wrote my code based on this. – Madmadmax Jul 31 '12 at 13:22
0

Because of the rules for aces, a card in blackjack does not have a value by itself. You do not look at each card, determine a value, and add those.

You look at the hand, and determine the value of the hand.

Now when determining the value of a hand, its true for most cards the value is equal to the card number, but you need special logic for face cards and aces.

Therefore: Don't draw "numbers" from your deck, draw "cards", and write a function that evaluates a "hand" (list) of "cards" into a value.

Matt
  • 3,778
  • 2
  • 28
  • 32