Click here to Skip to main content
15,868,164 members
Articles / Programming Languages / C#
Article

Poker logic in C#

Rate me:
Please Sign up or sign in to vote.
2.58/5 (13 votes)
5 Sep 20044 min read 154.4K   8.3K   42   9
Compute poker probabilites with a poker simulation in C#.

Introduction

This code snippet will let you calculate poker probabilities the hard way, using C# and .NET. Along the way, you will learn:

  • Enums and how they can help eliminate clutter.
  • How to use IComparable in a real world situation.
  • How to score a poker hand.
  • How to calculate poker probabilties with math.

Points of Interest

Enums: In the code, enumerators form the basis of the two main domain concepts that make up a card: the rank and the suit.

C#
enum SUIT { None, Diamonds, Hearts, Clubs, Spades }
enum RANK { None, Ace, Two, Three, Four, Five, Six, Seven, Eight,
    Nine, Ten, Jack, Queen, King }

By using enumerators, the initialization code that fills out the 52 cards in a standard deck is nothing more than two simple foreach statements. The code is complicated only by the fact that you must allow for a card not to have a default rank when it is created.

Notice, the call to the static method Enum.GetValues returns an Array, which is suitable for a foreach statement.

C#
foreach(SUIT s in Enum.GetValues(typeof(SUIT)))
    foreach(RANK r in Enum.GetValues(typeof(RANK)))
        if (r!=RANK.None && s!=SUIT.None)
            d[counter++] = new Card(r,s);

The only trick to this method is the typeof call which is needed to get the type of the enumerator for the method call.

The code also uses an enumerator to define the different poker hands that you can get. The most interesting use of the POKERSCORE enumerator comes in the Stats class.

In the Append method, a POKERSCORE is cast into an int that is used as an index into an array that keeps scoring information.

In the Report method, the call to the static method Enum.GetName gets the string value associated with each POKERSCORE.

C#
for(int i=0;i<counts.Length;++i)
{
    Console.WriteLine("{0,-10}\t{1,10}\t{2,10:p4}",
            Enum.GetName(typeof(POKERSCORE),i),
            counts[i],
            counts[i]/(double)_simCount);
}

This is another example of how C# lets you use words and phrases from the problem domain in your program.

IComparable: In order to make scoring a poker hand easier, we must sort the poker hand by rank. This will force pairs and other groups to appear that will let us take shortcuts in scoring the hand. In .NET, the Array.Sort method will handle the sorting for you, as long as the elements in the Array implement the IComparable interface. In the code, we implement CompareTo and use the _rank variable to determine the sort position.

The only problem that the example code presents with this arrangement is that in poker, an Ace is scored differently depending on the poker hand. For instance, a straight that starts with an Ace looks like this: A2345; but a straight that ends with an Ace looks like this: TJQKA. In both cases, we sort an Ace lower in the array since we are using the enum to determine the sort order. So, when we are scoring a straight, we must check for a special case.

Scoring a poker hand: In the code, the poker hand is scored in the static method score found in the class PokerLogic. The order of the calls and the fact that the scores are mutually exclusive is important.

The scoring happens in reverse order. A four of a kind is also a pair. In the domain of poker, a four of a kind is more desirable, and so should be the correct score.

Scoring a poker hand with math: You can look up all types of reference on Google on poker probability. Most of them do not list the Jacks or better case.

The total number of possible pairs is given by 52 choose 5 or 2,598,960 possible choices.

To get the total number of possible hands for Jacks or better, you must do the following:

  1. Choose 1 of the 4 possible choices for the pair (Ace, Jack, Queen, or King).
  2. Pick two suits for this pair.
  3. Pick 3 cards from the remaining 12 ranks.
  4. Choose one suit for each of the last three cards.

This will give you 337,920 possible hands with Jacks or better.

In our simulation, we should see around 13% (337,920/2,598,960) of the hands counted as Jacks or better.

By default, when you run the application, it will run 5000 poker hands and produce statistics to the screen. You may also run it with a single command line parameter that will be the number of hands dealt.

You must run the simulation for at least 100,000 hands to get a true picture of what the percentages will be.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Suggestiongood site Pin
Member 1097221225-Jul-14 16:37
Member 1097221225-Jul-14 16:37 
GeneralMy vote of 2 Pin
Jcmorin3-Mar-11 7:14
Jcmorin3-Mar-11 7:14 
GeneralRe: My vote of 2 Pin
Jesse Chunn7-May-18 7:35
Jesse Chunn7-May-18 7:35 
GeneralMy vote of 5 Pin
blackjack215028-Nov-10 7:30
blackjack215028-Nov-10 7:30 
JokeNice but... Pin
pi_co6-Feb-09 3:54
pi_co6-Feb-09 3:54 
GeneralDemo will install downloader Virus on your computer Pin
marcco41124-Sep-08 4:40
marcco41124-Sep-08 4:40 
Generalvery nice Pin
18-Jan-05 13:11
suss18-Jan-05 13:11 
i havent been looking around too long, but i have seen some very complicated and messy approaches to determining the rank of a hand.

i love this approach - very simple and great use of the IComparable and sorting functionality in .net

great job
GeneralNumber of players Pin
netclectic14-Nov-04 22:28
netclectic14-Nov-04 22:28 
GeneralRe: Number of players Pin
ipp1-Jul-05 20:44
ipp1-Jul-05 20:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.