How to Code Poker Hands – Comparing Hands For A High Card

Welcome!

The last article introduced you to writing code to compare two poker hands. You learned that when comparing poker hands of different ranks, the one with the higher rank wins (a full house beats a three of a kind). But what happens when you have poker hands that are the same rank? 🤔

In this article you’ll learn how to compare the lowest ranking poker hand, a high card.

A high card hand doesn’t fall into any of the other categories, such as a pair, two pair, three of a kind, straight, etc. When determining the type of hand, if it doesn’t match any of the poker hands, it’s automatically a high card hand.

When you compare high card hands, the one with the highest ranking card wins. If they have the same highest ranking card, then you compare the next highest-ranking card and so on.

Before comparing hands, sorting the cards in order of descending rank first makes the comparisons much easier. But instead of putting wild cards at the end, they’ll go at the beginning. We’ll cover this in more details later in this article.

Let’s have a look at these two hands:

As you can see, the first four cards both hands are of the same value. We get to the final card, and the second hand’s three beats the first hand’s two. So, the second high card hand beats the first one.

Setup

Note: The first stages of the setup can be found on the introduction page to comparing poker hands here.

In many of the hand comparisons, wild cards can be treated as the highest card value, because they can assume any value. So, it will assume the highest card value possible while still satisfying the poker hand (this would’ve already been determined when matching the poker hand). You may recall when matching poker hands, we sorted the cards in descending order, with the wild cards as the lowest value, ordering them at the end of the sorted hand. However, when comparing poker hands, the wild cards will be the highest value, ordering them at the beginning of the sorted hand.

From there, you’ll need a new, albeit simpler sort function. And because this sort will be used by multiple poker hand comparisons, you can put it in your CardMatchUtils class as a function:

SortCardsByDescendingValueHighWilds
CardMatchUtils.SortCardsByDescendingValueHighWilds = function(hand) {
  var sortedHand = hand.concat();
  sortedHand.sort(CardMatchUtils.OnSortCardsByDescendingValueHighWilds);
}
OnSortCardsByDescendingValueHighWilds
function CardMatchUtils.OnSortCardsByDescendingValueHighWilds(card1, card2) {
  if (card1.value < card2.value) {
    return(1);
  } else if (card1.value > card2.value) {
    return(-1);
  }
  
  return(0);
}

In the main function, SortCardsByDescendingValueHighWilds, a copy of the hand parameter, which is an array of Card objects.

The sort function is called on the array, along with a callback function, OnSortCardsByDescendingValueHighWilds, that specifies how the cards should be ordered. When this function returns a number greater than zero, card2 should be placed before card1 (card2 has a higher value). If the function returns a number less than zero, card1 should come first. And if the function returns zero, then both cards have equal value, and their sort order against each other doesn’t matter.

Writing The Code For Comparing High Card Hands

Since this article focuses on the high card hand only, it assumes that from the GetWinningHand function, the poker hands are the same rank, which happens to be the high card.

The GetWinningHand function will eventually call FindWinnerHighCard to compare two high card hands. FindWinnerHighCard is the main topic of discussion for this article. It accepts two parameters, the hand for both players, and it’ll return the ID of the player who has the winning high card hand. If both hands are equal, it’ll return 0 (which we’ll use to mean a draw). So let’s dive in with some pseudocode. 🙂

FindWinnerHighCard
FindWinnerHighCard = function(hand1, hand2) {
  sortedHand1 = CardMatchUtils.SortCardsByDescendingValueHighWilds(hand1);
  sortedHand2 = CardMatchUtils.SortCardsByDescendingValueHighWilds(hand2);
  
  FOR (index = 0; index < sortedHand1.length; index++) {
    card1 = sortedHand1[index];
    card2 = sortedHand2[index];
    
    IF (card1.value > card2.value)
      RETURN PlayerId1;
    ELSE IF (card1.value < card2.value)
      RETURN PlayerId2;
    END
  }
  
  RETURN 0;
}

This function first sorts the cards in descending card value, with wild cards ordered first. Next, it compares the first card of each hand to determine the winner. If both cards are the same, it compares the second card, and so on. It does this until it finds a winning card, or all cards in both hands have been compared. If the latter is the case, then both cards are of equal rank, and the function returns 0.

That’s pretty much it for comparing two hands for the highest card. ✔

Compare Your Own Hands

You can use the controls below to build your own hands and compare high cards. Have some fun playing around with it, and if you find an issue, please let me know!


Player 1

Result:

Player 2

Result:

Player 3

Result:

Who Won:

If you have any questions about recognizing a royal flush, or the above interaction, please let me know at cartrell@gameplaycoder.com.

That’s it for now! Thanks, and the next article in the series will cover comparing hands that have a pair of jacks or higher.

– C. out.

How to Code Poker Hands – Comparing Hands

Now that the poker hands have been covered, there is another set of functionality to cover. When two poker hands are compared, which one wins?

This series presented the hands in order of lowest rank to highest rank. So they are ranked like this:

  1. Pair (Jacks or higher)
  2. Two pair
  3. Three of a kind
  4. Straight
  5. Flush
  6. Full house
  7. Four of a kind
  8. Straight flush
  9. Royal flush

In earlier articles, you may have noticed in the “Build Your Own Hand” section that you could have a four of a kind, which is also a three of a kind, or even a pair. But the four of a kind was the result. This is because a four of a kind ranks higher than a three of a kind, which ranks higher than and a pair.

Or you may have formed a full house, which is also a pair, a three of a kind, and even a two pair. The full house beats the three of a kind, which beats the two pair, which beats the pair.

This is happening because even if a hand contains multiple matches, the highest ranking one will always be picked. The next set of articles of the poker hand-matching series cover writing game code to determine the highest ranking poker hand between two hands.

If I may digress for a moment, the new “Build Your Own Hand” will look something like this, so you can compare two hands to each other:

You could do something like this, by adding all the previous psuedocode function for matching poker hands, and running them on the player’s hand. You’d run them in order of highest to lowest rank, because you want to find the first poker hand that matches the player’s hand.

Have a look at this code:

GetPokerHand
GetPokerHand = function(hand) {
  IF RoyalFlush(hand)
    RETURN PokerHandIds.RoyalFlush
  ELSE IF StraightFlush(hand)
    RETURN PokerHandIds.StraightFlush
  ELSE IF FourOfAKind(hand)
    RETURN PokerHandIds.FourOfAKind
  ELSE IF FullHouse(hand)
    RETURN PokerHandIds.FullHouse
  ELSE IF Flush(hand)
    RETURN PokerHandIds.Flush
  ELSE IF Straight(hand)
    RETURN PokerHandIds.Straight
  ELSE IF ThreeOfAKind(hand)
    RETURN PokerHandIds.ThreeOfAKind
  ELSE IF TwoPair(hand)
    RETURN PokerHandIds.TwoPair
  ELSE IF JacksOrBetterPair(hand)
    RETURN PokerHandIds.JacksOrBetterPair
  END

  RETURN PokerHandIds.HighCard
}

