A Better Poker Hand Evaluator in C++

Still working on my poker game simulation, and now I got to the hand evaluation part. I had written a small C program to do it a while ago, but taking a look at it now, well, all I can say is it was pretty awful. I didn’t sort the cards on that program, so evaluating all the possible hands was a mess…

I wrote a much cleaner version now (in C++) with sorting upfront. There you go:

class Card{
    int suit;
    int rank;

int compareCards(const void *card1, const void *card2){
    return (*(Card *)card1).rank - (*(Card *)card2).rank;

int evaluateHand(Card hand[]){
            int straight,flush,three,four,full,pairs;
            int k;

            straight = flush = three = four = full = pairs = 0;
            k = 0;

            /*checks for flush*/
            while (k<4&&hand[k].suit==hand[k+1].suit)
            if (k==4)
                flush = 1;

            /* checks for straight*/
            while (k<4&&hand[k].rank==hand[k+1].rank-1)
            if (k==4)
                straight = 1;

            /* checks for fours */
            for (int i=0;i<2;i++){
                k = i;
                while (k<i+3&&hand[k].rank==hand[k+1].rank)
                if (k==i+3)
                    four = 1;

            /*checks for threes and fullhouse*/
            if (!four){
                for (int i=0;i<3;i++){
                    k = i;
                    while (k<i+2&&hand[k].rank==hand[k+1].rank)
                    if (k==i+2){
                        three = 1;
                        if (i==0){
                            if (hand[3].rank==hand[4].rank)
                        else if(i==1){
                            if (hand[0].rank==hand[4].rank)
                            if (hand[0].rank==hand[1].rank)

            if (straight&&flush)
                return 9;
            else if(four)
                return 8;
            else if(full)
                return 7;
            else if(flush)
                return 6;
            else if(straight)
                return 5;
            else if(three)
                return 4;

            /* checks for pairs*/
            for (k=0;k<4;k++)
                if (hand[k].rank==hand[k+1].rank)

            if (pairs==2)
                return 3;
            else if(pairs)
                return 2;
                return 1;

3 thoughts on “A Better Poker Hand Evaluator in C++

    1. Stepan

      Mike, who told you that? It’s called wheel straight or smthn.

      Anyways there is much to hand evaluation than implemented here.


Leave a Reply

Your email address will not be published. Required fields are marked *