as3防止连续两次选择随机帧标签

时间:2016-02-19 19:55:10

标签: flash actionscript-3

我写了一个小动作,基本上告诉影片剪辑去播放阵列中列出的随机帧。这是代码:

function getRandomLabel(): String {

    var labels: Array = new Array("e1", "e2", "e3");
    var index: Number = Math.floor(Math.random() * labels.length);
    return labels[index];
}
mc.gotoAndStop(getRandomLabel());

我想解决的问题是防止连续两次选择相同的随机帧标签。

2 个答案:

答案 0 :(得分:1)

如果你想要做的就是确保没有从列表中选择当前的帧标签,你可以通过简单地过滤出阵列中的当前标签来做到这一点:

function getRandomLabel(currentLabel:String):String {
    var labels:Array = ["e1", "e2", "e3"];
    var currentIndex:int = labels.indexOf(currentLabel);
    if (currentIndex > -1) 
        labels.splice(currentIndex, 1);
    var index:Number = Math.floor(Math.random() * labels.length);
    return labels[index];
}

mc.gotoAndStop(getRandomLabel(mc.currentLabel));

事实上,如果您要做的只是转到任何框架标签而不是当前框架标签,您可以使用MovieClip/currentLabels并将其作为任何可重复使用的功能MovieClip

function gotoRandomFrameLabel(mc:MovieClip):void {
    var labels:Array = mc.currentLabels.filter(function(frame:FrameLabel, ...args):Boolean {
        return frame.name != mc.currentLabel;
    });
    var index:int = Math.random() * labels.length;
    mc.gotoAndStop(labels[index].frame);
}

gotoRandomFrameLabel(mc);
gotoRandomFrameLabel(other_mc);

答案 1 :(得分:0)

我的建议是每ngetRandomLabel次调用将数组洗牌,其中nlabels数组的长度。随机播放时,请确保最近使用的标签不是数组中的第一项。

// this array can be of any length, and the solution should still work
var labels:Array = ["e1","e2","e3"]; 
var count:int = labels.length;
labels.sort(randomSort);

function getRandomLabel(): String {
    count--;

    var randomLabel:String = labels.shift();
    labels.push(randomLabel);

    // when the counter reaches 0, it's time to reshuffle
    if(count == 0)
    {
        count = labels.length;

        labels.sort(randomSort);
        // ensure that the next label isn't the same as the current label
        if(labels[0] == randomLabel)
        {
            labels.push(labels.shift());
        }
    }

    return randomLabel;
}

// this function will "shuffle" the array
function randomSort(a:*, b:*):int 
{
    return Math.random() > .5 ? 1 : -1;
}
相关问题