February 2010
M T W T F S S
« Jan   Mar »
1234567
891011121314
15161718192021
22232425262728

Generate a random number

Problem
Need show a random number on the stage.

Solution
Generate a random numbers with Math.random

Detailed explanation
Please flash cs4 professional program and create new document with Flash File(ActionScript 3.0) type.

rn1

On COMPONENTS area find Button and TextArea components and move it to the Stage.
On TOOLS area find ‘Free Transform Tool’ and make width for components bigger, for example 300.

rn21

rn3

rn4

For TextArea component create instance name numberOutput, and for Button component create name generateNumberBtn.

rn6

rn7

Change label for button to ‘generate number again’.
rn8

Create new layer for actions.

rn5

On Layer2 write code:

var minNumber:uint=1;
var maxNumber:uint=48;
var numberRange:uint=maxNumber-minNumber;
var
randomNumber:Number=Math.ceil(Math.random()*numberRange)+minNumber;

trace("our random number = "+" "+ String(randomNumber));
numberOutput.text="our random number = "+" "+String(randomNumber);

rn9

After this you can test a movie. So now your number will be randomly appears on the stage.

So now we need add some code for button.

generateNumberBtn.addEventListener(MouseEvent.CLICK, buttonClick);
generateNumberBtn.useHandCursor=true;
function buttonClick(event:MouseEvent):void {
gotoAndPlay(1);
}

rn10

After cliking the button we will cause function buttonClick.

Now you need insert frame to bouth layers.

rn11

And add next code to ACTIONS area:

stop();
gotoAndStop(2);

rn12

After this you can test movie your file. And click to button again and again. And you will see how your number will be randomly change.

rn13

In attached files you can find pictures preview with red areas borders. They can help you to clear all steps. Also .fla file with ready project.

Source:
my_random_number

Thank you for reading.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>