randompaul
randompaul

Reputation: 1

getting a random element from an array of movieclips(or labels in a timeline) in Flash CC . Actionscript 3

I am making a pretty neat quiz-game in flashCC right now and I definitely need your help. My skills are more on the design then the programming side. So to many of you this might seem a baby question (and asked many times before) but from all the answers I saw so far, I couldn't get any results for my project.

So here is the thing : I need the EXACT script for creating an array (with movieclips inside? or instance names of mcs? How does this even work?) and a method, to pick a random element of this array without repeats until the "game is over".

Paul

Upvotes: 0

Views: 109

Answers (2)

gabriel
gabriel

Reputation: 2359

You could try something like:

var array:Array = [1, 2, 3, 4, 5];
var shuffledArray:Array = [];
while (array.length > 0) 
{
    shuffledArray.push(array.splice(Math.round(Math.random() * (array.length - 1)), 1)[0]);
}

trace('shuffledArray: ', shuffledArray, '\nrandom item: ', shuffledArray[0]);

Upvotes: 0

Marcela
Marcela

Reputation: 3728

The easiest way to pick a random element from an array without repeating is to first sort the array with a "random" function, then pop or shift items out of it until the array is empty.

Let's say you have an array of items which can be filled with either instances or instance names, you've chosen instance names: :

var FirstArray:Array = ["blau", "orange", "green"];

Now, you'll need a random sort function:

// you do not need to modify this function in any way. 
// the Array.sort method accepts a function that takes in 2 objects and returns an int
// this function has been written to comply with that    
function randomSort(a:Object, b:Object):int
{
    return Math.random() > .5 ? -1 : 1;
}

The way a sort function normally works is it compares two objects and returns -1 if the first item precedes the second item, 1 if the opposite is true, and 0 if they are the same.

So what we're doing in the function above is returning -1 or 1 randomly. This should get the array all jumbled up when you call:

FirstArray.sort(randomSort);

Now that the array is randomly sorted, you can begin pulling items from it like so:

if(FirstArray.length) // make sure there's at least one item in there
{
    // since you are using instance names, you'll need to use that to grab a reference to the actual instance:
    var currentQuizItem:MovieClip = this[FirstArray.pop()];
    // if you had filled your array with the actual instances instead, you would just be assigning FirstArray.pop() to currentQuizItem
    // every time you call pop on an array, you're removing the last item
    // this will ensure that you won't repeat any items
    // do what you need to do with your MovieClip here
}
else
{
    // if there aren't any items left, the game is over
}

When strung together, the above code should be enough to get you up and running.

Upvotes: 1

Related Questions