Saturday, 29 August 2009

Generate random numbers in Actionscript 3

In this tutorial you will learn how to generate random numbers in Actionscript 3. The random numbers are generated using the Math.random function. There are many ways of achieving the random number effect, but I will show you the most common method. Some knowledge of basic buttons is needed for this tutorial.


Generate random numbers in Actionscript 3

Step 1

Open a new Flash AS3 file.
Select the text tool with dynamic text and drag out a text box like below. I have checked the ‘show border around text’ button as well.



I have also included the message “random numbers” above the dynamic text box using a doubled knocked out text effect. Now give your dynamic text box the instance name: showRandom_txt.


Step 2

Create your basic button on the stage. I have used a default button which can be found at Windows > Components, but you can alternatively create your own button on the stage. For more information on buttons checkout the basic buttons tutorial.




Step 3

Give your button the instance name: generate_btn. If you have created your own button then you should first convert it into a symbol.




Step 4

On the timeline create a new layer called ‘Actions’ then select the first frame and hit F9 to open up the actions panel and enter the following code:

//1.
function randomNumbers(min:Number,max:Number) {
var Results:Number=Math.floor(Math.random()*max)+min;
return Results;
}

//2.
generate_btn.addEventListener(MouseEvent.CLICK, showRandomnumber);

//3.
function showRandomnumber(event:MouseEvent):void{
showRandom_txt.text = randomNumbers(1,100);
}

Code:

1. This is a function for generating the random numbers using the Math.Random function.
2. This add an event listener to the generate button with the mouse click event.
3. This is a function which displays the random numbers. Currently the random numbers range from 1 – 100, but you can change this to whatever you want by changing the numbers inside the parenthesis. The first number in the parenthesis refers to the minimum number and the second number refers to the maximum number.

Step 5

Test your random numbers Ctrl + Enter. Now click the generate button and you should get a random number between 1 and 100.




You should now be able to generate random numbers in Actionscript 3.0.

2 comments:

Bla 6 July 2013 at 20:07  

Could you also do a random name generator, aka. how to assign array to a generator?

iliketo 9 July 2013 at 13:59  

@Bla

Take a look at my Letter guessing game for an example.

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP