pizza0502
pizza0502

Reputation: 343

[AS3]Randomly do something without repeat

I've 3 movieclip on stage which is mc1,mc2,mc3 at first they are alpha=0

What I want is when i click on revealBtn, 1 of them will show up as alpha=1.

But with my code below, sometimes I need to click about 5 times or more only can make all those mc show up.

Is there any solution for what I wanted? I've try splice but it's still not working well.

var mcArray:Array = [mc1,mc2,mc3];
for (var j:int = 0; j < mcArray.length; j++)
{
    mcArray[j].alpha = 0;
}

revealBtn.buttonMode = true;
revealBtn.useHandCursor = false;
revealBtn.addEventListener(MouseEvent.CLICK, revealClick);

function revealClick(event:MouseEvent):void
{
    var i:Number = Math.floor(Math.random() * mcArray.length);
    var movieClipToEdit:MovieClip = mcArray[i] as MovieClip;
    movieClipToEdit.alpha = 1;
}

Upvotes: 0

Views: 1112

Answers (2)

Michael Antipin
Michael Antipin

Reputation: 3532

Here's one of the many possible solutions. It destroys the initial array though. If you don't want to change the initial array, the rest depends on what you actually want to achieve.

var invisibleList:Array = [mc1,mc2,mc3];
for (var j:int = 0; j < invisibleList.length; j++)
{
    invisibleList[j].alpha = 0;
}

revealBtn.buttonMode = true;
revealBtn.useHandCursor = false;
revealBtn.addEventListener(MouseEvent.CLICK, revealClick);

function revealClick(event:MouseEvent):void
{

    if (invisibleList.length == 0) {
        return;
    }
    var i:Number = Math.floor(Math.random() * invisibleList.length);    
    var movieClipToEdit:MovieClip = invisibleList[i] as MovieClip;
    invisibleList.splice(i, 1);
    movieClipToEdit.alpha = 1;
}

Upvotes: 1

Joshua Honig
Joshua Honig

Reputation: 13215

Make a second array to use as your selection source. Every time you pick an item, Splice it from the second array. Also, since all your items are MovieClips you should use a Vector instead.

var mcVector:Vector.<MovieClip> = [mc1,mc2,mc3]; 
var vector2:Vector.<MovieClip> = mcVector.Slice(0); // This just copies the Vector
for (var j:int = 0; j < mcVector.length; j++) 
{ 
    mcVector[j].alpha = 0; 
} 

revealBtn.buttonMode = true; 
revealBtn.useHandCursor = false; 
revealBtn.addEventListener(MouseEvent.CLICK, revealClick); 

function revealClick(event:MouseEvent):void 
{ 
    var i:Number = Math.floor(Math.random() * mcVector.length); 

    // Retrieves and deletes the item in one step:
    var movieClipToEdit:MovieClip = vector2.Splice(i, 1); 
    movieClipToEdit.alpha = 1; 
} 

Upvotes: 0

Related Questions