Random Numbers: Math.Random()

In the previous example, we rolled dice. We know that dice have six sides and we used the constant 6 in the code.
In this example we will add a flower movie clip to the stage when we click and then select a random frame from the flower movie clip.

Get Adobe Flash player
  1. Start a new ActionScript3 movie.
  2. Create a movie clip called Flower with a different flower in each frame:
    4 flowers
  3. Make sure that you export it for ActionScript
    :Export for actionscript
  4. Create a green area and make it a movie Clip called Grass.
  5. Name the instance on the stage grass.
  6. Write the code to add flowers to the grass when you click on the grass:
grass.addEventListener(MouseEvent.CLICK,clickGrass);
function clickGrass(e:MouseEvent): void {
	var flwr: Flower=new Flower(); //create a new instance of the Flower
	flwr.x=e.localX; //same place you clicked on the grass
	flwr.y=e.localY;
	var n:int=int(Math.random()*flwr.totalFrames)+1; //random frame
	flwr.gotoAndStop(n); //stop at that frame
	grass.addChild(flwr); //add the new flower to the grass
}

Note: You can add more frames. The code will work no matter how many frames you have in the flower.

Experiment: Add a tree to the picture. Create leaf with various sizes and shades of green. Add them to the tree when you click.

Download the movie to experiment.

NEXT: Boolean values: True or False