Search code examples
c#blackjack

How to Implement Blackjack Basic Strategy in Easy Way


I'm working on a blackjack game. I want to implement blackjack basic strategy to program in order to help players.

Basic strategy (from blackjackinstitute.com)

http://www.blackjackinstitute.com/store/images/Basic_Strategy_Chart.jpg

I can do it with tons of if statements. For example

if(dealerHand[0] == 2 && playerTotal == 9){

  MessageBox.Show("Hit")

} 

else if(dealerHand[0] == 2 && playerTotal == 10){

  MessageBox.Show("Double Down")

} 

Maybe i can use switch case for it. But i'm not sure. How can I implement it in easy way?


Solution

  • You could implement a simple two-dimensional array:

    var NextPlay[][] rules = new NextPlay[12][99]; // dealer x player
    rules[2][5] = NextPlay.Hit;
    rules[2][6] = NextPlay.Hit;
    // ....
    rules[11][99] = NextPlay.Stay;
    

    and then you can access it:

    var nextPlay = rules[dealerHand[0]][playerTotal];
    

    ATTENTION: I assumed you can save "special hands" with "special values", e.g. two 9 are a "player total" of 99.

    More elegant, but more complex would be some kind of lookup-table, e.g. something like:

    public class Hand
    {
        public int DealerCard { get; set; }
        public int? PlayerTotal { get; set; }
        public int? PlayerCard1 { get; set; }
        public int? PlayerCard2 { get; set; }
        public NextPlay Play { get; set; }
    }
    

    and

    var List<Hand> rules = new List<Hand>();
    rules.Add(new Hand() { DealerCard = 2, PlayerTotal = 5, Play = NextPlay.Stay });
    // ...
    rules.Add(new Hand()
       { DealerCard = 11, PlayerCard1 = 9, PlayerCard2 = 9, Play = NextPlay.Stay });
    

    and then look it up:

    var nextPlay = rules.FirstOrDefault(h => h.DealerCard == dealerHand[0] &&
                       h.PlayerCard1 == playerHand[0] && h.PlayerCard2 == playerHand[1]);
    if (nextPlay == null)
    {
        nextPlay = rules.FirstOrDefault(h => h.DealerCard == dealerHand[0]
                      && h.PlayerTotal == playerTotal);
    }
    var play = nextPlay.Play;