### Archive for September, 2013

September 19, 2013

## Floral Matchmaker Tutorial #4: Randomizing the Game Board

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.

• 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.

## 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.

September 5, 2013

## Floral Matchmaker Tutorial #3: Hiding and Showing the Game Board

In the first two tutorials of the series, I covered the code solution for the automatic colorization of our flowers and the way I got the ornaments to swing naturally.  For this tutorial, I wanted to focus on how to combine responsive and traditional layouts to expand and shrink the stage.  If you view the live example and mouse over the panel, you’ll notice that the game board pops out to the left, over the text of the webpage.  Once the mouse leaves the confines of the stage, the stage closes back to its original dimensions.  Some of our users think of this as “expanding and shrinking the stage,” and go through extensive code solutions to actually change the size of the Stage.

When the game board is open, it covers existing text.

I decided to approach this problem in a different manner; instead of resizing the stage, I decided I would resize the container and let Animate’s scalable content handle the rest.

• scalable layout
• direction anchors
• HTML iframes
• jQuery’s animate() function

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.

## Resizable Content and iFrames

Animate’s resizable content settings allows you to change the dimensions of your objects based on percentage instead of pixels.  This is commonly used to create content that will fit on multiple platforms, such as content that should take the full size of the browser on multiple mobile devices, each of which has similar but not identical form factors.

Stepping back to a more conceptual level, I wanted my match-two game to slide in and out from behind the informational half of my advertisement.  At first, I thought (like many others) I should resize the stage using jQuery.  But after taking a look at what might be involved, I realized that I was thinking of the Stage as the container, when in reality my advertisement would actually live within an iframe.  If my iframe didn’t resize, all I’d get would be an iframe with a horizontal scrollbar on the side of a webpage.

I realized I should be focusing on changing the iframe’s size, not the stage size.  Knowing that we had a scalable layout feature made it all that much easier for me to make my content change with the size of the iframe.

## Step 1: Resize the Background

Since I knew that my advertisement would stay 600px high, I only had to resize the width of the Stage.

• Click on the Stage in the Elements panel, or click on an empty part of the Stage in the main Stage panel
• Select the toggle button next to the W (width) selection in the properties panel to change it from px to %
• Preview in browser and change the browser size

Notice that the previewed project takes up the entire width of the browser.  This is expected until you place the Animate file in its parent iframe.

You can also preview what this looks like by changing the size of the stage by adjusting the preview marks.  Once you select the % property for the Stage, you can drag the slider in the ruler left and right to see the Stage resize.

## Step 2: Set the Reference of the Major Objects to Different Sides

By default, all of the objects take their references from the top and left sides.  This means that any X or Y value you set references 0,0 in the upper left hand corner of the Stage, and move the object based on a point defined in its upper left hand corner.  However, in order to make the expansion and shrinking to work, I needed to have objects pinned to both left and right of my Stage.

Animate makes this easy by providing a four-square selection box in the properties panel for every object.  Since the main part of the advertisement would stay pinned to the right hand side, I decided to pin my cascadingFlowers object and the associated text to the right side of the Stage.

• Select the first four objects in the Elements panel (“playGame”, “sfflowerexpo”, “decorateTheOutdoorsText”, and “cascadingFlowers”)
• In the properties panel, select the top-right rectangle
• Preview in browser and change the browser size, or adjust the preview marks to see how the objects flow

## Step 3: Place the Project in an iframe

Many times, an Animate project is placed within the context of another HTML file, like as a menu, an animated header, or content rotator.  In this case, our skyscraper advertisement lives on a news site and will pop over existing text when the user mouses over the project.

• Start with an HTML file with some text in it.  In this case, I used the following as my container:
```<div align="left" style="width:700px; position: absolute; top: 0px; left: 0px; border: none; font-family: Verdana, Geneva, sans-serif; font-size: small">
INSERT MY TEXT HERE
</div>```
• Add jQuery to the parent page by adding a <script> tag in the header of the file:
`<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>`

This allows us to use jQuery within the parent page.  Even though Animate has jQuery in it, we’re not allowed to use it in the parent unless we reference it properly due to scope.

• Create an iframe and load the Animate project into it
`<iframe id="advertisement" src="skyscraper.html" height="600" frameborder="0" style="position:absolute; top: 50px; right: 10px; width: 160px"></iframe>`

As you can see from the iframe statement, the default width of the iframe is 160 pixels.

## Step 4: Opening and Closing the iFrame

We can now use jQuery to open and close the iFrame by adding the following script to the body of the parent HTML file:

```<script>
});

});
</script>```

This is jQuery that says: “When the mouse enters the ‘advertisement’ object, resize the width of that object to 600px.  When the mouse leaves the ‘advertisement’ object, resize the width of that object to 160px.”  Both resizing functions (using the jQuery animate() API) will animate over the course of 500ms, or half a second.

Note that we’re using the mouseenter and mouseleave events and not the mouseover and mouseout events.  Many new users will confuse the two, but mouseover and mouseout will fire whenever the mouse moves, which means that your animation will oftentimes flicker as you move your mouse.  Instead, use mouseenter and mouseleave – it’s what you want 90% of the time.

## Step 5: The Need for a Background Object

At this point of development, I noticed I had a problem.  To see the problem in the project:

• Click on the eyeball next to the “background” element in the Elements Panel
• Resize the Stage width to 160px using the preview slider in the ruler

The text with the game (and really, the game board itself) displayed behind my flower wind chimes.  But the animation trigger for opening and closing the advertisement lives within the parent HTML, and I didn’t want to call back into the project if I could help it.  Instead of doing the complicated code solution, I realized I could just create an object that would live below the wind chime flowers but on top of the game board and all of its associated text.

Since I had a gradient as the background, I used color swatches to save my gradient.

• Click on the Stage in the elements panel
• Click on the gradients icon in the properties panel to load the gradients color selector
• Click on the + next to the vertical gradient bar to add it to the color swatch
• Draw a rectangle and set it to 160px wide by 600px high
• Click on the gradient selector in the properties panel
• Click on the saved gradient in the color swatch to reload it
• (optional) Convert to symbol (notice that background is a symbol, though it isn’t required in this case)
• Drag the background object in the Elements Panel until it’s below the cascadingFlowers
• Change the reference point of background to top-right and align it with the right side of the project

Gradient swatches and color swatches are saved with your Animate project, so you can reuse them over and over again through the lifetime of your project.

## Summary

By inserting Animate into an iframe, you can easily add independent animated content to existing HTML projects.  You can use a little bit of jQuery in the parent HTML to take advantage of Animate’s scalable layout feature and adjust the size based on whatever you’d like, including mouse events and media queries, to name a few options.  And, finally, the color and gradient swatches feature is a great little time saver for when you’re working with the same colors over and over again.

Have questions on this technique?  Edge Animate engineering staff and great community members answer questions in the Animate user forum.