The above code will return a value that tells you what type of poker hand the players hand is. But, look at these PokerHandIds.HandIsRoyalFlush, PokerHandIds.HandIsStraightFlush, and such pieces. What are those?

There needs to be a way to uniquely identify each poker hand, hence these “poker hand IDs”. You’ll assign each poker hand a unique ID. This brings us to the first part of the setup.

Setup
Poker Hand IDs

Let’s create a new data object, PokerHandIds, and similar to CardValues and CardSuits, we’ll assign it some properties.

PokerHandIds = {
  HighCard: 0,
  JacksOrBetterPair: 1,
  TwoPair: 2,
  ThreeOfAKind: 3,
  Straight: 4,
  Flush: 5,
  FullHouse: 6,
  FourOfAKind: 7,
  StraightFlush: 8,
  RoyalFlush: 9
};

Note: The HighCard means a hand that is not any poker hand. It’s of the lowest value, and the GetPokerHand function defaults to returning HighCard if the specified hand doesn’t match any of the poker hands.

Writing The Code To Compare Poker Hands

So you might be able to see where this is going. To compare two poker hands to find the higher-ranking one, you get the poker hand ID of both hands, then compare those IDs.

Say you have two players and their hands are stored in hand1 and hand2. The code for matching them might look something like this:

GetWinningHand
GetWinningHand = function(hand1, hand2) {
  hand1PokerId = GetPokerHand(hand1);
  hand2PokerId = GetPokerHand(hand2);

  IF (hand1PokerId > hand2PokerId)
    RETURN PlayerId1 ("player 1 wins")
  ELSE IF (hand2PokerId > hand1PokerId)
    RETURN PlayerId2 ("player 2 wins")
  END

  RETURN GetWinningPlayerId(hand1, hand2, hand1PokerId)
}

Note: The PlayerId1 and PlayerId2 are just used to uniquely identify which player we are referring to.

If one ID is bigger than the other, it’s pretty easy to determine which player wins. But what if both hands are the same rank, for instance, both are flushes, or both are two pairs? It’s not necessarily a “draw”, because you’ll need to do some additional checking on each hand to determine which flush, for example wins, or which two pair wins. And this type of comparison depends on the poker hand.

This new GetWinningPlayerId function accepts three parameters: both players’ hands, and the poker hand ID. (It doesn’t matter if you use either hand1PokerId or hand2PokerId, because they’re both the same.) And GetWinningPlayerId looks like:

GetWinningPlayerId
GetWinningPlayerId = function(hand1, hand2, pokerHandId) {
  IF pokerHandId EQUALS PokerHandIds.HighCard
    RETURN FindWinnerHighCard(hand1, hand2)
  ELSE IF pokerHandId EQUALS PokerHandIds.JacksOrBetterPair
    RETURN FindWinnerJacksOrBetterPair(hand1, hand2)
  ELSE IF pokerHandId EQUALS PokerHandIds.TwoPair
    RETURN FindWinnerTwoPair(hand1, hand2)
  ELSE IF pokerHandId EQUALS PokerHandIds.ThreeOfAKind
    RETURN FindWinnerThreeOfAKind(hand1, hand2)
  ELSE IF pokerHandId EQUALS PokerHandIds.Straight
    RETURN FindWinnerStraight(hand1, hand2)
  ELSE IF pokerHandId EQUALS PokerHandIds.Flush
    RETURN FindWinnerFlush(hand1, hand2)
  ELSE IF pokerHandId EQUALS PokerHandIds.FullHouse
    RETURN FindWinnerFullHouse(hand1, hand2)
  ELSE IF pokerHandId EQUALS PokerHandIds.FourOfAKind
    RETURN FindWinnerFourOfAKind(hand1, hand2)
  ELSE IF pokerHandId EQUALS PokerHandIds.StraightFlush
    RETURN FindWinnerStraightFlush(hand1, hand2)
  END IF

  RETURN FindWinnerRoyalFlush(hand1, hand2)
}

Depending on which player’s hand won, GetWinningPlayerId would return either PlayerId1 or PlayerId2.

It is also possible that both player hands, could the same rank, in cards, as well as poker hand. In that case, the match up really is a draw. So GetWinningPlayerId would return neither PlayerId1 nor PlayerId2, but Draw.

And these FindWinner... functions is where all the real fun of finding which poker had wins is! 😉 And like matching poker hands, you’ll be learning those in the next set of articles. So stay tuned for more!

That’s it for now. Talk you next time, and take care,

– C. out.

How to Code Poker Hands – Royal Flush

Well, if you’ve read the entire series, congrats! You’ve reached the final poker hand we’re covering, the royal flush! ⭐

A royal flush is a specialized version of the straight flush, so let’s quickly go over the straight flush first.

A straight flush is a combination of a straight and a flush. A straight is where the cards are in sequential order by value, and there are least two different suits among the cards. And a flush is where all cards in the hand have the same suit, and are not in sequential order by value.

So then, a straight flush is a hand where the cards are in order by rank, and they all have the same suit.

Now, back to the royal flush. It’s a special type of straight flush where the highest card is an ace. The image featured at the top of this article is a royal flush.

Before continuing, you can review the poker hands that have already been covered by following any of the links below:

Setup

If you’ve been following the series, you’ve probably got this part burned into your memory by now, haha! Of course, they are briefly discussed here, but you check out this link . Otherwise, if you’d like to skip ahead, check here.

Card Values
CardValues = {
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  jack: 11,
  queen: 12,
  king: 13,
  ace: 14,
  wild: 100
};
Card Suits
CardSuits = {
  hearts: 1,
  diamonds: 2
  clubs: 3,
  spades: 4
};
Card
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

And a hand is an array of Card objects:

var hand = [
  new Card([card value 1], [card suit 1]),
  new Card([card value 2], [card suit 2]),
  ...
  new Card([card value 5], [card suit 5])
];
Writing The Code To Identify A Straight Flush

We’ll start with writing code for a straight flush, because it’s a easier than the royal flush. The pseudocode for matching a straight flush looks like:

Straight Flush
StraightFlush = FUNCTION(hand) {
  SORT the hand by descending card value and store in a variable called sortedHand

  IF AreCardsStraight(sortedHand) AND AreCardsFlush(sortedHand)
    //we have a straight flush!
    RETURN TRUE 

  //no straight flush in this hand
  RETURN FALSE
}

Most of the code has already been written, thanks to the CardMatchUtils file that contains three functions:

If you’re new to the series, we previously defined a “utilities” file, named CardMatchUtils.js. This file is shared by all the poker hand matching functions, because it contains a several functions that they all use, and sorting the cards by their descending value makes performing the card-matching functions much easier.

So after sorting the cards in the hand, you want to check if the cards are both a straight and a flush. If so, the hand is a certifiable straight flush. Super easy 😎

