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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
1
2
3
4
5
6
CardSuits = {
  hearts: 1,
  diamonds: 2
  clubs: 3,
  spades: 4
};
Card
1
2
3
4
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

A hand is an array of Card objects:

1
2
3
4
5
6
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:

1
2
3
4
5
6
7
8
9
10
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
1
2
3
4
5
6
CardSuits = {
  hearts: 1,
  diamonds: 2
  clubs: 3,
  spades: 4
};
Card
1
2
3
4
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

And a hand is an array of Card objects:

1
2
3
4
5
6
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:

1
2
3
4
5
6
7
8
9
10
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
1
2
3
4
5
6
CardSuits = {
  hearts: 1,
  diamonds: 2,
  clubs: 3,
  spades: 4
};
Card
1
2
3
4
Card = function(value, suit) {
  this.value = value;
  this.suit = suit;
};
Hand

And a hand is an array of Card objects:

1
2
3
4
5
6
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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:

1
2
3
4
{
  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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
1
2
3
4
5
6
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:

1
2
3
4
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:

1
2
3
4
5
6
7
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:

1
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
1
2
3
4
5
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
1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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.