简体   繁体   中英

Randomize frames with no repeats with html5 javascript

Super noob question here. I have the code below from an as3 project below where frame numbers are randomized then clicking a sprite (next) will move to the next random frame. I am having trouble figuring out what else I need to do to convert it to javascript. Can anyone help me out or point me in the right direction? TIA!

var sortedNumbers:Array = [];
for(var i:int = 1; i < 21; i++)
{
    sortedNumbers.push(i);
 }
var unsortedNumbers:Array = sortedNumbers.slice();

while(sortedNumbers.join() == unsortedNumbers.join())
{
    unsortedNumbers.sort(function (a:int, b:int):int { return Math.random() > .5 ? -1 : 1; });
}

this.start.addEventListener("click", f_nextRE.bind(this));

function f_nextRE() {
        if(index == 20) {
    gotoAndStop (22);
    }
    else {
    gotoAndStop (unsortedNumbers [index] + 1);
    index +=1;  
    }
}

So it took me a few days but I found my answer (a combination of several sources many on this site)... Posting it here to help others...

//create array
var shuffledFrames = [];
//fill array
for (var i = 1; i <= 35; i++) {
   shuffledFrames.push(i);
}
//shuffle array 
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
   }
}
//run shuffle function
shuffle(shuffledFrames);
//function to call next random frame then repeat when reaching the end. 
function f_next()
{
    if (shown == 1){
        if (nextF == 35) {
            nextF = 0;
            }
        else {
        nextF += 1;
        }
    this.gotoAndStop (shuffledFrames [nextF]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM