开发者

Randomly removing an array

just for the record, i'm using AS3.

I have an issue where I would like to remove a sprite randomly in AS3, I have managed to figure out how to create the sprites so that they fill as a grid, just for the life of me I can't figure out how to remove them!

Here's the code i've used to create them:

function showpixels() : void
{   

    for (var i:int = 0; i < 40; i++)
    {
        for (var j:int = 0; j < 40; j++)
        {
            var s:Sprite = new Sprite();
            s.graphics.beginFill(0);
            s.graphics.drawRect(i*10, j*10, 10, 10);
            s.graphics开发者_StackOverflow中文版.endFill();
            addChild(s);
            pixels.push(s);
        }
    }
}

Basically I need these to be removed randomly until what's underneath can be seen.

Any help would be good, I'm pretty new to this! Thanks!


function removeRandom():void
{
    var rand:uint = Math.random()*pixels.length;

    var i:Sprite = Sprite(pixels[rand]);

    if(i.parent) i.parent.removeChild(i);
    pixels.splice(rand, 1);
}

UPDATE: To remove at random intervals you could try something like this:

var _timer:int = 100;

addEventListener(Event.ENTER_FRAME, _handle);
function _handle(e:Event):void
{
    if(pixels.length > 0) _timer --;
    if(_timer < 1)
    {
        _timer = 10 + Math.random()*50;
        removeRandom();
    }
}

function removeRandom():void
{
    var rand:uint = Math.random()*pixels.length;

    var i:Sprite = Sprite(pixels[rand]);

    if(i.parent) i.parent.removeChild(i);
    pixels.splice(rand, 1);
}


Marty's idea works. Another option would be to shuffle the array first and then just pop off elements.

To shuffle an Array use pixels.sort(function (...args):int { return int(2*Math.random()-1) }).

And then you can simple remove them like this:

function remove():void {
     if (pixels.length) removeChild(pixels.pop());
     else clearInterval(this.id);
}

And add this line at the end of showpixels:

this.id = setInterval(remove, 500);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