OOP PRINCIPLE:COMPOSITION – CREATING RANDOM NUMBER GENERATION CLASS

Creating multiple instances of the same class is called “Composition”. This simple few words single line definition describe the what is composition. but how to use this principle or how it works….

Here is the simple example i have created.

randomN.as [ Document class ]
[as3]
package{
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.utils.Timer;
import num;

public class randomN extends MovieClip{

private var create_timer:Timer;

// Constructor
public function randomN():void{
// generating random delay value
// between 500-1000 miliseconds
var delay:Number = Math.random()*800+200;
create_timer = new Timer(delay);

// Start creation
create_timer.addEventListener(TimerEvent.TIMER, create_number);
create_timer.start();
}

private function create_number(e:TimerEvent):void{
var number:num = new num();
addChild(number);
}
}
}

[/as3]

 

Inside the above given document class you can find the instances of the given below class.

num.as [ Random number generation class ]
[as3]
package{
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.text.*;
import flash.utils.Timer;

public class num extends MovieClip{

private var format:TextFormat = new TextFormat();
private var fade_timer:Timer = new Timer(100);

// Constructor
public function num(){
// setting up text format
format.color = Math.random()*0xFFFFFF;
format.font = “Arial”;
format.size = 50;

// Generating random number between 1 to 10.
var mynum:Number = Math.floor(Math.random()*9)+1;

// Creating textfield
var mytext:TextField = new TextField();
mytext.text = String(mynum);
mytext.setTextFormat(format);
mytext.selectable = false;
this.addChild(mytext);

// setting x,y position
this.x = Math.random()*500;
this.y = Math.random()*350;

// start fading this
fade_timer.addEventListener(TimerEvent.TIMER, fade);
fade_timer.start();
}

// fade transition
private function fade(e:TimerEvent):void{
var fade_val:Number = (10 – fade_timer.currentCount)/10;
this.alpha = fade_val;

if(this.alpha <= 0){
fade_timer.addEventListener(TimerEvent.TIMER, fade);
fade_timer.stop();
MovieClip(parent).removeChild(this);
}
}
}
}
[/as3]

Here you can find the source of the file.
Download source [randomN.zip]

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *