开发者

Flash: Randomly generate numbers 0-9 repetitively

Basically I need the "image" of fast changing n开发者_开发知识库umbers. I am planning on having a series of these in a line, sort of like the matrix (how the numbers change repeatedly). I want them to basically generate the numbers 0-9 over and over pretty fast (sort of like milliseconds on a stopwatch), until I have them fade out.

I am fairly new to flash, so if you guys could help me out with a code I would greatly appreciate it!


As stated to get a random number between 0 and 9, Math.random is the way to go:

var n:int = Math.floor(Math.Random()*10);

But to address your second question, of how to get it so it does this every millisecond

import flash.utils.setInterval;
import flash.utils.clearInterval;

//variable for the intervalID, 
//and the variable that will be assigned the random number
var rnGenIID:uint, rn:int;

//function to update the rn variable 
//to the newly generated random number
function updateRN():void{
    rn = random0to9();
    //as suggested, you could just use:
    //rn = int(Math.random()*10);
    //but I figured you might find having it as a function kind of useful, 
    //...
    //the trace is here to show you the newly updated variable
    trace(rn);
}
function random0to9 ():int{
    //in AS3, when you type a function as an int or a uint,
    //so instead of using:
    //return Math.floor(Math.random()*10);
    //or
    //return int(Math.random()*10);
    //we use:
    return Math.random()*10;
}

//doing this assigns rnGenIID a number representing the interval's ID#
//and it set it up so that the function updateRN will be called every 1 ms
rnGenIID = setInterval(updateRN,1);

//to clear the interval
//clearInterval(rnGenIID);


just a quick tip: casting a Number ( the Math.random() * 10 ) into an int

int( n );

does the same as

Math.floor( n );

and is way faster. we can get a Math.round() by adding .5 to n

int( n + .5 );

and a Math.ceil() by adding 1 to the result

int( n ) + 1;

here's a loop to check:

var n:Number;
var i:int;
var total:int = 100000;
for ( i = 0; i < total;  i++ )
{ 
    n = Math.random() * 10;
    if ( int( n ) != Math.floor( n ) ) trace( 'error floor ', n );
    if ( int( n + .5 ) != Math.round( n ) ) trace( 'error round ', n );
    if ( int( n ) + 1 != Math.ceil( n ) ) trace( 'error ceil ', n );
}

this, shouldn't trace anything :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