by Elaine

Created

September 19, 2013

Over the past three tutorials in this series about the Floral Matchmaker sample, I’ve talked about animating with the timeline, using the scalable stage in conjunction with a resizable iframe, and creating dynamic colors.  This next post steps away from Edge Animate specifically and into JavaScript to explain how one might efficiently put together a randomized game board.

My game is a very simple match-2 game that has 12 pairs of colors.  The user flips over one token and then another.  If they match, the tokens stay on the flower; if they don’t match, the tokens turn back over so that they’re hidden again.  While I could have laid out a static layout, I thought it would be a more interesting game to play (if not test!) if the game board were randomized so that no one, not even the developer, knew the order of the colors underneath the token.

This article is intended for users of Animate who have some knowledge of coding in JavaScript.

Topics covered in this article:

  • Animate symbol scope
  • the code panel
  • Javascript objects
  • Javascript random number generation
  • Javascript arrays

The screen shots and project files from this post are based on Edge Animate CC, which is available for a free 30 day trial via the Adobe Creative Cloud and is included in any paid subscription to the Adobe Creative Cloud.

Download the finished project files
See a live example

 

The Problem with Random Numbers

Some users have asked the question: “I have <a bunch of things> that I want to display in a random order, one after another.  How do I do that?”  Sometimes their first solution looks something like this:

  • Pick a question at random by selecting a random number
  • When the question is complete, pick another question at random by selecting a random number
  • Repeat the previous step as many times as you have questions

Anyone who has done this has probably experienced the problem of repeated questions, where the random numbers turn out to be: 20, 5, 1, 2, 6, 7, 7, 8, 8, 8, 8, 8, etc.  The problem is that we aren’t guaranteed 20 equally distributed random numbers when we use standard random number generation.  In my case, I wanted to ensure that I had 12 unique matching pairs.

 

Would You Like a Hash with That?

Let’s say I have five marbles, each a different color: blue, red, white, green, and yellow.  I want to make a list of five unique colors.  These marbles all go into a bag, and every time I draw from the bag, I take note of the color and then stick it back into the bag.

Here’s how I start my list:

  • draw a marble (red)
  • write the color of the marble on my list (red), put the marble back in the bag
  • draw a marble…

At this point, if it’s red, we can’t just repeat step 2, because my list wouldn’t be unique anymore.  So, I keep a second list.  Here’s what it looks like:

  • draw a marble (red)
  • write the color of the marble on my first list (red), and write the color of the marble on my second list.  Put the marble back in the bag
  • draw a marble (green)
  • check the second list to see if the color is on the list (no).  Since it’s not, add it to my first list (red, green), and add it to the second list (red/green).  Put the marble back in the bag.
  • draw a marble (red)
  • check the second list to see if the color is on the list (yes).  Since it is, put the marble back in the bag.

At this point, you’re probably thinking that the two lists are the same.  Why, then, would I maintain a second list?  Well, here’s where things get interesting.  Let’s say that we have 1,000 colors on our first list and a very large bag of marbles.  The standard way of checking to see if a color is on the list is:

  • draw a marble (white)
  • look at the first item in the list.  Is it white?  (no)
  • look at the next item in the list.  Is it white? (no)
  • repeat until you either find a white object or you run out of items on the list

If your color (white) isn’t on the list, you’ve effectively had to look at every item in the list.  And if you’re drawing 2,000 unique colors, you can imagine that this would get pretty slow if you have to traverse the list every single time.

Instead, there’s a way to create an object called a hash where your workflow looks like this:

  • draw a marble (white)
  • ask the hash if it has a white object (no)
  • add the color to the first list and to the hash

Or:

  • draw a marble (white)
  • ask the hash if it has a white object (yes)
  • repeat the draw

While the first way of looking at the data requires you to check the list multiple times, the second type of list only requires one request.  A hash is a very efficient way of checking to see if you’ve already selected the object so that your first list only consists of unique items.  This comes in handy whether or not you’re making a list of questions or selecting 2 colors.

Now that we have a good concept of how we want to implement the code, let’s take a look at JavaScript.

 

JavaScript and Hashes

For those of you who are familiar with JavaScript, the first thing you might point out is that JavaScript doesn’t actually have a hash object or even an associative array object.  This is true; instead, you can use properties of a generic object to accomplish the same thing.  To follow along in the Floral Match Maker sample:

  • open the Code Panel by selecting Window > Code from the main menu or typing Ctrl/Cmd-E
  • Select the “gameBoard” line in the tree control

This will show you all of the code in the gameBoard symbol.  Note that there are some custom function outside of the scope of the creationComplete event handler.  Declaring them in the gameBoard symbol space means that any functions within the symbol closure can call them, somewhat akin to a private method in other programming languages.

Then:

  • scroll down to line 25

At this point, we declare two containers: one an array and the other a generic object.

var matchArray = new Array();
var colorHashObject = new Object();

In the parlance of the previous section, “matchArray” would be the first array and “colorHashObject” would be the second array.

 

Setting Up the Color List

We’re now going to introduce two more lists: a list of colors in order and a list of all of the flowers I need to populate.

Line 9 in the gameBoard scope has a variable declaration:

var colorArray = ["#989AE8","#D3A7FF", "#B4DBFF", "#98E8E6",
      "#F55A76", "#A384AD", "#FFFFBF", "#FFB6FF",
      "#BEF299", "#CCCCFF", "#FFD7A2", "#CCFFF8"];

