Thursday 5 November 2009

Decimal to Fraction

This class will be very handy to transform a decimal number to a fraccion. This was taken from forum entry in Actionscript.org and the user "rondog" converted a AS2 class to AS3. This is one more place where you can get it.

package com.lookmum.util
{
    public class Fraction
    {
        private static var it         :Number = 0;
        public static var iterationLimit:Number = 10000;
        public static var accuracy    :Number = 0.00001;
        
        public function Fraction()
        {
            
        }
        
        private static  function resetIt():void
        {
            it = 0;
        }
        
        private static  function addIt():Boolean
        {
            it++;
            if (it == iterationLimit)
            {
                trace('error : too many iterations');
                return true;
            }
            else
            {
                return false;
            }
        }

        public function getFractionString(num:Number):String
        {
            var fracString:String;
            var fracArray:Array = getFraction(num);
            switch (fracArray.length)
            {
                case 1 :
                    fracString = num.toString();
                    break;
                case 2 :
                    fracString = fracArray[0].toString() + '/' + fracArray[1].toString();
                    break;
                case 3 :
                    fracString = fracArray[0].toString() + ' ' + fracArray[1].toString() + '/' + fracArray[2].toString();
                    break;
            }
            return fracString;
        }
        
        public function getFraction(num:Number):Array
        {
            var fracArray:Array = new Array();
            var hasWhole:Boolean = false;
            if (num >= 1)
            {
                hasWhole = true;
                fracArray.push(Math.floor(num));
            }
            if (num - Math.floor(num) == 0)
            {
                return fracArray;
            }
            if (hasWhole)
            {
                num = num - Math.floor(num);
            }
            var a:Number = num - int(num);
            var p:Number = 0;
            var q:Number = a;
            
            resetIt();
            
            while (Math.abs(q - Math.round(q)) > accuracy)
            {
                addIt();
                p++;
                q = p / a;
            }
            fracArray.push(Math.round(q * num));
            fracArray.push(Math.round(q));
            return fracArray;
        }
    }
}

Monday 26 October 2009

Instantiate from library by class name

This maybe is one of the best hints for any as3 developer.

You have several objects in the Library, and some of them have sequenciall names, like "obj1", "obj2", "obj3"... and so on.

Normally if you want to instanciate an object from the library you would do like this:

var obj1:obj1=new obj1();
var obj2:obj2=new obj2();
...

What do you think... tedious, right? and not eficient, at all.

One of the solutions is to use the flash.util class that as a method called getDefinitionByName, wich can help a lot on this sort of thing.

By the upper example you just need a FOR cycle to instantiate all the objects. Imagine that I have from obj1 to obj5, this is how I would do it:

import flash.util.*;

private function instObj():void{
  for(var i:Number=1; i<6; i++){
    var name:String="obj"+i;
    var object = new (getDefinitionByName(name) as Class)();
    addChild(object);
  }
}

Sunday 25 October 2009

Generalize Methods

This one I saw in the "Actionscript 3 Cookbook" by Joey Lott, Darron Schall, Keith Peters and published by O'Reilly. Although it's on the first chapter of the book, it may come handy most of the times.


This recipe applies when you have a method and you want to use it several times, but with slightly different numbers of arguments, like calculating the average number. You can calculate the average between 2 numbers, or maybe, 7.


Lets  make a example:

