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.

Converting a Flash Game To HTML5

Hey guys,

I’m working on an interesting project now. A repeat client has requested that I convert a cards game I previously made for them from Flash to HTML5.

As you may be aware, Adobe is discontinuing their Flash player browser plugin by the end of 2020.

There really aren’t any true “conversion” tools out there. In other words, say you have a Flash project that consists of a few Flash FLA files with library assets in them, and maybe some exported to external classes, as well as additional external asses loaded at run-time, as well as external AS3 files. And your build process (what you use to generate your final SWF file) uses either Flash CSx/Animate or say, FlashDevelop (good tool, by the way – I highly recommend it if you’re using Adobe AIR to build mobile games).

There is no conversion tool that can just convert all that into a HTML + JavaScript files with all the assets extracted from FLA files, and present you with an HTML index file that you can simply run and be on your merry away.

That. Would. Be. Awesome.

If you want to convert a Flash game to HTML5, you pretty much have to learn JavaScript if you don’t already know it, and rebuild it from scratch).

Depending on the simplicity of your game, you may get some help from Adobe’s Flash Animate, but I’ve never tried it, and due to the complexity of the games I make, it’s likely to not work.

There are several other tools out there, your best bet may be to simple rebuild the code, but you can still use the assets.

However, if you have the original source code – the ActionScript 3 .AS files, sounds, and Flash .FLA files (which I do have because I wrote the original Flash project in the first place) – you already have everything you need to do this. Meaning, you don’t need to go through the trouble of decompiling SWF files and other dubious tasks.

Also, fortunately, the Flash game I’m converting doesn’t do any blitting of bitmaps. All graphics are either bitmaps imported into the FLA, or vector art saves as library symbols. The library symbols can be converted to bitmaps so they can then be used in the HTML5 version.

The biggest challenge for assets and layout is no longer having a super-convenient WSYISYG (what you see is what you get) editor like Flash CS/Animate. This allows you to place and size the objects in a scene as they should look when the game is running. Without this vital tool, you have a few options:

1). Hard-code all the sizes and positions of everything, and references to what everything looks like. (OUCH! This is not the old days of game development. I’m pretty sure we can come up with something quicker and easier, right? 🤔 )

2). Use an editor, like Phaser Editor. A visual editor to build your layout, position and size objects on the scene. This editor has a built-in code Canvas Compiler that will translate your layout into JavaScript code, placing and sizing all your objects for you. You can then focus on building the layout. Now…

For the most part, converting AS3 to JavaScript files is fairly simple. Although it’s a laborious task of recoding, ActionScript 3 and JavaScript share many similarities, both having roots in the ECMAScript standards for example. Sure, you can’t just copy AS3 code, paste it into a JS file and call it a day, but if you know both languages well, the conversion process isn’t all that painful.

Here a quick example of an original source file written in AS3 for Flash, and below it, the JavaScript counterpart.

public final class EZ_PlayerData {
  private var mvo_dailyScores:Vector.<BJ_DailyScoresData>;
  private var mvo_cardsData:Vector.<EZ_PlayerCardsData>;
  private var mn_betValue:Number;
  private var mn_credits:Number;
  private var mu_selectedHandIndex:uint;
  private var mn_tournamentCredits:Number;
  private var mb_isTournamentEnabled:Boolean;
  
  ////////////////////////////////////////////////////////////////////
  // ctor
  public function EZ_PlayerData(u_maxHands:uint, u_maxCardsPerHand:uint) {
    super();
    
    mn_betValue = mn_credits = mn_tournamentCredits = 0;
    mvo_dailyScores = new Vector.<BJ_DailyScoresData>();
    
    mvo_cardsData = new Vector.<EZ_PlayerCardsData>(u_maxHands);
    for (var u_index:uint = 0; u_index < u_maxHands; u_index++) {
      mvo_cardsData[u_index] = new EZ_PlayerCardsData(u_index, u_maxCardsPerHand);
    }
  }
  
  ////////////////////////////////////////////////////////////////////
  // public functions
  
