Most object oriented programing languages are divided into two categories.
  1. Primitive Data types
  2. Reference Data types

Primitive Data types:
Primitive data types are handled "by value" and the actual primitive values are stored in address which can be passed/retrieved within the other functions. For example, the primitive data types in flash are String, Boolean, int, uint and Number.

Reference Data types:
The other non-primitive data types in OOP programing is called "Reference data types" such as Objects and Arrays. Reference data types are handled "by references" and the address of the objects and arrays are stored in a value which can be passed/retrieved within the other functions. Reference data types in flash are Classes, Objects, Arrays, Interfaces and packages.
 
Type Casting is the process of converting/transforming the value of a one datatype into another datatype's value. For example, you can use the movie clip as sprite using "as" in AS3.

To change the type of number and string we can use the following codes.

// Changing a number as string
var myNum:Number = 10;
var myStr:String = String(myNum)
trace(myStr);

// Changing a Boolean value as Number
var myBool:Boolean = true;
var myNum:Number = Number(myBool);
trace(myNum);

Typecasting in AS3 is even simpler than as2. We can use "as" to type casting. For example, if you want to change an object to array, it is very easy in AS3.

// Changing a object to an Array
var obj:Object = new Object();
obj = [1,2,3,4];
var b:Array = new Array()
b = obj as Array;
trace(b);

 
Facebook is becoming very popular and bringing more advanced options every month and attracting the members.  I like mindjolt facebook application and i enjoyed almost all the games. Tower Stacker is one of game i like the most from mindjolt. That game is a simple game and a very interesting game too. So, I planned to create the same game in AS3. I know that game needs some math functions like "atan2" to swing the holder.
Objective of this game:
  1. Holder should pick a new tower ball and start to swing
  2. Holder should place the ball on the selected location
  3. Again a new ball will be generated and started swing. If the recent ball placed on the line of the previous ball, the ball is on the stack or it will fall down from the stack.
  4. The score is based on the exact location of the recent ball with the last ball placed on the stack.
To swing the holder every time right after picking the new ball, we need pythagoras theorem, atan2(x1-x2)*degrees/PI, this will swing the holder one time, to make it oscillate I have to detect two x positions for start and end and need decrease/increase the speed of the oscillation based on the direction like,

rope_mc.rotation=Math.atan2(rope_mc.x-xSpeed,ySpeed)*90/Math.PI;

to make it swing, I am multiplying the speed with -1 on each swing like,

if (holderStatus=="swing") {
                if (xSpeed>=540||xSpeed<=50) {
                    speed*=-1;
                }
                xSpeed+=speed;
}

Now I should drop the ball on each mouse click, and placed the ball on stack based on some conditions. I used a separate movieclip to have the base of the stack and to add the balls each time on mouse click. From the second ball, each ball will be placed on the stack only if it is hit the previous one in a least best position. The score will be calculated based on the position it placed on the stack.
You like it? Let me come with some other game soon.
 
I have worked with AS2 LocalConnection, but this time I wanted to check what are the new options included with AS3 localConnection. LC is used for creating communication between the SWFs. Check out the following two swfs which is created in AS3. Moreover everything is same about LC in AS2 and AS3 and only the difference is event listeners.

Sender SWF:
Receiver SWF:
Sender:

package{
    import flash.display.*;
    import flash.net.*;
    import flash.events.*;

    public class FirstClassDoc extends Sprite{
        private var senderConnect:LocalConnection;
        public function FirstClassDoc():void{
            trace("Document Initiated");
            senderConnect = new LocalConnection();
            senderConnect.addEventListener(StatusEvent.STATUS,onStatusEvt);
            send_btn.addEventListener(MouseEvent.CLICK, onSendClick);
            //senderConnect.send("lc_id", "callFromSender","Checking");
        }
        private function onSendClick(evt:Event){
            senderConnect.send("lc_id", "callFromSender", send_txt.text);
        }
        private function onStatusEvt(evt:StatusEvent){
            trace(evt.level);
        }
    }
}


Receiver:
package{
    import flash.display.*;
    import flash.net.*;
    import flash.events.StatusEvent;

    public class SecondClassDoc extends Sprite{
        private var receiverConnection:LocalConnection;
        public function SecondClassDoc():void{
            trace("Document 2 Initiated");
            receiverConnection = new LocalConnection();
            receiverConnection.client = this;
            receiverConnection.connect("lc_id");
        }
        public function callFromSender(str:String){
            lc_txt.text = str;
        }
    }
}
 
The codes written between the #initclip and #endinitclip in movieclip from a Flash file (Fla) library that has been attached somewhere in the same flash file by using the linkage id will be executed first before the codes in the first frame of that movieclip. But, this option is completely removed from AS3.

The exact place where it is useful is the user defined component. Component should have pre-defined classes before its been used somewhere. For default components we don't need this as they are already linked. But for user defined components we should use this to register the movieclip as component and initialize the component classes before its been used somewhere. Check the simple code. The following code is written in a movieclip which will be attached to the stage using the linkage id.