public function average (num1:Number, num2:Number):void{
   trace("The average number is: "+(num1+num2)/2;
}

You call this method like this:

average(3,6);

The answer will be:

The average number is: 4.5

So how can I call the average method with a different number of arguments?


In the first place, you don't specify the number of arguments you put in the method, when you define it.
 Then, you must have a cycle inside the method, that will read all the arguments when you call it. 
Do it like this:

public function average():Number{
  var sum:Number=0;


  for(var i:Number=0; i
     sum+=arguments[i];
  }
  
  return sum/arguments.length;
}

The keyword arguments will retrieve the number and the value of the arguments that you place when you call a method.


then call the function like this:


var value:Number=average(2,3,4);


or


var value:Number=average(5,6,7,8,9,10);




This is a nice feature

Friday 16 October 2009

How to Format Text in Actionscript

This time I will post a snippet about how to format text in a textfield that is placed dynamicaly in the Stage.


Firstly you must insert the TextField on the stage. For that you need to place these two line in order to import the class that controls the TextField object in AS3. The second import, will import the class that control the appearence of TextFields:



import flash.text.TextField;
import flash.text.TextFormat;

Next you need to create the TextField and place it in the DisplayObject list:

var myText:TextField = new TextField();
addChild(myText);

Next you can tell Flash if the user can select the text, and if you want some border around the TextField:



myText.selectable = false;
myText.border = false;


Next you can tell if the TextField is autosizable, that is, if the text inside is to be dynamic, maybe you need the TextField to stretch or shrink, according to the text value. You can even tell if the autosize is to the right, center or left:


myText.autoSize = "center";


Now we're ready to format the contents of the TextField. For that you need to create a TextFormat object that will be associated to the TextField later on.


Create the TextFormat object:


var myFormat:TextFormat = new TextFormat();


Define the font face you want to use. Then you can define if the text is to bold, underline or italic:


myFormat.font = "Myriad Pro";
myFormat.bold = true;


Give it some colour:


myFormat.color = 0xFF0000;


Change the size:


myFormat.size = 12;


Finally associate the TextFormat to the TextField:


myText.setTextFormat(myFormat);


Happy Texting...

Tuesday 6 October 2009

AS3 Sandbox

Flash has some issues towards using foreign information, that is, you have an SWF file that has to access an external XML file, or other type of file. When this type of error occurs, you will get (if you have the Flash Player Debugger) a sandbox violation.

You have two ways to solve this... one that requires PHP or ASP, or any other script language knowledge, and the other requires that you have access to the source server (the one that has the information that you require).

This example will be to retrieve XML data, for example, a WebService.

1. By PHP, ASP or other script language (I will focus on PHP)
In order to do this you have to establish a "proxy" file, wich is, a file that will retrieve the data for you.
It works this way: In the same directory where the SWF file is you have to put a PHP (or ASP, or...) file that has a command to get the information. This is very simple.

In the SWF side:

 
function loadNews():void {
   var loader:Loader = new Loader();
   xml_NwsLoader.addEventListener(Event.COMPLETE, loadXMLNews, false, 0, true);
   xml_NwsLoader.load(new URLRequest("http://example.com/proxy.php"));
}

Notice that I will not call the XML file but a PHP one.

In the PHP side you must put a simple address call to get the data you want.

 
You can always look for a example and download files for Coldfusion, PHP, ASP and Java Servlet at this URL
http://kb2.adobe.com/cps/165/tn_16520.html

2. Using crossdomain
For this technique is supposed that you have access to the server where the XML file, or webservice is.

You must put a file at the server root called crossdomain.xml

You can see examples of this in detail in the Adobe site
http://kb2.adobe.com/cps/142/tn_14213.html


Cheers.

Monday 17 August 2009

Strings and Arrays

Continuing my last message about "String operations" some more usefull functions to use with strings. These allow you to receive a all string and separate them into data chunks that you can put in a array. It's usefull if get data like a cvs file, where all data is separated with a comma, ou semicollom(;)

var rainbow:String="red;orange;yellow;green;cyan;blue;violet";

1. Split string into an array using the (;)
trace(rainbow.split(";"));
or
var colourArray:Array=rainbow.split(";");

This will split the string in all the colors that are separated by the ";" symbol, and put them in a array

2. Split string a few times only
trace(rainbow.split(";",3));
or
var colourArray:Array=rainbow.split(";",3);

This will do the same as above, but limited to three splits

========================================

There's another operation that is even more powerfull... the combination of Split with Join.
This allow you to search for a word in text and replace it with another

1. To remove a repeating word in text
var rainbow:String="red then comes orange then comes yellow then comes green then comes cyan then comes blue then comes violet";

rainbow=rainbow.split(" then comes ").join("");

trace(rainbow);

2. Replacing words
var rainbow:String="red then comes orange then comes yellow then comes green then comes cyan then comes blue then comes violet";

rainbow=rainbow.split(" then comes ").join(";");

trace(rainbow);

String operations

Dealing with String sometimes gets you wonder "How can I split this?", "Can I extract that?".

Well, AS3 has some pretty function that manage to do this, but sometimes, the documentation gets you wonder how practical it is.

So here are some examples for common operations with Strings:

My string:

var myString:String="Always speak the truth, think before you speak, and write it down afterwards.";

==============================================

1. Show the first character
var fstChar:String=myString.charAt(0);

2. Output the first 6 characters
var sixChar:String=myString.substring(0,6);

3. Output from the sixth character
var fromSixth:String=myString.substring(6);

4. Slice the string from the 8th to the 12th character (basically will to the same has the substring)
var eigthToTwelve:String=myString.slice(8,12);

5. Search for a word and output it's position
var search:String=myString.search("truth");

6. Convert all letters to lower case
var lowerCase:String=myString.toLowerCase();

7. Convert all letters to upper case
var upperCase:String=myString.toUpperCase();

8. Length of a string
var howBig:Number=myString.length;

9. Concatenation... or adding something to the string (String are not like numbers, you can't add an "a" to a "b", so the operation "a"+"b" will result in "ab")

10. Replacing text with other text (this might get trickier)
var rplcText:String=myString.replace(myString.substring(0,6),"sometimes");
(this will replace the word "Always", wich is between character 0 and 6, and replace it with the word "sometimes")

Hope it helps someone.

Welcome

Hi everybody,

I thought of creating this blog, mostly because there are small pieces of code, that can be recycled to different situations.
We all can find some pieces of code and keep a bookmark for the web page that contains it, but sometimes it's not praticall to have scattered pages with the code we need, and some pages, will eventually, be offline or disappear.

So with this in mind I'me creating this blog to help me, and all of you that will find some of the snippets usefull.

Althought it's called "AS3 Snippets", wich is main programming language that I use, it's not exclusive to it. If you think some sort of snippet will be usefull to everyone, please email it to me, to include.

Thank you.