  //==================================================================
  // addDailyScore
  //==================================================================
  public function addDailyScore(o_score:BJ_DailyScoresData):void {
    if (!o_score) {
      return;
    }
    
    mvo_dailyScores.push(o_score);
    mvo_dailyScores.sort(onSortDailyScores);
  }
  
  //==================================================================
  // betValue (get)
  //==================================================================
  public function get betValue():Number {
    return(mn_betValue);
  }
  
  //==================================================================
  // betValue (set)
  //==================================================================
  public function set betValue(n_value:Number):void {
    if (!isNaN(n_value)) {
      mn_betValue = n_value;
    }
  }
  
  //==================================================================
  // cardsData (get)
  //==================================================================
  public function get cardsData():Vector.<EZ_PlayerCardsData> {
    return(mvo_cardsData);
  }
  
  //==================================================================
  // credits (get)
  //==================================================================
  public function get credits():Number {
    return(mn_credits);
  }
  
  //==================================================================
  // credits (set)
  //==================================================================
  public function set credits(n_value:Number):void {
    if (!isNaN(n_value)) {
      mn_credits = n_value;
    }
  }
  
  //==================================================================
  // getDailyScores
  //==================================================================
  public function getDailyScores():Vector.<BJ_DailyScoresData> {
    return(mvo_dailyScores);
  }
  
  //==================================================================
  // isTournamentEnabled (get)
  //==================================================================
  public function get isTournamentEnabled():Boolean {
    return(mb_isTournamentEnabled);
  }
  
  //==================================================================
  // isTournamentEnabled (set)
  //==================================================================
  public function set isTournamentEnabled(b_value:Boolean):void {
    mb_isTournamentEnabled = b_value;
  }
  
  //==================================================================
  // removeLastDailyScore
  //==================================================================
  public function removeLastDailyScore():BJ_DailyScoresData {
    return(mvo_dailyScores.pop());
  }
  
  //==================================================================
  // selectedHandIndex (get)
  //==================================================================
  public function get selectedHandIndex():uint {
    return(mu_selectedHandIndex);
  }
  
  //==================================================================
  // selectedHandIndex (set)
  //==================================================================
  public function set selectedHandIndex(u_value:uint):void {
    mu_selectedHandIndex = u_value;
  }
  
  //==================================================================
  // tournamentCredits (get)
  //==================================================================
  public function get tournamentCredits():Number {
    return(mn_tournamentCredits);
  }
  
  //==================================================================
  // tournamentCredits (set)
  //==================================================================
  public function set tournamentCredits(n_value:Number):void {
    if (!isNaN(n_value)) {
      mn_tournamentCredits = n_value;
    }
  }
  
  ////////////////////////////////////////////////////////////////////
  // private functions
  
  //==================================================================
  // onSortDailyScores
  //==================================================================
  private function onSortDailyScores(o_score1:BJ_DailyScoresData, o_score2:BJ_DailyScoresData):Number {
    if (o_score1.score >= o_score2.score) {
      return( -1);
    }
    
    return(1);
  }
}

And here is the corresponding JavaScript code:

(function(global) {
  global.Multiplay = global.Multiplay || {};
  Multiplay.PlayerData = Multiplay.PlayerData || {};
  
  //===========================================================================================
  //"public"
  
  //-------------------------------------------------------------------------------------------
  //ctor
  //-------------------------------------------------------------------------------------------
  Multiplay.PlayerData = function(u_maxHands, u_maxCardsPerHand) {
    this.dailyScores = [];
    this.betValue = 0;
    this.credits = 0;
    this.selectedHandIndex = 0;
    this.tournamentCredits = 0;
    this.isTournamentEnabled = false;
    
    this.cardsData = [];
    for (var u_index = 0; u_index < u_maxHands; u_index++) {
      this.cardsData.push(new Multiplay.PlayerCardsData(u_index, u_maxCardsPerHand));
    }
  };
  
  //-------------------------------------------------------------------------------------------
  //addDailyScore
  //-------------------------------------------------------------------------------------------
  Multiplay.PlayerData.prototype.addDailyScore = function(dailyScoreData) {
    if (!dailyScoreData) {
      return;
    }
    
    this.dailyScores.push(dailyScoreData);
    this.dailyScores.sort(this._onSortDailyScores);
  };
  
  //-------------------------------------------------------------------------------------------
  //removeLastDailyScore
  //-------------------------------------------------------------------------------------------
  Multiplay.PlayerData.prototype.removeLastDailyScore = function() {
    return(this.dailyScores.pop());
  };
  
  //===========================================================================================
  //"private"
  
  //-------------------------------------------------------------------------------------------
  //_onSortDailyScores
  //-------------------------------------------------------------------------------------------
  Multiplay.PlayerData.prototype._onSortDailyScores = function(score1, score2) {
    if (score1.score >= score2.score) {
      return( -1);
    }
    
    return(1);
  };
})(window);

