Random numbers generator - as3

Random numbers are an indispensable part of many Flash applications, but sometimes the simplest code can cause problems. Recently I needed a simple random number generator that of a pool of numbers will draw 10 random numbers. Below I present a simple code and source files for download, for those interested :-)

Here is the whole code of the random numbers generator, the following will describe exactly how it works.

import flash.events.MouseEvent; 
btn.addEventListener(MouseEvent.CLICK, deal); 
var total:int = 10; 
var startNum:int = 1; 
var endNum:int = 400; 
function deal(e:MouseEvent):void{ 
    for (var i:int; i < total; i++) { 
        var j:int = i+1; 
        var myNum:Number = Math.ceil(Math.random() * endNum) + startNum;
        trace(myNum); this["t"+j].text = String(myNum); 
    } 
}

2.Listening for whether the button was clicked

btn.addEventListener(MouseEvent.CLICK, deal);
//the scene has the movieclip with instance name "btn" when clicked will start function "deal"

3.Defining variables

var total:int = 10;
//count of numbers to be drawn

var startNum:int = 1;
//The first number from which to begin to draw, because I do not want to draw from the default 0 at this point I type 1, but you can use any number you want

var endNum:int = 400;
//maximum number to draw from, in this case 400

4.Function generating random numbers

function deal(e:MouseEvent):void{ 
    for (var i:int; i < total; i++) { 
        var j:int = i+1; var myNum:Number = Math.ceil(Math.random() * endNum) + startNum; trace(myNum); 
        this["t"+j].text = String(myNum); 
    }
}

When the function is called by a specyfic event, in parentheses should be mentioned on what type of event, this function has to respond. Since the function is fired on mouse event, type (e: MouseEvent) "e" is short for event, but you can type anything there, I use the "e" because it is shorter.

Then the "for" loop generate random numbers. The method of obtaining the random number in actionscript 3 I described in detail in the article:  actionscript 3 random

Pobierz plik