Royal Flush

As I mentioned before, a royal flush is a special version of the straight flush, where the ace is the high card.

The royal flush would be a simple modification of adding a check to see if the first card of the sorted hand is an ace, and if so, you’d have a royal flush. However, we’re using wild cards, and they will throw a 🐒 🔧 into that plan.

First, let’s consider this hand:

Once you’ve successfully determined that the hand is a straight flush, check the first card. As long as it’s an Ace, you’re good to go.

Because wild cards are already handled in both CardMatchUtils.AreCardsStraight AND CardMatchUtils.AreCardsFlush, you don’t need to do anything specific for wild cards here.

However, what if you had a straight flush where the high card is not an ace, and wilds are present instead? Consider these hands:

All of these hands are royal flushes because of the wild cards!

If you look at what’s going on, for each wild card in the hand, the high card is the value of the ace, minus the number of wild cards in the hand. For example, if there is one wild, the high card (the first card in the hand) must be ace – 1 = king. You can use the numeric values defined in CardValues to do the math. If there are, say three wilds, the high card must be ace – 3 = jack.

However, for the last hand with five wilds, this won’t work. If you took ace – 5, we’d have 9. And the high card is a wild, and CardValues.nine != CardValues.wild.

Back when you setup CardValues, you gave CardValues.wild an arbitrary, super-high numeric value (in this case, 100). So when checking that high card, you’ll want to use a greater-than-or-equal-to comparison, instead of equal-to.

So, the royal flush pseudocode looks like this:

RoyalFlush
RoyalFlush = FUNCTION(hand) {
  SORT the hand by descending card value and store in a variable called sortedHand

  IF NOT AreCardsStraight(sortedHand) OR NOT AreCardsFlush(sortedHand)
    //no royal flush in this hand - must be both straight and flush to be considered
    RETURN FALSE

  get number of wilds in the hand and store in a variable called numWilds
  get the max card value by subtracting numWilds from the ace value (CardValues.ace) and store in a variable called maxCardValue
  get the first card in the sorted hand (array)
  IF the value of this card is GREATER THAN OR EQUAL TO maxCardValue
    //this hand is a royal flush
    RETURN TRUE

  //no royal flush in this hand
  RETURN FALSE
}
Build Your Own Hand

You can use the controls below to create your own hand to see if it is a royal flush or a straight flush. It will also recognize previous poker hands we’ve covered up to this point. Have fun playing around with it!


Result:

If you have any questions about recognizing a royal flush, or the above interaction, please let me know at cartrell@gameplaycoder.com.

That’s all for this article, and also for the poker hands series. Congrats for getting through all of them! ⭐⭐ You should now have a solid idea on how to write code to identify poker hands in a five-card hand.

Thanks, and stay tuned for more articles!

– C. out.

How to Code Poker Hands – Four Of A Kind

Hello!

You’ve seen the pair (two of a kind), three of a kind, so guess what’s coming next?

