The demonstration project above shows use of the ActionScript random() function to jump to a different frame each time the mouse is clicked. If you watch closely, however, you'll see that though selections do recur, they never recur back-to-back: each time you click the mouse, you will always see an image different from the one you start with.
To achieve this effect, we constrain the random() method by keeping track of the last random number it generated and forcing it to try again if it comes up with the same number twice in a row. This technique is useful enough by itself (what's the point of being random if you're going to repeat yourself?), but it also demonstrates an important logical tool--the while loop.
Here's the script attached to the "click to change" button in this demo:
on(press){
while(randyOld == randy)
{
randy = random(15)+1;
}
randyOld = randy;
_root.gotoAndStop(randy);
}
Statements in a while loop execute continually as long as the governing condition remains true. If the actions within the loop change the condition, the loop terminates.
That's exactly what happens here. The loop begins with the two variables, randy and randyOld, equal to each other (when the program begins, both have a value of null). Because the two variables are equal, the while loop is activated, meaning that one of the variables, randy, acquires a new value. If that value is not the same as the value of randyOld, the while loop terminates. If it is the same, then the assignment statement is repeated and randy gets another value, which hopefully will meet our expectations.
Outside the while loop, two things happen. First, we reassign the value of randyOld to the current value of randy. Thus the next time this handler is invoked, the triggering condition on the while loop will be true and we will get a new random number. Once we have the random number we want, the movie jumps to a frame corresponding to this number (and since frames are numbered from 1, not zero, we have to add 1 to the random value).
You can adapt this logic to other situations in which you need to run through a range of possibilities until they either meet some expectation or you find one that fits.
If you're mainly concerned with random numbers, you can adapt this simple script to allow for multiple constraints--say you want to be sure the random number generator never hits the same number three times in a row. One solution is simply to add a variable:
on(press){
while(randyOld == randy || randyOlder = randy)
{
randy = random(15)+1;
}
randyOlder = randyOld;
randyOld = randy;
_root.gotoAndStop(randy);
}
The source file for the demo at the top of this page is called whileLoop.fla. It is available on Crow in multimediaShare/whileLoop.