AS3 takes the usual object oriented programming approach with classes, by defining an actual ‘class’, its constructor, and added properties and methods onto that class.

JavaScript uses protoypes, and a function of the same name as the “class” acts like a constructor. You then add functions onto the prototype which act like the class’s methods.

Due to the absence of public getter/setter properties, the JavaScript file turned out to be way shorter than the original ActionScript. However, you have to be careful when accessing members of the Multiplay.PlayerData prototype, that you don’t accidentally modify a member intended to be treated as private. In JavaScript, I precede such functions and members with an underscore ( _ ).

Throughout the conversion process, I highly recommend that you constantly test the code in small updates to ensure that the code is working as expected (much like you would when building any game, but especially here). I convert AS3 classes as few as possible at a time, then re-test for errors.

How Phaser Editor Helps

Other than the aforementioned benefits of using a WSYIWYG editor, Phaser Editor also allows you to write custom code in the same files that it creates with its canvas compiler.

In most cases, I prefer to keep the UI code separate from logic/business/implementation code, adapting some concepts from Model View Controller design pattern. This makes it easier for me to convert classes from AS3 to JS, since the UI and logic code will be implemented different in the two scripting languages.

That said, in the files generated by the Phaser Editor canvas compiler, I can add an “initialization” method call the editor’s User Code section, and from there, set up all the UI objects that were created on the canvas.

This one line is the only one I write in the Create tab of the User Code dialog. I prefer to keep code in here minimal and focus on write what the _init does in the user code section of the canvas JS file. Phaser Editor will reserve areas of the JS file as user code for you, and the code there will not be overwritten the next time you save the canvas layout (which will cause the canvas compiler to update the corresponding JS file, overwriting any unsaved changes – make sure you always save your JS file first before going saving new changes in the editor’s canvas!)

In the “user code here” section of the JS file (marked by Phaser Editor in a commented at the bottom of the file), I defined an empty _init function. This is where you can custom setup any UI objects, and we’ll be revisiting this later.

GameView.prototype._init = function () {
};
Converting a Button

Next, say I want to create (or “re-create”, as we’re rebuilding the original Flash layout 😉 ) a button on the canvas named btnBet1 (from the casino cards game I’m converting for my client). Because I also have the field property set to true, the canvas compiler will create a property on the JavaScript file of the corresponding canvas called fBtnBet1. I also have the callback property set to a method on this instance of the canvas object this._onBet1Pressed. In my user code, I can define the _onBet1Pressed function. You’ll also want to add the button frames for over, out, down, and up so your button can respond to the various button states.

The canvas file is actually a Phaser state, and the canvas compiler will automatically generate the following code in the state’s create method:

var _btnBet1 = this.add.button(931.0, 753.0, 'some_atlas', this._onBet1Pressed, this, 'bet_up_1_over', 'bet_up_1_norm', 'bet_up_1_over', 'bet_up_1_over', _buttons);
...
this.fBtnBet1 = _btnBet1;

In the user code section of the JS file, I can create the button pressed callback function like this:

GameView.prototype._onBet1Pressed = function () {
};

It’s similar to a MouseEvent handler from ActionScript 3 when setting up a button to respond to mouse clicks.

Keeping the UI code and implementation code separate, I won’t include what the button actually does inside this method. Instead, I’ll have it dispatch a notification, via a Phase Signal. I treat the signal is treated as a public property of the canvas object, and I define the signal in the _init method created earlier:

