'randomize Background image in an array for a button for AS3

I have a sample code:

backgroundChange_btn.addEventListener(MouseEvent.CLICK, randomBG);
function randomBG(e: MouseEvent): void {
    var Background = new Array();
    Background[1] = "Ocean Floor.jpg";
    Background[2] = "Underwater Ruins.jpg";
    Background[3] = "Underwater Temple.jpg";
    Background[4] = "Background 1.jpg";
    Background[5] = "Background 2.jpg";
    Background[6] = "Background 3.jpg";
    Background[7] = "Background 4.jpg";
    Background[8] = "Background 5.jpg";
    var rnd = Math.floor(Math.random() * Background.length);
    if (rnd == 0) {
        rnd = 1;
    }
    var BG:Button = new Button();
    
}

Does anyone know how to randomize the background images from an array by clicking a button?

Now:

function randomBG(e: MouseEvent = null): void 
{ 
    rnd = Math.floor(Math.random() * Background.length); 
    if (rnd == 0) 
    { 
         //randomBG(); 
         game_BG.gotoAndStop(randomBG); 
    }
}


Solution 1:[1]

If you're getting undefined then...

  • Either your rnd is wrong (it points to a not-existing position of Array).
  • Or else the Array itself is not a valid object (so create it properly).
  • Finally (in AS3) you must add data types when declaring your variables.

See if this example helps you get a random number.

var rnd :uint = 0;
var BG :Button = new Button();
var Background :Array = new Array(9);

Background[0] = "empty";
Background[1] = "Ocean Floor.jpg";
Background[2] = "Underwater Ruins.jpg";
Background[3] = "Underwater Temple.jpg";
Background[4] = "Background 1.jpg";
Background[5] = "Background 2.jpg";
Background[6] = "Background 3.jpg";
Background[7] = "Background 4.jpg";
Background[8] = "Background 5.jpg";
    
backgroundChange_btn.addEventListener(MouseEvent.CLICK, randomBG);


function randomBG(e: MouseEvent = null): void 
{
    //# length is 9 so "minus 1" to get val between 0 to 8
    rnd = Math.floor( Math.random() * (Background.length-1) );
    
    //# if zero then re-run the function for a new random
    if (rnd == 0) { randomBG(); }
    
    //# check the results...
    trace( "Background is : " + Background ); //is Array?
    trace( "random num is : " + rnd ); //is between 1 and 8?
    trace( "random image  : " + Background[ rnd ]); //is JPG file name?
    
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VC.One