2011-01-31 27 views
0

基本上我需要快速變化數字的「圖像」。我正在計劃將這些系列中的一系列,像矩陣(數字如何反覆變化)。我希望他們基本上以相當快的速度生成0-9的數字(有點像秒錶上的毫秒),直到我將它們淡出爲止。Flash:隨機生成0-9重複的數字

我是相當新的閃光,所以如果你們可以幫我一個代碼,我將不勝感激!

回答

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

爲什麼你使用`setInterval`代替遞歸`Timer`? – 2011-01-31 23:03:43

+2

@Matt McDonald,`setTimeout` /`setInterval`比`Timer`重量輕,因爲它是一種語言結構。如果你知道你在做什麼,他們可以創造奇蹟。爲了幫助新手使用閃光燈,我建議使用'計時器'。 – zzzzBov 2011-01-31 23:15:04

1

只是一個快速提示:鑄造號碼(所述的Math.random()* 10)爲一個int

int(n); 

不一樣

Math.floor(n); 

,是方式更快。 我們可以通過添加0.5〜ň

int(n + .5); 

和Math.ceil()加入1結果

int(n) + 1; 

在這裏得到一個Math.round()是一個循環來檢查:

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

這一點,不應該跟蹤什麼:)