Random numbers

Flash Players 5 and above provide the Math class with a variety of functions including Math.random()

Math.random() takes no parameters and returns a number n, where 0 <= n < 1.

It can be used with the Math.floor() function (which selects the lowest whole number below the parameter) and multiplication to generate random whole numbers.

To simulate the roll of a die (1 - 6)
var x = Math.floor(Math.random()*6+1)

Used with the if statement it provides powerful control over movies.

You could use it 2 different ways:

  1. To randomly choose the next scene to go to
  2. To randomly decide which objects will appear in a scene.

-------------------------------------------------------------------------------------------------------------------------------

To choose the next scene randomly

The Script

Explanation

on(release) {

var winningcar = Math.floor(Math.random()*2+1) ;
trace("the winning car is " + winningcar);
if (winningcar = = 1) gotoandPlay("car1wins",1);
else gotoandPlay("car2wins",1);

}

when the button is released

randomly choose 1 or 2
for debugging, show the number chosen
go to the scene indicated

NOTE: The trace function allows you to see what is going on while you are testing a movie. It will not display anything when you publish your final swf movie. ALSO: the double equal sign should NOT have a space in the middle

 

  This movie consists of 3 scenes, the first scene has the button with the script above that decides which ending scene to play: car1wins or car2wins

 

----------------------------------------------------------------------------------------------------------------------------------

For this example there are 3 movie clips to choose from: papaBear, mamaBear or babyBear. To randomly decide which bear will be visible, place this code in the beginning frame of the timeline, after you name the movie clip objects that will be visible or not. These must be created as movie clips, dragged into the scene from the library and named in the properties panel.

var whichBear = Math.floor(Math.random()*3+1);
trace("the bear is " + whichBear);
if (whichBear == 1) {
papaBear._visible=true;
mamaBear._visible=false;
babyBear._visible=false;}
else if (whichBear == 2) {
papaBear._visible=false;
mamaBear._visible=true;
babyBear._visible=false;}
else {// this is whichBear = 3
papaBear._visible=false;
mamaBear._visible=false;
babyBear._visible=true;}