AS2:
trace("Normal Check");
#initclip
trace("Check");
#endinitclip
trace("Check Again");


When you run the file it will trace in the following order.

Check
Normal Check
Check Again

So, the code we have written between #initclip and #endinitclip excutes the codes first before the other codes written in the first frame.

What is the use of Object.registerClass?

This can be used in custom component creation to register a class to a movieclip that will be attached using the linkage id. See the code,

AS2: (inside a movieclip on first frame)
#initclip
function DrawRectangle() {
    this.setPosition(this.x, this.y);
    this.drawShape(this.width, this.height, this.colour);
}
DrawRectangle.prototype = new MovieClip();
DrawRectangle.prototype.setPosition = function(x, y) {
    this._x = x;
    this._y = y;
};
DrawRectangle.prototype.drawShape = function(width, height, colour) {
    this.beginFill(colour, 100);
    this.moveTo(0, 0);
    this.lineTo(0, height);
    this.lineTo(width, height);
    this.lineTo(width, 0);
    this.lineTo(0, 0);
    this.endFill();
};
Object.registerClass("myClip", DrawRectangle);
#endinitclip
 
As many flash developer do, I started implementing a small game in flash AS2 to step into Game Development. The game Tic Tac Toe, I have played this game many times in my mobile whenever I traveled a long distance. It's been always easy to play, win and lose sometimes. But when I was thinking about the logic behind this game, I decided to go with simple Matrix combination. I am always a matrix hater because it gives me indefinite loops sometime and crash my flash and make my system slow. But I had no choice for this game and I planned a matrix combination like the following one. A simple box matrix.

00                 01               02
10                 11                12
20                 21                22

I have separated my class files into Game.as, Logic.as and Object.as. By their names, they do separate jobs in this game. Game class will be generating the game platform and link the Object class and Logic class right after creating the game platform. Logic class will create the logic and then initiate the game process. Object classes will return games objects that are used and loaded into game platform at run-time. Lets see the game before we get into it.
The Logic for this game is working in two different way. One way is to act like another player (called PC man) and another way is to keep track of the user's (You) movement and check the game win scenarios. When Logic work as a PC Man, it will keep listening to the user movement first to check if there is any wining point for the user in the next move, if there is any then it will lock that next point otherwise it will pick one random places and place PC man coin there.

How logic works and checks:

If any one of the box is clicked, I am placing the user name of who clicked in that box. So, the user name is key to check all the boxes for win. So, I will check the horizontal boxes, vertical boxes and two side diagonal boxes for their user names. If all the three names are same, its should say someone has won the game already. Look into the source file for more details. I am working some other facebook flash game too. I will post it here soon.
tic_tac_toe.zip
File Size: 1191 kb
File Type: zip
Download File

 
Initially the flash players were introduced to focus on manipulating 2D animations. Later, a big revolution was created by some new support of flash players like streaming of audios/videos and capability of creating RIA (Rich Internet Application) using Flash. From Flash player 6, you can stream audio files and video files with the extension of .mp3 and .flv respectively.
FLV is a container format of video which can be played in flash player directly by either downloading or streaming. Based on this technology you can find there are more popular website increasing their visitors everyday like youtube, metacase and many other websites. Though there are other options to play the video files in internet, flash player are mostly welcome only because of its light weight and video file's size.

Advanced flash technologies lead us to another extension of Multiplayer Games, Audio/Video Recording and A/V Chat Communication. Adobe Flash Media Server is one of the Flash Supporting server which let us to create multiplayer games and a/v chat communications. Server side coding is the same actionscript as it is in Flash.

I was working on a product of youtube video player clone. I didn't want to clone the exact player and also wanted to add some new features which is not available in youtube and other website players.

After few months, I was planning to create another AS2 video player with some other different options. So, I started developing a brand new player from the scratch. First I created a new and unique design and then I planned to add some tween functions to make it more shining. This player supports mid-roll advertisements and pre-roll, post-roll HTML advertisements. This player supports progress downloading and streaming as well.

AS2 Video Player 2:

Same as the above one, I wanted to create another player in AS3 which supports some additional features and some additional video formats like mp4. This player is called HD Player which is capable of playing HD videos like H264, M4V, M4A, MOV, Mp4v, F4V, H.264 and FLV.

AS3 HD Video Player:
 
There is always some confusion about why we need singleton class instead of using static. I can explain it with few program samples. Lets create a singleton class first.
package {
   import flash.events.*;
   public class Singleton extends EventDispatcher {
    public static var singletonObj:Singleton;
    public static function getInstance():Singleton {
       if (singletonObj==null) {
            singletonObj = new Singleton();
       }
       return singletonObj;
     }
    public function callTrigger() {
     dispatchEvent(new Event("onTrigger"));
    }
   }
}


Now lets create other two classes which are going to use this singleton class. Lets say FirstClass.as and SecondClass.as.