Yep… four of a kind! (:

Programming the match for this hand is very similar to that of a three of a kind.

Ok first, you can review the poker hands that have already been covered by following any of the links below:

Setup

Before we begin writing the main code, here are some data structures you’ll be using. They are briefly discussed here, but if you’d like the full details, check out this link. Otherwise, if you’d like to skip ahead, please click here.

Card values
CardValues = {
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  jack: 11,
  queen: 12,
  king: 13,
  ace: 14,
  wild: 100
};
Card suits
CardSuits = {
  hearts: 1,
  diamonds: 2
  clubs: 3,
  spades: 4
};
Card
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

A “hand” is not a custom data structure like the ones above, but an array of Card objects:

var hand = [
  new Card([card value 1], [card suit 1]),
  new Card([card value 2], [card suit 2]),
  ...
  new Card([card value 5], [card suit 5])
];
Writing The Code To Identify A Four Of A Kind

A four of a kind is similar very much like a three of a kind. We’re looking for four cards of the same value (rank) instead of three.

First, sort the cards by their rank, in descending order. We previously defined a “utilities” file, named CardMatchUtils.js, and added a function to it called, CardMatchUtils.SortCardsByDescendingValue, which can perform the sorting. If you’re just joining this series, CardMatchUtils.js is a file that is shared by all the poker hand matching functions, because it contains a several functions that they all use. CardMatchUtils.SortCardsByDescendingValue is one of those functions, because sorting a hand by the ranks of its cards in descending order helps to make the poker hand matching much easier.

The CardsHaveSameValue utilities function, previously written here, determines if a certain number of cards in the hand have the same rank. In this case, we want to check for four cards.

We’re also using the “wild card”, which is a card that can assume the rank of any card. So, the following hand would also qualify as a four of a kind:

After sorting the cards by their card rank in descending order, the hand looks like:

Wild cards are always sorted at the end of the hand.

There are a pair of fives already, and the two wilds will assume another pair of fives.

The pseudocode for matching a four of a kind looks like:

FourOfAKind = FUNCTION(hand) {
  SORT the hand by descending card value and store in a variable called sortedHand

  IF CardsHaveSameValue(sortedHand, 4)
    //we have a three of a kind!
    RETURN TRUE 

  //no four of a kind in this hand
  RETURN FALSE
}

The CardsHaveSameValue function does most of the work here, and you can review that function to see how it functions.

Build Your Own Hand

You can use the controls below to create your own hand to see if it is a four of a kind. It will also recognize previous poker hands we’ve covered up to this point. Have fun playing around with it!


Result:

If you have any questions about recognizing a four of a kind, or the above interaction, please let me know at cartrell@gameplaycoder.com.

That’s all for this article. Thanks, and stay tuned as this series continues!

– C. out.

How to Code Poker Hands – Full House

Hey there,

We’re almost done with coding solutions for determining the various hands in the card game of poker. In this article, you’ll learn how to code the solution for the full house.

A full house is a hand that contains a pair of cards on one value (rank), and a three of a kind of another value.

You can check out the poker hands that have already been covered, using the links below:

Setup

Continuing the trend in the series, yep, you guessed it, the code setup has not changed. 🙂

A brief summary of the setup is below. If you’d like to skip ahead of this section, click here. If you want to see the full details of the setup, check out this link.

Card Values
CardValues = {
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  jack: 11,
  queen: 12,
  king: 13,
  ace: 14,
  wild: 100
};
Card Suits
CardSuits = {
  hearts: 1,
  diamonds: 2
  clubs: 3,
  spades: 4
};
Card
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

A hand is an array of Card objects:

var hand = [
  new Card([card value 1], [card suit 1]),
  new Card([card value 2], [card suit 2]),
  ...
  new Card([card value 5], [card suit 5])
];
Writing The Code To Identify A Full House

Although the full house is essentially a pair and a three of a kind combined into one hand, it’s a little more of a challenge, especially when wild cards are involved.

Just as with coding solutions for the other poker hands, first make sure the cards in your hand are sorted by descending value.

Also, we’ll be using the utilities class, CardMatchUtils. This is the class we’ve been building that contains common functionality used across all poker hands.

There are two specific functions that CardMatchUtils will use:

Now let’s get into some pseudo code! 😎

The function takes one parameter, sortedHand which a hand that has already been passed to CardMatchUtils.SortCardsByDescendingValue, and the result being used as this parameter.

Writing out the main function for a full house looks like this:

AreCardsFullHouse = FUNCTION(sortedHand) {
  //check for an x-x-x-y-y full house
  IF the first three cards have the same value AND the last two cards have the same value, but different from the first three
    RETURN TRUE (this hand has a full house)
  END IF

  //check for an x-x-y-y-y full house
  IF first two cards have the same value AND the last three cards have the same value, but different from the first two
    RETURN TRUE (this hand has a full house)
  END IF

  RETURN FALSE (this hand does not form a full house)
}

When the cards are sorted by descending value, there are two possible combinations for a full house. The first one is if the three of a kind comes first, followed by a pair, and it looks like this:

The second combination is if the pair comes first, followed by the three of a kind:

And if you have a wild card with a two pair, that also forms a full house:

The wild could assume a value of 10, thus forming a three of a kind, which is followed by the pair. Wild cards are always placed at the end of the hand when sorted.

Also, because of those blasted wild cards (damn you, (: ), they can be used in either the three of a kind or the two pair, and we need to keep track of who many wild cards are left remaining, while the AreCardsFullHouse function is running.

CardMatchUtils.DoCardsHaveSameValue is a function that determines if a certain number of cards in the hand have the same value. The function takes three parameters:

  • sortedHand – The hand, already assumed to be sorted in descending order by card rank.
  • numToMatch – The number of cards that must have the same value.
  • wildsInfo – An object that stores information about the wild cards.

The wildsInfo parameter is used to save information for multiple calls to CardMatchUtils.DoCardsHaveSameValue. First declare an empty object { }. The first time you call the function, you’d pass in this empty object. On subsequent calls to CardMatchUtils.DoCardsHaveSameValue, you’d pass in the same object.

While CardMatchUtils.DoCardsHaveSameValue is running, it creates two properties on the wildsInfo object:

  • numWilds – The number of wild cards available for use as substitutes.
  • startIndex – The index of the sortedHand array on which DoCardsHaveSameValue starts when it checks each card in the hand.

These properties are modified and saved while CardMatchUtils.DoCardsHaveSameValue runs. Each subsequent call to this function continues where the previous one left off. For example, if the hand contains one or more wild cards and at least one was used to, say, form a three of a kind, the numWilds will be updated for use in the next call to CardMatchUtils.DoCardsHaveSameValue.

The CardMatchUtils.DoCardsHaveSameValue function is explained in detail here, and you can go back to review it if you want. It’s a rather long one, but it does the brunt of the work of checking for a full house.

Build Your Own Hand

You can use the controls below to create your own hand to see if it is a full house. It will also recognize previous poker hands we’ve covered up to this point. Have fun playing around with it! ⭐


Result:

If you have any questions about recognizing a full house hand, the above interaction, or any of the other poker hands, please let me know at cartrell@gameplaycoder.com.

Finally, if you’d like to hire me to program an actual card game for you, please e-mail me, or use the contact form here.

That’s all for this article. Thanks, and stay tuned as we are almost finished with this series! 💪🏾

– C. out.

How to Code Poker Hands – Flush

Hey there,

In this article, we’re continuing the series of writing code that recognizes the various poker hands. Today, you’ll build the solution for a hand that matches a flush.

A flush is a hand where all five cards are of the same suit, but not in order of sequential rank.

If you’d like to see poker hands that have already been covered, please check the links below.

Setup

The code setup is the same as in the previous articles of this mini-series. A quick rundown of the setup is below, but if you’d like to skip ahead, check here. If you’d like to see the full details of the setup, check out this link.

Card Values
CardValues = {
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  jack: 11,
  queen: 12,
  king: 13,
  ace: 14,
  wild: 100
};
Card Suits
CardSuits = {
  hearts: 1,
  diamonds: 2
  clubs: 3,
  spades: 4
};
Card
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};

And a hand is an array of Card objects:

var hand = [
  new Card([card value 1], [card suit 1]),
  new Card([card value 2], [card suit 2]),
  ...
  new Card([card value 5], [card suit 5])
];
Writing The Code To Identify A Flush

As mentioned before, a flush is a hand where all the cards have the same suit, but their ranks are not in sequential order. Now, programming the flush is one of the easier poker hands to match, because all you’re doing is checking that all the cards have the same suit, using the first card’s suit as the criteria.

But remember, we’re also using “wild cards” here. So far you’ve used them to assume any value (rank), but in the case of a flush, a wild card can also assume any suit.

You don’t necessarily need to sort the cards by descending rank, since the flush is not a value-based hand. However, doing so will programming the matching logic a little easier.

Like you did with the previous hand, the straight, you’ll be adding a function to the “utilities” file, CardMatchUtils.js. In an upcoming article, you’ll program the straight flush, which is a combination of the straight and the flush. So, you’ll add a new function, CardMatchUtils.AreCardsFlush, CardMatchUtils, which will be used by both hands.

There are two functions that CardMatchUtils will use:

  1. CardMatchUtils.SortCardsByDescendingValue – This function sorts the cards in the hand by descending value. This orders the cards from highest value to lowest.
  2. CardMatchUtils.AreCardsFlush – This function has not yet been written (but that’s what you’ll write in this article! 🙂 ) This function will be used in recognizing both, the flush, and the straight flush poker hands.

And without further ado, let’s get into some pseudocode for the flush! It looks like this:

Flush = FUNCTION(hand) {
  SORT the hand by descending card value and store in a variable called sortedHand

  IF AreCardsFlush(sortedHand)
    //we have a flush hand
    RETURN TRUE 

  //this hand is not a flush
  RETURN FALSE
}

This function looks very similar to the AreCardsStraight function from the last article. The bulk of the details is in the AreCardsFlush function. Let’s now have a look at its pseudocode:

AreCardsFlush
AreCardsFlush = FUNCTION(sortedHand) {
  FOR EACH card in the sortedHand {
    IF this card (the current loop card) is the first card being checked {
      set a variable called baseCardSuit to the suit of this card
      re-start FOR loop again with next card (in other words, "continue" if you're familiar with for-loops)
    }

    IF this card is a wild card {
      RETURN TRUE (since cards are already sorted, once we get to a wild card we're done; all preceding cards match the base card suit)
    }

    IF the suit of this card EQUALS the value of baseCardSuit {
      re-start FOR loop again with next card
    } ELSE {
      RETURN FALSE (suit of this card doesn't match the vase card suit - this hand is not a flush)
    }
  }

  RETURN TRUE (all cards have the same suit)
}

This code gets the suit of the first card in the sorted hand, and compares it to the suit of every other card. As long as they match, the loop will continue until it reaches the end, or encounters either a wild card (success), or a card whose suit doesn’t match that of the first card’s (failure).

Say you have a hand that looks like this (after sorting all cards in descending value order, with wild cards at the end):

The first card is the king of hearts, so the “base card suit” will be assigned to value CardSuits.diamonds.
The suit of the second card is spades, which does not match diamonds. So, this hand is not a flush.

Now say we had this hand:

The base card suit is the spade, from the jack of spades. The next two cards are also spades. So far so good. Then then fourth card is a wild. At this point, you can say that this hand is a flush. The cards are already sorted with wilds at the end, and because wilds can assume any suit (in this case, spades), so they will complete the flush. There is no need to continue checking the cards, because they will all be wilds. This is how sorting helps simplify recognizing a flush.

Not too much more to say about programming a flush, since it’s one of the easier hands to identify – even easier than a 🍐, in my opinion.

Build Your Own Hand

You can use the controls below to create your own hand to see if it is a flush or not. It will also recognize previous hands we’ve covered up to this point. Have fun playing around and making various hands!


Result:

If you have any questions about recognizing a flush hand, or the above interaction, please let me know at cartrell@gameplaycoder.com.

Finally, if you’d like to hire me to program an actual card game for you, you can e-mail me, or you may use the contact form here.

That’s it for today. Thanks, and stay tuned because we more poker hands to program. The next one will be the full house!

– C. out.

How to Code Poker Hands – Straight

Continuing the series of writing code that recognizing poker hands, you’ll learn how to code a solution for determining if a hand is a straight.

A straight is a hand where all five cards are in order of sequential rank, meaning each card is the next highest (or lowest) than the one before it.

If you’d like to see poker hands that have already been covered, please check the links below.

Setup

The setup is the same as in the previous articles of this mini-series. A quick rundown of the setup is below, but if you’d like to skip ahead, click here. If you’d like to see the full details of the setup, check out this link.

Card values
CardValues = {
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  jack: 11,
  queen: 12,
  king: 13,
  ace: 14,
  wild: 100
};
Card suits
CardSuits = {
  hearts: 1,
  diamonds: 2
  clubs: 3,
  spades: 4
};
Card
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

A hand is an array of Card objects:

var hand = [
  new Card([card value 1], [card suit 1]),
  new Card([card value 2], [card suit 2]),
  ...
  new Card([card value 5], [card suit 5])
];
Writing The Code To Identify A Straight

As stated earlier, a straight is a hand where each card is one value (rank) above the next card, or below the next card. An easy way to accomplish this is to first sort the cards by descending value, then check that each card is one less than the one before it.

However, the deck being used includes a “wild card”, which can assume any value. So, this makes the challenge a bit more interesting. 😏

Also, in anticipation of recognizing another poker hand that also uses a straight (the straight flush), you can place the function that you’ll be writing (called CardMatchUtils.AreCardsStraight) in the in the “utilities” file, CardMatchUtils.js. This is a file that we’ve been using to assist with matching poker hands in past articles. It contains common functions that can be used across several poker hands, so we don’t have to keep rewriting them for every poker hand.

There are two functions that CardMatchUtils will use:

  1. CardMatchUtils.SortCardsByDescendingValue – This function sorts the cards in the hand by descending value. This orders the cards from highest value to lowest.
  2. CardMatchUtils.AreCardsStraight – This function has not yet been written (but that’s what you’ll write in this article!) This function will be used in recognizing both, the straight, and the straight flush hands.

Let’s start with the pseudo code for the straight. It looks like this:

Straight = FUNCTION(hand) {
  SORT the hand by descending card value and store in a variable called sortedHand

  IF AreCardsStraight(sortedHand)
    //we have a straight!
    RETURN TRUE 

  //this hand is not a straight
  RETURN FALSE
}

It’s short and fairly straightforward. However, the AreCardsStraight function mentioned above is where all the action is. It will determine if the cards are straight, and return TRUE if they are. It takes one parameter, which is a hand (array) of cards, already sorted in descending order, by their values. The pseudo code for the AreCardsStraight function looks like:

AreCardsStraight
AreCardsStraight = FUNCTION(sortedHand) {
  count the number of wild cards in the hand and store in a variable called numWilds (to do this, you can use the `CardMatchUtils.CountCardsByValue` function that was introduced here ( https://gameplaycoder.com/how-to-code-poker-hands-pair-of-jacks-or-higher/#countCardsByValue ) )
  set a variable called currentCardValue to 0

  FOR EACH card in the sortedHand {
    IF this card (the current loop card) is the first card being checked {
      set currentCardValue to the value of this card
      re-start FOR loop again with next card (in other words, "continue" if you're familiar with for-loops)
    }

    subtract the value of currentCardValue from the value of this card and store in a variable called valueDifference
    set currentCardValue to the value of this card

    IF valueDifference EQUALS 1 {
      re-start FOR loop again with next card (the condition for the straight is met so far)
    }

    IF the card is a wild card {
      EXIT FOR LOOP (a wild card can assume any card value, including the next value to satisfy a straight, since)
    }

    if valueDifference EQUALS 0 {
      RETURN FALSE (this card has the same value as the previous card's stored in currentCardValue, the card from the previous loop iteration - this hand is not a straight)
    }

    (check if there are enough wilds remaining to cover the difference in card values)
    IF numWilds GREATER THAN 0 AND numWilds GREAT THAN OR EQUALS valueDifference - 1 {
      (there are enough wilds, deduct that from the number of wilds available, and straight is still satisfied
      numWilds = numWilds - (valueDifference - 1)
    } ELSE {
      RETURN FALSE (there are not enough wilds to cover the range in value between the two cards - this hand is not a straight)
    }
  }

  (straight is satisfied through all cards - success!)
  RETURN TRUE
}

What the AreCardsStraight function does is take the value of the first card, and compare it to the next card’s value. If the value of the next card is one less, then the straight so far is OK, it continues checking cards. The first two card comparisons look like:

If the next card is a wild card it instead of a card whose value is one less, then the wild card will assume the value of the card with the lesser value, and it continues checking cards. Let’s say your hand is a different one, like this:

After sorting the above hand in descending value order, you’d have:

Remember in the sorting algorithm, wild cards are always placed at the end.

Once we arrive at the wild card, we can exit the loop. There is no point in further checking cards, because they will all be wild cards, assuming the next value lowest value. And AreCardsStraight returns TRUE if the end of the loop is reached. This means the hand is identified as a straight, because each card is one less value than the one preceding it.

Once the loop reaches this first wild, we are done, and can conclude that this hand is a straight.

Ok, let’s try another example.

Say you had a hand, and after sorting, looked like this:

Once we get to the queen, the next card is a 10, which is more than one value less than the queen (the jack was expected). Since you have one wild card, you can “use” it as the jack, and the straight would still be satisfied.

But wait…

What if THIS was your hand?

To cover the gap in between the 8 and 6, you’d use the wild as a 7. However, there is another gap in between the 6 and 4. Since you used the wild already – and this hand only has one wild – you can no longer substitute another wild for a 3. So hmm, I’ma ‘fraid this hand would not be a straight. 🤔

Have a look at this hand:

This hand would be a straight, because it contains two wilds to cover both gaps, between the 9 and 7, and another one between the 7 and 5. Yes!

The gaps we’ve looked at only cover a value range of one. Let’s say you had this hand (after sorting):

There are two gaps between the 7 and 4 (6 and 5), we’d need at least two wilds to cover them both. Since this hand only has one, it’s not a straight.

One more:

This hand would be a straight because it has enough wilds (at least three) to cover for the 9, 8, and 7. I know I’m getting pretty wild with wilds here, but it illustrates the point of using wild cards to support any hand to find a straight.

Build your own Hand

Like in the last article, you can use the controls below to create your own hand to see if it is a straight or not. It will also recognize previous hands we’ve covered up to this point, which are pairs (jacks or higher), two pair, and three of a kind.


Result:

If you have any questions about recognizing a straight hand, or the above interaction, please let me know at cartrell@gameplaycoder.com.

Finally, if you’d like to hire me to program an actual card game for you, please e-mail me, or you may use the contact form here.

That’s it for now. Thanks, and stay tuned as we add more poker hands. The next one will be the flush!

– C. out.

How to Code Poker Hands – Three Of A Kind

Hey there,

The mini-series about writing code to match poker hands continues on! This article covers how to match a three of a kind.

You can also find links to the previously covered poker hands in the list below. The list also includes the ones we’ve yet to cover.

Setup

The setup was also explained in the first article of the mini-series, you can check that out here. There, you’ll also a detailed description of the data structures used. But here is a quick rundown of the data structures used in the code:

Card values
CardValues = {
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  jack: 11,
  queen: 12,
  king: 13,
  ace: 14,
  wild: 100
};
Card suits
CardSuits = {
  hearts: 1,
  diamonds: 2
  clubs: 3,
  spades: 4
};
Card
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

And a hand is an array of Card objects:

var hand = [
  new Card([card value 1], [card suit 1]),
  new Card([card value 2], [card suit 2]),
  ...
  new Card([card value 5], [card suit 5])
];
Writing The Code To Identify A Three of a Kind

A three pair is similar to a pair, except you’re looking for three cards of the same value (rank) instead of two.

As you’ve done before, first you sort the cards by their rank, in descending order. We previously defined a “utilities” file, named CardMatchUtils.js, and added a function to it called, CardMatchUtils.SortCardsByDescendingValue, to help with that. You’ll be sorting the cards by descending value for all of the poker hands, so it’s very handy to have this reusable function.

You’ll also be using the “wild card”, which is a card that can assume the rank of any card. The image of the following hand would also qualify as a three of a kind:

In this image, we have a three of a kind with sixes, because the wild card can assume the rank of a six.

The main function for the pseudocode for matching a three of a kind looks like:

ThreeOfAKind = FUNCTION(hand) {
  SORT the hand by descending card value and store in a variable called sortedHand
  
  IF CardsHaveSameValue(sortedHand, 3)
    //we have a three of a kind!
    RETURN TRUE 
    
  //no three of a kind in this hand
  RETURN FALSE
}

As you can see, this function is very short and sweet, because of the CardsHaveSameValue function, which we previously wrote as the CardMatchUtils.DoCardsHaveSameValue function. If you haven’t seen CardMatchUtils.DoCardsHaveSameValue yet, that’s where the brunt of the work is done. This function determines if any cards in the hand have the same rank, specifying the number of cards we want to match, in this case, three.

Now time for a little fun 🙂

Below you’ll find a “hand” of five cards. You can set the suit and value of each card. It will then tell you if the cards you selected match any of the poker hands you’ve looked at so far:

  • Pair (Jacks or higher)
  • Two pair
  • Three of a kind

Each article in this series will introduce the next poker hand that you can explore. Give it a try!


Result:

If you have any questions about the above interaction, please let me know at cartrell@gameplaycoder.com.

Finally, if you’d like to hire me to make an actual card game for you, please e-mail me at cartrell@gameplaycoder.com , or you may use the contact form here.

That’s it for now. Thanks, and stay tuned for more as we add more poker hands!

– C. out.

How to Code Poker Hands – Two Pair

Hey! What’s up.

Today, we’ll be resuming in the mini-series of writing code that can tell what kind of poker hand a player has. And the poker hand we’re covering is a two pair.

  • Pair (jacks or higher only)
  • Two pair
  • Three of a kind
  • Straight
  • Flush
  • Full house
  • Four of a kind
  • Straight flush (a non-ace-high straight flush)
  • Royal flush (an ace-high straight flush)

A two pair is a hand that has two cards of one value, two more cards of another value, and a third card whose value is different than the first four. Here is an example the a two pair hand:


We have a pair of kings and sixes.
Setup

If you’d like to see the first article, coding a pair of Jacks or higher, you can check that out here. There, you’ll also a detailed description of the data structures used. But here is a quick rundown of those data structures:

Card values
CardValues = {
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  jack: 11,
  queen: 12,
  king: 13,
  ace: 14,
  wild: 100
};
Card suits
CardSuits = {
  hearts: 1,
  diamonds: 2,
  clubs: 3,
  spades: 4
};
Card
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

And a hand is an array of Card objects:

var hand = [
  new Card([card value 1], [card suit 1]),
  new Card([card value 2], [card suit 2]),
  ...
  new Card([card value 5], [card suit 5])
];
Writing The Code To Identify A Two Pair

When looking for a two pair, it’s also very helpful if we first sort the cards by their value (rank), in descending order. We previously defined a “utilities” file, CardMatchUtils.js, and added a function to it called, CardMatchUtils.SortCardsByDescendingValue, to help with that.

We’re also using the “wild card”, which is a card that can assume the value of any card. So, the following hand would also qualify as a two pair:

In this image, we have a pair of sixes, and because we have a wild card, we take the highest non-paired card, in this case a king, and pair the wild with that. So, we have a pair of kings.

The main function of our pseudocode looks like this:

TwoPair
TwoPair = FUNCTION(hand) {
  SORT the hand by descending card value and store in a variable called sortedHand
  SET wildsInfo to an empty object
  ADD a PROPERTY numWilds to wildsInfo and set it to 0
  ADD a PROPERTY startIndex to wildsInfo and set it to 0
  
  IF CardsHaveSameValue(sortedHand, 2, wildsInfo) AND
  CardsHaveSameValue(sortedHand, 2, wildsInfo)
    //we have two pairs!
    RETURN TRUE 
    
  //no two pair in this hand
  RETURN FALSE
}

That’s it… not so fast! What’s this CardsHaveSameValue function we’ve never seen before? 🤔

This is a new utility to our CardMatchUtils.js file. Let’s officially call this CardMatchUtils.DoCardsHaveSameValue. This function will determine if a hand has at a certain number of cards that have the same arbitrary value.

This function accepts three parameters:

  • sortedHand – Array of Card objects that are already sorted in descending value.
  • numToMatch – An integer that indicates how many cards whose value we are looking to match. In our case, it’s two.
  • wildsInfo – An object that will allow us to save data for subsequent calls to this DoCardsHaveSameValue function. From our code above, we called CardsHaveSameValue twice, passing in wildsInfo each time. The first call needs to save certain intermittent data so the next call can resume where the first one left off. The wildsInfo parameter has two properties:
    • numWilds – The number of wild cards available for use as substitutes.
    • startIndex – The index of the sortedHand array on which DoCardsHaveSameValue starts when it checks each card in the hand.

The wildsInfo paramater is only needed if your game supports wild cards. Otherwise, you can set it to null (or don’t specify it, if the programming language you’re using supports some form of optional arguments like JavaScript or C#).

CardMatchUtils.DoCardsHaveSameValue will return true if the specified number of cards have the same value, or false otherwise.

DoCardsHaveSameValue
CardMatchUtils.DoCardsHaveSameValue = function(sortedHand, numToMatch, wildsInfo) {
  SET numWilds to 0
  SET startIndex to 0
  
  IF wildsInfo is specified
    SET numWilds to wildsInfo.numWilds
    IF numWilds is 0
      count the number of wild cards in the hand, and set this value to numWilds
    END IF
    SET startIndex to wildsInfo.startIndex
  ELSE
    count the number of wild cards in the hand, and set this value to numWilds
  END IF
  
  SET maxIndex to sortedHand.length - numWilds - 1
  SET baseCardValue to 0
  SET numMatched to 0
  
  LOOP through each card in the sortedHand array, starting at index startIndex
    IF it's the first card in the loop
      //first card starts off the number of matches with a base card value
      SET baseCardValue to the card's value
      SET numMatched to 1
      CONTINUE with next card in the loop
    END IF
    
    IF the baseCardValue EQUALS the card's value
      //this card's value matches the base card value
      ADD 1 to the current value of numMatched
      
      IF numMatched EQUALS numToMatch
        //total number of matched cards found - success
        IF wildsInfo is specified
          SET PROPERTY wildsInfo.numWilds to numWilds
          SET PROPERTY wildsInfo.startIndex to the current loop index + 1
        END IF
        RETURN TRUE
      END IF
      
      //still need to match more cards for the base card value
      CONTINUE with next card in the loop
    END IF
    
    //This card's value does not match the base card value. Check if there are enough wilds that can satisfy the match.
    
    IF numMatched + numWilds is GREATER THAN OR EQUALS numToMatch
      //there are enough wilds that can satisfy the base card value - success
    
      //deduct the number of wilds used to satisfy the base card value from the current number of wild cards
      SET numberOfWildsToDeduct to numToMatch - numMatched
      DEDUCT numberOfWildsToDeduct from numWilds
      
      //update the wilds info
      IF wildsInfo is specified
        SET PROPERTY wildsInfo.numWilds to numWilds
        SET PROPERTY wildsInfo.startIndex to the current loop index
      END IF
      
      RETURN TRUE
    END IF
    
    //If we arrive here, there are not enough wild cards to satisfy the base card value.
    
    //start a new base card value with the current card that did not match
    SET baseCardValue to the value of the card
    
    IF the card is a wild card
      //the base card value can't be a wild card - abort the for loop
      END LOOP
    END IF
    
    SET numMatched to 1
  END LOOP
  
  //unable to satisfy a match - however, one last attempt, if there are remaining wilds, check if number of matched cards on the last loop + num wilds satify
  IF numMatched + numWilds GREATER THAN OR EQUALS numToMatch
    //there are enough wilds that can satisfy the base card value - success!
    
    //deduct the number of wilds used to satisfy the base card value from the current number of wild cards
    SET numberOfWildsToDeduct to numToMatch - numMatched
    DEDUCT numberOfWildsToDeduct from numWilds
    
    //update the wilds info
    IF wildsInfo is specified
      SET PROPERTY wildsInfo.numWilds to numWilds
      SET PROPERTY wildsInfo.startIndex to the current loop index
    END IF
    
    RETURN TRUE
  END IF
    
  //if we arrive here, we were unable to satisfy a match
  RETURN FALSE
}

You can see that if wildsInfo is specified, its properties are updated for subsequent calls to CardMatchUtils.DoCardsHaveSameValue.

Now, let’s have another look at our previous hand with a wild card in it:

We first sort the cards by descending value, so the sorted hand looks like:

The wild cards are always sorted last.

Note: The order of cards by is are arbitrary in this case. The 6c and 6h cards could have been swapped.

Recall that of TwoPair function calls CardMatchUtils.DoCardsHaveSameValue twice, specifying the samewildsInfo parameter each time.

The first time it’s called, the pair of sixes was found. When CardMatchUtils.DoCardsHaveSameValue completes, it will return true, because it found a pair of kings. When the code doesn’t find a match, it will first try to use as many wilds available to satisy the match. In this hand, there is one wild, so it was used. The wildsInfo object was modified as such:

{
  numWilds => 0
  startIndex => 1
}

The next time CardMatchUtils.DoCardsHaveSameValue is called, instead of starting at the first index (index 0, the KH) in the array, it will start at index 1, the six of clubs. It will find two cards of the same value, the 6C, and 6H, and return true. Since both calls to CardMatchUtils.DoCardsHaveSameValue returned true, this hand does indeed contain two pairs.

If you have any questions, contact me by using the contact form here, or you can e-mail me directly at cartrell@gameplaycoder.com.

And of course, if you have a card game you need help coding, get in touch with me, and let’s talk!

That’s all for now. In the next article, we’ll go over the poker hand, three of a kind.

Thanks, and I’ll talk to you next time. Take care,

– C. out.

How to Code Poker Hands – Pair of Jacks or Higher

Hey guys,

In the next several article of this multi-part series, we’ll go over how to code the various poker hands, like Straight, Flush, and Full House. This is the first article of the series, and we’ll be writing code that matches the hand for a Pair of cards that are least a jack or higher.

When developing card games with poker hands in them, writing the code that acknowledges these hands can be a challenge. At least, writing something that can be completed in one lifetime.

You could write out every single card combination for every single hand, but that’d take forever.

So, we’re going to write something that’s a bit more robust robust when it comes to recognizing the card patterns that form the various poker hands.

For some clarity, a poker hand we’ll be using consists of five cards, and cards of certain suits and values and combinations for a poker hand. The hands we’ll be matching are:

  • Pair (jacks or higher only)
  • Two pair
  • Three of a kind
  • Straight
  • Flush
  • Full house
  • Four of a kind
  • Straight flush (a non-ace-high straight flush)
  • Royal flush (an ace-high straight flush)

The list also orders the hands from lowest to highest.

We’ll also be using wild cards. A wild card can assume any suit and/or value of a card to help create a poker hand. For example, in this hand:

We have a pair of queens, because the wild card could be substituted for another queen. Having wild cards does create a challenge, but the results are amazing. (:

Setup

Before starting, we need to define a few data structures. We’ll need to define the suits, values, a “card” which will hold the suit and value, and a “hand” which is an array of cards. All the algorithms will be mostly pseudocode based on JavaScript.

Card values

We can store the card values in an object like this in ascending rank like this:

CardValues = {
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  jack: 11,
  queen: 12,
  king: 13,
  ace: 14,
  wild: 100
};

Note: The values assigned to the card values are arbitrary, as long as the are unique, and the values are in ascending order, corresponding to the rank of the card. For example, ace ranks higher than king, which ranks higher than queen, and so on. Also, we’re including the value of the wild card here, because it’ll be useful later on.

Card suits
CardSuits = {
  hearts: 1,
  diamonds: 2,
  clubs: 3,
  spades: 4
};

Note: The values assigned to the card suits are arbitrary, as long as the are unique (order doesn’t matter). Also, we only need the wild value specified in CardValues, and not CardSuits. A wild card really doesn’t have a suit or value, but putting it in CardValues makes things easier, We don’t have to check two different places for the value of the card (meaning within CardValue, and some other place).

Card

An individual card will hold two pieces of data: the value and the suit. We can define it in a constructor function like this:

Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

We also have a “hand”. It won’t be a custom data structure like the previous three, because it’s really just an array of Card objects. A hand might look like this:

var hand = [
  new Card(CardValues.five, CardSuits.diamonds),
  new Card(CardValues.eight, CardSuits.hearts),
  new Card(CardValues.king, CardSuits.spades),
  new Card(CardValues.ace, CardSuits.hearts),
  new Card(CardValues.three, CardSuits.clubs)
];

Wild cards can be defined like this:

var wildCard = new Card(CardValues.wild);

No suit is specified, and wildCard.suit will be undefined.

Note: We could get into defining a “deck”, which would also be a container of cards, and “deal” those to the player, by removing the “top” card from the deck, and adding it to the player’s hand. However, for the purposes of this how-to, we won’t get into that. Each scenario will assume that the player’s hand already has five cards.

Note: We’re also working off the assumption that there is only one wild card in the deck. So the total number of cards in the deck is 53.

Common Functionality

Because we’ll be using some of the same functionality to match several of the poker hands. So, we’ll have a “utilities” JavaScript file, and let’s called it CardMatchUtils.js. We’ll put these functions here, but for now, our CardMatchUtils file is empty.

Onto Matching Them Poker Hands!

Those are all the data structures we’ll need for this guide. Now, let’s get into matching those poker hands! 🃏

Pair (jacks or higher only)

A pair is any two cards with the same value, and the other three cards are of arbitrary different values. Consider this hand:

there is a pair of fives. But our purposes, while this is a pair, it would not qualify because it’s not jacks or higher.

So we want something like this:

Now we have a pair of kings which does satisfy that requirement. If a wild card was involved, we could have something like this and still have a pair of kings:

You may have noticed that the wild card can create a pair with any of the other four cards. However, we’re only interested in jacks or higher, so the king is the only card that qualifies. Our code will handle this situation as well.

Each matching function will accept one parameter, the hand (which is our array of cards).

While performing matches, it is very helpful if we first sort the cards by descending value, meaning highest value to lowest. This will help with all of our matching functions. So first, let’s add a SortCardsByDescendingValue to our CardMatchUtils file:

SortCardsByDescendingValue
CardMatchUtils.SortCardsByDescendingValue = function(hand) {
  set sortedHand = create a copy of the hand array
  sort the sortedHand array by descending card value
  return sortedHand
};

When you’re sorting hands of cards, be sure that the wild cards are always sorted after the other cards. So, if you had a hand of:

the sorted result would be:

Another utility function that will useful through this matching series is the ability to count how many cards in the hand have a specific value, including the wild card value. We can make a function that looks something like this:

CountCardsByValue
CardMatchUtils.CountCardsByValue = function(hand, cardValue) {
  set numCardsFound = 0
  for each card in the hand {
    if card.value equals cardValue then add one to numCardsFound
  }
  return numCardsFound
}

We send this function our hand and the card value we’re looking for, and it’ll return to us the number of cards found in the hand that have our value.

Now, we have enough to write the code for function that matches a jacks or better pair:

JacksOrBetterPair = function(hand) {
  sort the hand by descending card value and store in a variable called sortedHand
  count the number of wild cards in the sorted hand, and store in a variable called numWilds
  set a variable called numberOfMatches to 0
  for each non-wild card in the sorted hand {
    if the current card in the loop is the first card in the hand being checked in this for loop then {
      if the value of the current card card is lower than a jack then
        return false (there are no cards of at least a jack in this hand, so therefore we don't need to bother checking any further)
      otherwise {
        set the current card as the base card (the values of other cards will be compared with this one to see if they match)
        set numberOfMatches to 1
        restart the loop with the next card as the new current card in this loop
      }
    }
    
    if the value of the base card equals the value of the current card then {
      add one onto numberOfMatches
      if numberOfMatches equals 2 then
        return true (this hand has a pair of jacks or higher!)
    }
    otherwise
      restart the loop with the next card as the new current card in this loop
      
    note: the value of base card does not match the value of the current card's value in the loop, so check if there are enough wild cards to qualify
    if numWilds + numberOfMatches >= 2 then
      return true (this hand has a pair of jacks or higher)
    
    note: no match has been established, so set a new base card value if it's at least a jack
    if the value of the current card is less than a jack then
      restart the loop with the next card as the new current card in this loop
      
    set the current card as the new base card
    set numberOfMatches to 1
  }
  
  note: if we've reached here, then the loop went through all the non-wild cards and didn't find a pair of jacks or higher
  return false
}

That’s something just for looking for a pair of jacks or higher, huh? (:

Finally, if you want to try this out, you’d create your hand like we did earlier. Next you’d call your JacksOrBetterPair function, passing in your hand. TheJacksOrBetterPair will return true if the specified hand contains a pair of jacks or higher, andfalse if it doesn’t.

Also, as we add more functionality to our CardMatchUtils file, the card matching will become somewhat easier, even for the higher ranking poker hands.

That’s it for now! The next article will focus on matching a Two Pair hand!

I’ve been coding heavily in card games lately. I recently released a free Android version of my Blackjack game, Thunderjack!. I’m also working on converting a poker game that I made for a client from Flash to HTML5 using Phaser, which I wrote about here.

Please feel free to ask me any questions you may have about this by replying in the comments below or contacting me here.

And if you’re looking for someone to code your next card game, contact me at cartrell@gameplaycoder.com, and let’s talk.

Thanks, and I’ll talk to you next time. Take care,

– C. out.