Flash:重复随机生成数字0-9

时间:2011-01-31 18:38:51

标签: flash actionscript-3

基本上我需要快速变化数字的“图像”。我计划在一行中有一系列这些,有点像矩阵(数字如何重复变化)。我希望他们基本上能够快速地反复生成数字0-9(在秒表上有点像毫秒),直到我让它们淡出。

我对flash很新,所以如果你们可以帮我解决一下代码,我会非常感激!

2 个答案:

答案 0 :(得分:2)

如上所述,要获得0到9之间的随机数,Math.random就是要走的路:

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

但要解决你的第二个问题,如何得到它,这样每毫秒就能做到这一点

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);

答案 1 :(得分:1)

快速提示:将数字(Math.random()* 10)转换为int

int( n );

相同
Math.floor( n );

并且速度更快。 我们可以通过将.5添加到n

来获得Math.round()
int( n + .5 );

和Math.ceil()通过在结果中添加1

int( n ) + 1;

这是一个要检查的循环:

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 );
}

这个,不应该跟踪任何事情:)