FirstClass.as
package {
     import flash.events.*;
     public class FirstClass {
         var singletonObj:Singleton;
         var secClass:SecondClass;
         public function FirstClass() {
             secClass = new SecondClass();
             singletonObj=Singleton.getInstance();
             singletonObj.addEventListener("onTrigger", testEvent);
             singletonObj.callTrigger();
         }
         private function testEvent(evt:Event) {
             trace("FirstClass");
         }
    }
}

SecondClass.as

package {
    import flash.events.*;
    public class SecondClass{
        var singletonObj:Object = new Object();
        public function SecondClass() {
            singletonObj=Singleton.getInstance();
            singletonObj.addEventListener("onTrigger", testEvent);
        }
        private function testEvent(evt:Event) {
            trace("SecondClass");
        }
    }
}

Lets consider we have created an object for FirstClass  somewhere. Inside the constructor function of FirstClass, when callTrigger() function is fired, the singleton class will dispatch the same event for both FirstClass and SecondClass as they are sharing the same object of singleton class. So, by using the singleton we are controlling the two classes with only one central/common object.

singleton.zip
File Size: 8 kb
File Type: zip
Download File

 
OOPs: Object Oriented Programming
OOP is  Organizing a program around with its Data and set the well defined interface to the Data

What are the OOPs Concepts?
OOPs use the three basic components. Class , Objects and Methods. Additionally Inheritance, polymorphism, Abstraction, Event Handling and Encapsulation are the significant concepts of OOPs.

Types of Classes (AS3)

ActionScript 3.0 supports the following class attributes:

  • dynamic (allows properties to be added to instance at run time)
  • final (cannot be extended by another class)
  • internal (visible inside the current package)
  • public (visible everywhere)
Class Property Attributes

  • internal (visible inside the same package)
  • private (visible in the same class)
  • protected (visible in the same class and derived classes)
  • public (visible everywhere
  • static (specifies that a property belongs to the class, not to instances of the class)
Encapsulation

It is an ability to hide and protect the data. For example, getters and setters in a class. We don’t need to know about the properties we get from the getters, but we should know what should be sent to the setters. So these getters and setters are used to make your class properties private and also accessible by the other classes.

Inheritance

Inheritance is a form of a code reuse which allows programmers to develop new classes that are based on the existing classes. Advantage of inheritance is the way it allows you to reuse the code from the base class and leave the existing code unmodified.

Interfaces

Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. Implementing an interface allows a class to become more formal about the behavior it promises to provide. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. Lets see a simple code later in another post.

By using interfaces, you can maintain the consistency through-out the application. It will also make you (or anyone else editing/implementing your interfaces) to not leave any methods that is necessary to a class. It is more useful in cases where you can use more classes.

See at the end of this thread to download a sample interface classes in AS3.

Function Overloading

Function overloading is one attribute of Polymorphism in OOP. Writing two methods with the same name and different parameters is called Function Overloading. Function overloading is available in AS2 but AS3 do not support. See the code example.

function MyFun() {
   trace("Function");
}
function MyFun(msg:String) {
   trace(msg);
}

This sample will work with AS2 compiler but not with AS3 compiler. To overload a function in AS3, we can use the “*” as datatype for the parameter which will get any parameter type with the same function name and we can add our codes to behave according to the type of arguments.

function doSomething(obj:*) : int
{
  if (obj is int)
  // do int stuff
  else if (obj is String)
  // do string stuff
  else
  // what type did you give me?
}

Singleton Class:

Singleton class restrict the limit of instantiation of the objects. In other words, its a class which have only one object. For example, configuration data is stored in one singletone class, and objects for this class have initialized in many classes. In this case, data in configuration is important for all the classes, so everything is managed by a single object or central object. Any change in configuration can be easily notified for all linked classes.

interfaces_oop.zip
File Size: 8 kb
File Type: zip
Download File

 
Action Script:

  • It was originally developed by Macromedia Inc.
  • It is a specific group of ECMAScript. (Its a scripting language standardized by Ecma international which is a non-profit standards organization for Information and Communication Systems)
  • It has the same syntax and semantics of well known script JavaScript.
  • It was initially designed for 2D animation with simple vector graphics.
  • Later version are designed to focus on wide range of Rich Internet Application (RIA), Games and Streaming audio and videos.
  • Now, we have three version of AS, called AS1 , AS2 and AS3 (the latest one).
  • Flash version 1 to 6 supports AS, Flash 7 and 8 supports AS and AS2, all other versions supports AS2 and AS3.
  • AS2 is based on ECMAScript 4 which runs on AVM1 (ActionScript Virtual Machine1) whereas AS3 was introduced with some major improvement of performance in AVM1 (called as AVM2).
  • AS3 version has much improvement in performance with Flash player using Just In Time (JIT) compiler.
  • AS3 version supports Binary sockets, E4x XML parsing, Full-Screen Mode and inclusion of Regular Expression. Binary Sockets are used to work with  remote server connectivity.