This sets a series of hex color values into an array.  This means that if I query colorArray for the first value (colorArray[0]), it will return “#989AE8″, and so on and so forth down the line until we get to the 12th value (index 11).  Note that I came up with this number based on the fact that I have 24 matching pairs, and so need 12 predefined colors.

Similarly, line 2 in the gameBoard scope has a variable declaration:

var boardArray = ["flower0", "flower1", "flower2", "flower3", "flower4",
     "flower5", "flower6", "flower7", "flower8", "flower9", "flower10",
     "flower11", "flower13", "flower14", "flower15", "flower16",
     "flower17", "flower18", "flower19", "flower20", "flower21",
     "flower22", "flower23", "flower24" ];

This ordered list corresponds to the element names associated with the gameBoard.  To see where I got these element names:

  • go to the Library Panel
  • double click on the icon next to “gameBoard”
  • look in the elements panel

I’ve laid out a 5×5 grid in this symbol with the flowers named flower0-flower24 – a total of 25 flowers.  But since it’s an odd number of flowers, I decided the center would be a free square.  Therefore, my boardArray array doesn’t contain a “flower12″ object.

In the boardArray array, I have 24 objects, with indices from 0-23.

Now that I understand my four lists, I’m ready to populate my game board.

 

Making the Slots

The first thing I need to do is to initialize my hash.  Since I’m keeping track of 2 of each object, I decided to use a number to track how many of each object I’ve already drawn.  If the number is 2, then I know to draw again.  If I were to only need one of each (like in my question example), I could use a Boolean value (true/false) instead.  In the sample project, line 28:

for (var i=0; i < 12; i++) {
    colorHashObject[i.toString()] = 0;
 }

Note that we use JavaScript’s toString() function to convert the number (let’s say 5) from its numerical value to a text value.  This is important, because object parameters are referred to by a string, not a numerical value.  So, essentially, what we are doing is saying:

colorHashObject["0"] = 0;
colorHashObject["1"] = 0;
…
colorHashObject["11"] = 0;

 

Filling The First List

Now it’s time to fill our first list (matchArray) with 24 randomized, numerical values, and our second list (colorHashObject) is ready to be used as a checklist.

while(matchArray.length < 24) {
    var randNum = Math.floor(Math.random() * 100) % 12;
    if (colorHashObject[randNum.toString()] < 2) {
       colorHashObject[randNum.toString()] += 1;
       matchArray.push(randNum);
    }
    else {
       continue;
    }
 }

This block creates a random number in the following way:
Math.random() creates a number between 0 and 1 (e.g. 0.260384).  We then multiply it by 100 (in this case, 260.384), then take the floor of the number (round down: 260).  Then, we modulo, or take the remainder, of the number once it’s been divided by 12 (therefore, 8).

Stepping through the function, we check to see if this number has already been chosen, by saying: “If colorHashObject["8"] has not been hit twice, then add one to that object, add it to the end of the first list, and move to the next iteration.”  The index of colorHashObject is a string value, but the value it holds determines how many times it’s been called.  Since we’re looking for a pair, the number has to be less than 2 for us to keep going.

Let’s walk through this.  After we draw 8, our colorHashObject looks like this:

colorHashObject["0"] is 0
colorHashObject["1"] is 0
...
colorHashObject["8"] is 1
...
colorHashObject["11"] is 0

If we draw a 6 the next time, we now have:

colorHashObject["0"] is 0
...
colorHashObject["6"] is 1
colorHashObject["7"] is 0
colorHashObject["8"] is 1
...
colorHashObject["11"] is 0

Now, if we draw 8 again, we’ll get:

...
colorHashObject["8"] is 2
...

If we draw 8 again, the program checks:

if (colorHashObject["8"] < 2) ...

In this case, we reject the draw because we know we already have a pair in matchArray and try again.

Note that we use a while loop instead of a for loop because we don’t know how long it’s going to take to get 24 values.  We just keep on checking whether or not the list is long enough.  At the end of the while loop, we should have a matchArray of exactly 24 objects, with exactly 12 pairs of objects.

 

Setting Up the Game Board

When I set up each game piece, I want each one to not only have the background set, but also to know what its own value is for a quick comparison when I’m playing the game board.  Since each game piece is actually a symbol, I know that I can just set a variable in that symbol’s scope so I can just ask the game piece what its value is.

In the sample project, I separated this out into the colorizeBoard method.  I pass in the matchArray into the function as “randomColors,” so you can think of the two as identical.

// NOTE: randomColors is actually matchArray in this code
for (var i=0; i<24; i++) {
    // each flower knows what its color is
    var currColor = randomColors[i];
    currSym.getSymbol(boardArray[i]).setVariable("color", colorArray[currColor]);
    // set the color of the background
    currSym.getSymbol(boardArray[i]).$("background").css("background-color", colorArray[currColor]);
 }

Since I have exactly 24 objects, I can use a for loop.  I use the colorArray I defined with all of the hex values and the list of elements in boardArray to essentially do the following:

  1. Grab the current index’s random number out of randomColors, each of which should be between 0 and 11
  2. Grab the associated element in boardArray, get its symbol, and assign a variable with the current index’s random number
  3. Get the color associated with the random number out of colorArray, grab the background out of the element, and get its DOM handler.  Assign the background-color to the color using jQuery.

 

Summary

Unique randomization can be a difficult problem for intermediate coders, but this little trick of using helper arrays and a hash (or generic JavaScript object) can really help optimize your code and make it more efficient.  Have questions on this technique?  Edge Animate engineering staff and great community members answer questions in the Animate user forum.