GameView.prototype._init = function () {
  this.onBetButtonPressed = new Phaser.Signal();
};

When the button is pressed, I want that signal to fire a notification to be handled by the implementation code. Modifying the _onBet1Pressed function, it now looks like this:

GameView.prototype._onBet1Pressed = function () {
  this.onBetButtonPressed.dispatch();
};

There is no logic code in this canvas JS file, since it’s for UI only. The implementation is handled by the code that processes the game logic. First, it assigns a function to be handled by the signal when it dispatches a notification:

var gameView;
...
gameView.onBetButtonPressed.add(function() {
  //do whatever when the button is pressed
});

Instead of inlining the function, you can also pass in a function reference:

gameView.onBetButtonPressed.add(onBetBtnPressed);
...
function onBetBtnPressed() {
  //do whatever when the button is pressed
}

That’s pretty much how all the buttons will be converted.

Converting Fonts

Fonts is a big one. In Flash, you can embed fonts directly into the SWF file to make sure that the fonts will show up, even if the fonts aren’t installed on the end users’ machines. However, you can’t do this with HTML5. Instead, you have to either use web fonts something like this, or you can use bitmap fonts. Phaser Editor can not show all the fonts installed on your system. A quick excerpt from this page about fonts in Phaser Editor:

Phaser Editor uses JavaFX to render the scenes but Phaser uses the browser for the same purpose. This means that in some cases the text object is not rendered in design-time like Phaser renders it at run-time.

Note that Phaser Editor can use the fonts installed in the OS, but the majority of them are not available in all platforms, so we recommend to use safe fonts or load the font files in the CSS of your game.

I decided to go with using Bitmap fonts. Phaser Editor also supports bitmap fonts. This means, I have to create a texture atlas and corresponding XML for all the fonts I want to use. There are a few tools out there for this task:

For this project, I went with the Generator. While it’s not as powerful as Littera in terms of customizations, because it supports font formats other than only True Type. And this game does use some True Type fonts, and I want to be as faithful to the original implementation as possible.

A quick note on using the Generator. When it creates your text image atlas, you’ll also get a .FNT data file. This is the XML file that Phaser (and Phaser Editor) uses when setting up bitmap fonts. You can simply rename the extension from FNT to XML, and you should be good.

That’s the jist of what I’ve done, and so far, I’m not running into any major hurdles. It’s just a detailed process, and you should convert and test in small increments. I may write future updates to this if I encounter anything that warrants an article. I’m thinking timeline animations, but because I didn’t use any in this game, I don’t expect any issues there.

That’s all for now guys. Thanks, and I’ll talk to you next time. Take care!

– C. out.

Added Brickout Game To GitHub

Hey guys,

The source code for one of the earlier games I created, Brickout, is now available on GitHub here. If you’re interested in looking at games under the hood, have a look!

Screenshot of Brickout.

This game is the first completed game using HTML5 + Phaser. To build the level, I used Tiled. I found level graphics on OpenGameArt from Matriax.

The bomb explosion animation was also on OpenGameArt, by Jetrel.

Meanwhile, I’m working on some new 2D games, made in either Phaser or Unity, so there’s more to come!

Like this:

The image above is a screenshot for a Unity game I’m currently working on. This is from the course on Udemy: Complete C# Unity Developer 2D: Learn to Code Making Games.

It’s the last project in the course (I’m almost done! YEAH! 💪🏿) , and it’s a tile-based, 2D, side-scrolling platformer, one of my favorite game genres, and I can’t wait to use all the skills I’ve learned in this course (and outside of it), to really go beyond the course material, and finish it! Though it’s gonna take me a while (AS IT SHOULD), because I have a lot planned for this game.

If I may digress for a moment: Speaking of finishing things, if you’re like me, and you find it challenging to sometimes finish your side projects, watch the following video.


John Sonmez talks about how to become a finisher and finish shit.

