Friday, April 3, 2009

Change HTML background colour

More External Interface stuff. This snippet of code will enable you to change the background colour of a HTML page. Add the following Actionscript and a movieclip with an instance name of "btn":
import flash.external.*;
var jsCall:String;
btn.onPress = function() {
jsCall = String(ExternalInterface.call("changeBgColor", "#fffecb));
};

Add the following Javascript to your HTML code:

<script language="JavaScript">
function changeBgColor(newBgColor)
{
if (window.document && window.document.bgColor)
{
document.bgColor = newBgColor;
}
}
</script>

You can add a little random spice by using the following Actionscript:
import flash.external.*;
var jsCall:String;
btn.onPress = function() {
ranColor = Math.round(Math.random() * 0xFFFFFF);
jsCall = String(ExternalInterface.call("changeBgColor", ranColor));
};

You can see a working example here along with the code.
Follow this link for details on how to change the background image.

Sunday, March 1, 2009

Generating a list of unique random numbers

Here's a useful function for generating a list of N random numbers from a larger list M:

function randList(max:Number, num:Number, shuffled:Boolean):Array {
var tempArray:Array = [];
for (i = 0; i < max && num > 0; ++i) {
if (Math.floor(Math.random() * (max - i)) < num) {
tempArray.push(i + 1);
num--;
}
}
if (shuffled) {
tempArray.sort(function () {
return Math.floor(Math.random() * 2) ? true : false;
});
}
return (tempArray);
}

Just provide the maximum number (M) in your list and the number of items (N) you wish to generate from that list:

// to generate an array of 10 unique sequential numbers
// between 1 and 10
var myArr:Array = randList(10, 10);
trace(myArr);
// to generate an array of 5 unique sequential numbers
// between 1 and 100
var myArr:Array = randList(100, 5);
trace(myArr);

Finally, the function also allows for the list of N random numbers to be shuffled:

// to generate an array of 10 unique shuffled numbers
// between 1 and 10
var myArr:Array = randList(10, 10, true);
trace(myArr);
// to generate an array of 5 unique shuffled numbers
// between 1 and 100
var myArr:Array = randList(100, 5, true);
trace(myArr);

Tuesday, December 2, 2008

Accessing HTML page details

Flash only has a basic in-built property to retrieve details of the HTML page in which an SWF is embedded. You can retrieve the URL of the SWF file itself, for example with the following code:

myTxt.text = this._url;

Later versions of the Flash player also allow you to retrieve the URL of any JPEGs, GIFs or PNG files by applying the _url property to a movieclip into which any of those filetypes has been loaded.

However, to retrieve the page URL, you have to use External Interface to communicate with the page directly. For example, the following code will retrieve the page URL:

import flash.external.ExternalInterface;
var pageURL = ExternalInterface.call('window.location.href.toString');
myTxt.text = pageURL;

A similar technique can be used to retrieve the HTML page title:

import flash.external.ExternalInterface;
var pageTitle = ExternalInterface.call('window.document.title.toString');
myTxt.text = pageTitle;

With both techniques, you can also consider using Flash's unescape function to convert any URL-encoded characters into ASCII strings:

myTxt.text = unescape(myTxt.text);

Finally, it's possible to use ExternalInterface to change details of the HTML page rather than just retrieving them. Create an FLA containing a dynamic text field and a button. Add the following code:

import flash.external.*; // imports the external interface class
var newTitle:String;
btn.onPress = function() {
newTitle = String(ExternalInterface.call("changeDocumentTitle", title_txt.text));
};

Publish the SWF file and the corresponding HTML page. Now edit the HTML page and add the following javascript code:

<SCRIPT LANGUAGE="JavaScript">
function changeDocumentTitle(a) {
if (a != null) {
window.document.title=a;
window.document.write;
}
}
</SCRIPT>

If you upload the SWF and HTML page, you should now be able to change the HTML page title dynamically from Flash. You can see a working example here and get the source files here.

Obviously you wouldn't necessarily want to use a text field to do this but, by storing newTitle as a variable, you can alter the HTML page dynamically, for example as part of a Flash navigation.

Sunday, November 30, 2008

Rounding numbers

Previous posts touched on the subject of formatting numbers; either as formatting currency or separating with commas and two decimal places. Another question that's frequently asked is how to round to different numbers of decimal places?

The standard answer is to use powers of 10 as per the following examples. To round to two decimal places use:
roundedNumber =  Math.round(yourNumber * 100)/100;

For three decimal places, use:
roundedNumber =  Math.round(yourNumber * 1000)/1000;

However, an easier way is to create a quick function to perform the work for you:

function roundDecimal(num:Number, places:Number):Number {
// defaults to two decimal places
if (places == null) {
places = 2;
}
power = Math.pow(10, places);
return Math.round(num * power) / power;
}

Use it as follows:

trace(roundDecimal(3.14159265358979, 5)); // Outputs 3.14159
trace(roundDecimal(3.14159265358979, 3)); // Outputs 3.142

Wednesday, August 6, 2008

Formatting currency

Following on from the previous entry about formatting numbers, it's a simple task to convert the same function into one that accepts currency symbols:


function formatCurrency(num:Number, comma:Boolean, currency:String):String {
// return a zero value if num is not valid
if (isNaN(num)) {
return "0.00";
}
// return a blank value if currency is not valid
if (currency == undefined) {
currency = "";
}
// round num to the nearest 100th
num = Math.round(num * 100) / 100;
// convert num to a string
var num_str:String = String(num);
// seperate any decimals from the whole numbers
var num_array = num_str.split(".");
// if there are no decimals add them using "00"
if (num_array[1] == undefined) {
num_array[1] = "00";
}
// if the decimals are too short, add an extra "0"
if (num_array[1].length == 1) {
num_array[1] += "0";
}
// separate whole numbers with commas
// if required (comma = true)
if (comma) {
var whole_array:Array = new Array();
var start:Number;
var end:Number = num_array[0].length;
while (end > 0) {
start = Math.max(end - 3, 0);
whole_array.unshift(num_array[0].slice(start, end));
end = start;
}
num_array[0] = whole_array.join(",");
}
// construct a return string joining
// the whole numbers with the decimals
// and prefixing a currency symbol
return (currency + num_array.join("."));
}
trace(formatCurrency(1234.5, true, "£"));
// outputs £1,234.50
trace(formatCurrency(1234.5, true, "\u00a5"));
// outputs ¥1,234.50

Formatting numbers

This one comes up a lot - how to format a number with commas and decimal points? Just pass your number into this function and it will return a formatted string. Including commas is optional.


function formatNumbers(num:Number, comma:Boolean):String {
// return a zero value if num is not valid
if (isNaN(num)) {
return "0.00";
}
// round num to the nearest 100th
num = Math.round(num * 100) / 100;
// convert num to a string
var num_str:String = String(num);
// seperate any decimals from the whole numbers
var num_array = num_str.split(".");
// if there are no decimals add them using "00"
if (num_array[1] == undefined) {
num_array[1] = "00";
}
// if the decimals are too short, add an extra "0"
if (num_array[1].length == 1) {
num_array[1] += "0";
}
// separate whole numbers with commas
// if required (comma = true)
if (comma) {
var whole_array:Array = new Array();
var start:Number;
var end:Number = num_array[0].length;
while (end > 0) {
start = Math.max(end - 3, 0);
whole_array.unshift(num_array[0].slice(start, end));
end = start;
}
num_array[0] = whole_array.join(",");
}
// construct a return string joining
// the whole numbers with the decimals
return (num_array.join("."));
}
trace(formatNumbers(1234));
// outputs 1234.00
trace(formatNumbers(1234.56));
// outputs 1234.56
trace(formatNumbers(1234.5, true));
// outputs 1,234.50
trace(formatNumbers(-1234.56789, true));
// outputs -1,234.57

Monday, August 4, 2008

Numbers to words in Flash

It is sometimes necessary to convert a given number into its equivalent value in words.

At first this might appear to be a daunting and complex task but, fortunately, the method for formulating spoken numbers in English can be broken down into a set of simple rules. These rules are then applicable for any number, regardless of its size:

  1. if the number value is zero then the number in words is 'zero' and no other rules apply.
  2. all numbers can be split into groups of three digits starting from the right-hand side. Each group of three digits can then be processed individually to obtain their hundreds, tens and unit word equivalents.
  3. if the hundreds portion of a three-digit group is not zero, the number of hundreds is added as a word. If the three-digit group is exactly divisible by one hundred, the text hundred is appended. If not, the text hundred and is appended, for example three hundred or one hundred and forty six.
  4. if the tens section of a three-digit group is two or higher, the appropriate -ty word (twenty, thirty, etc.) is added to the text and followed by the name of any non-zero third digit. If the tens and the units are both zero, then no text is added. For all other values, the name of the one or two-digit number is added as a special case.
  5. each group of three digits can be recombined with the addition of any relevant scale number (thousand, million, billion) separated by a comma, unless the group is blank in which case it's not included at all. The exception to this rule is when the final group of three digits does not include any hundreds and there is more than one non-blank group. In this case, the final comma is replaced with and, for example one million and forty six.
  6. negative numbers are preceded by a word to indicate this negativity, for example Minus

The following function obeys all of the above rules by, firstly, splitting any given number into groups of three digits which are stored as individual elements in an array. Secondly, it then converts each of the elements from this array into its equivalent value in words, using the rules outlined above, and stores them into a new array. Finally, it takes the new array, recombines all of the elements, and applies any additional formatting to produce the returned string:


function NumberToWords(num:Number, display:Number, minus:String):String {
if (minus == null) {
minus = "Minus";
}
var smallNumbers:Array = new Array("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
var tenNumbers:Array = new Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety");
var scaleNumbers:Array = new Array("", "Thousand", "Million", "Billion");
if (num == 0) {
return smallNumbers[0];
}
var digitGroups:Array = new Array();
var positive:Number = Math.abs(num);
for (var i:Number = 0; i < 4; i++) {
digitGroups[i] = Math.floor(positive % 1000);
positive /= 1000;
}
groupText = new Array();
for (var i:Number = 0; i < 4; i++) {
groupText[i] = digitGroupToWords(digitGroups[i]);
}
function digitGroupToWords(threeDigits) {
groupText[i] = "";
var hundreds:Number = Math.floor(threeDigits / 100);
var tensUnits:Number = Math.floor(threeDigits % 100);
if (hundreds != 0) {
groupText[i] += smallNumbers[hundreds] + " Hundred";
if (tensUnits != 0) {
groupText[i] += " and ";
}
}
var tens:Number = Math.floor(tensUnits / 10);
var units:Number = Math.floor(tensUnits % 10);
if (tens >= 2) {
groupText[i] += tenNumbers[tens];
if (units != 0) {
groupText[i] += " " + smallNumbers[units];
}
} else if (tensUnits != 0) {
groupText[i] += smallNumbers[tensUnits];
}
return groupText[i];
}
var combined:String = groupText[0];
var appendAnd:Boolean;
appendAnd = (digitGroups[0] > 0) && (digitGroups[0] < 100);
for (var i:Number = 1; i < 4; i++) {
if (digitGroups[i] != 0) {
var prefix:String = groupText[i] + " " + scaleNumbers[i];
if (combined.length != 0) {
prefix += appendAnd ? " and " : ", ";
}
appendAnd = false;
combined = prefix + combined;
}
}
if (num < 0) {
combined = minus + " " + combined;
}
switch (display) {
case 0 :
// Upper case
combined = combined.toUpperCase();
break;
case 1 :
// Sentence case
combined = combined.substr(0, 1) + combined.substring(1).toLowerCase();
break;
case 2 :
// Lower case
combined = combined.toLowerCase();
break;
default :
// Capitalised
break;
}
return combined;
}

The function accepts three arguments:

  1. the number to be converted into words, e.g. 474635
  2. a value representing the case of the returned string of words:
    0 = upper case, e.g. ONE HUNDRED AND EIGHT
    1 = sentence case, e.g. One hundred and eight
    2 = lower case, e.g. one hundred and eight
    3 = capitalised, e.g. One Hundred and Eight
    The default is 3
  3. the prefix to signify a negative number, e.g. Negative
    The default value is Minus
Examples of the function's usage are shown here:


// default use
trace(NumberToWords(123456789));
// lower case
trace(NumberToWords(123456789, 1));
// upper case with an alternative negative prefix
trace(NumberToWords(-123456789, 0, "negative"));