It’s from John Sonmez, founder of Bulldog Mindset, a company that helps people, particularly software developers, become better, stronger versions of themselves and get more out of life by improving their soft skills, mindset, philosophy, wealth, investing, and relationships. He also wrote a book called Soft Skills. It’s a great read; I invite you to give this book a read.

I’m also working on a simple RPG that will use an Active Time Battle System. I’ve always been a fan of battle systems in RPGs. I’m way more interesting the the working of battle systems than I am in the story lines. ⚔

Ever since I was introduced to the ATBS in Final Fantasy IV (and it was elaborated on in Final Fantasy VI), I’ve always been fascinated by it.

There is so much involved in this type of game, such as inventory, moving around in maps, stats, and the various intricacies involved in building a battle system.

This is a very exciting project, as I’ve never worked on an RPG before. Neither as side project (until now), or a client project – though I’d LOVE to work on a client’s RPG!

By the way, if you’re looking for a coder to help you build a 2D tile-based, single-player RPG, get in touch with me through this contact form, or e-mail me directly at cartrell@gameplaycoder.com. 😉

That’s it for now, guys. Take care,

– C. out.

P.S.: And should I survive all that, let’s not forget about card games, which I’m still considering specializing in. I want to make a battle card system (think collectible card game), that has mechanics similar to Yu-Gi-Oh!. It’s really the automation of the mechanics of this game that fascinate me. This will likely be THE most difficult game I’ve ever worked on, but I’m looking forward to the challenge.

Thunderjack! HTML5 Game Update: A Few More Adjustments

Hey, what’s up!

Ok, I can’t believe I uploaded the game without addressing these few functions! Ha! I guess I was so excited (:
Anyway, here’s what’s “new”:

  • You can no longer start a round without placing a bet (doh!)
  • Dealer’s second card is hidden until it’s the dealer’s turn (I had his hand fully revealed while testing and forgot to hide its second card)
  • Added self-promotion on intro screen (of course!)

I’ve also been exploring minifiying JavaScript files and combining them into one file, and found UglifyJS.

UglifyJS can be run as a command-line tool, and it can accept a list of all the files you want to combine. I tried combining the Phaser JS file, but was having problems. So I ended up combining only my own source files, as well as the files generated by the Phaser Editor canvas compiler.

On the page that hosts the game, it no longer loads a bunch of JS files (currently 44 files), but just two files: the Phaser source file, and a minified Thunderjack! source file.

You can play the game here.

That’s all for now guys. Take care.

– C. out.

Thunderjack! HTML5 Game Update: A Little More Polish

Hey there.

I made some more adjustments to the Thunderjack! card game.

The updates include:

  • Sound effects
  • The Thunderjack! effect (lightning + thunder sound + screen flash + screen tremor)
  • Added a preloader
  • Cleaned up text visuals (use of BitmapText)
  • Cleaned up loading (some assets were being loaded twice from various Phaser state files per Phaser Editor. After studying the editor a bit, I may write an article about setting up assets in pack files, and a basic understanding as to how Phaser accomplishes this. )

I’ll be making one more change to the game: How to minify the JavaScript code. Currently, all the JS files are being loaded individually. Although most are small (less than 10 KB), there are quite a few files, and it causes the web browser to make many HTTP requests to the server.

By having files “minified”, it combines several JS files into a single one (and can optionally compress and/or mangle the files’ contents), reducing load times, and number of requests. I’ve been looking at tools like UglifyJS, which is also caused me to look at tools like Node.js ( https://nodejs.org/en/ ) and npm … Looks like I’m going down the damn rabbit hole whether I want to or not! 😏

And I’m not done with card games, especially consider how many I’ve made for a client, Squarejack Gaming.

Also, not only will I get into not more traditional type of card games, but also other non-gambling relatively simple ones, like Concentration (Match). Even a battle card game may be in the works later down the road.

And I’ll really be going deep when I start adding multi-player aspect to these games. Lots of exciting things ahead!

So, go ahead and give have some fun playing Thunderkjack!. 👍🏿

Finally, if you’d like me to code your next card game, please get in touch with me at cartrell@gameplaycoder.com.

That’s all for now. Talk to you later, guys. Take care.

– C. out.