1

所以在我的闪光中,我有部分你可以选择哪种方式,你选择的那条道路应该有随机化,我正在尝试构建它,以便当用户选择一条道路时,他会被扔进其中一条3 个随机标记的帧,我什至考虑将一些随机化部分添加到一条最不可能发生的道路上。

    stop();

road1a.addEventListener(MouseEvent.CLICK, firstroadA);

function firstroadA(e:MouseEvent):void{
    if(this.currentFrame == 9){
        var randomNumber:Number = Math.floor(Math.random()*3)
        if (randomNumer == 0){
            gotoAndStop(10);
        }
        if (randomNumber == 1){
            gotoAndStop(11);
        }
        if (randomNumber == 2){
            gotoAndStop(12);
        }
    }
    else{
        nextFrame();
    }

}

在这个测试中,我试图让用户的选择发生在第 9 帧,当他选择点击 firstroadA 时,他会转到一些随机帧,10、11 或 12 ......所以,我希望我已经很清楚了;简而言之,我的问题是,如何随机化 gotoAndStop 帧,以及如何添加一些很少有机会选择 gotoAndStop 的稀有帧......谢谢!

4

1 回答 1

0

您可以根据需要使用加权随机数。查看此代码,它可以按照您的意愿执行:

stop();

gotoAndStop(9);

road1a.addEventListener(MouseEvent.CLICK, firstroadA);

function firstroadA(e:MouseEvent):void
{
    if(this.currentFrame == 9)
    {
        // These are the weight chance for each "road"
        // I used 30%, 50%, and 10% arbitrarily
        var choiceWeights:Array = [30, 50, 10];

        // frame choices
        var roadFrames = [10, 11, 12];

        // get a weighted random
        var r:int = makeChoiceWithWeight(choiceWeights);

        //go to the selected frame
        gotoAndStop(roadFrames[r]);
    }
    else
    {
        nextFrame();
    }
}

function makeChoiceWithWeight(choiceWeights:Array):int
{
    var sumOfWeights:int = 0;
    var numWeights:int = choiceWeights.length;

    // add all weights
    for(var i:Number = 0; i < numWeights; i++) sumOfWeights += choiceWeights[i];

    // pick a random number greater than zero and less than the total of weights
    var rnd:Number = Math.floor(Math.random()*sumOfWeights);

    //keep reducing the random number until less than a choices weight
    for(var ii:Number = 0; ii < numWeights; ii++)
    {
        if(rnd < choiceWeights[ii]) return ii;

        rnd -= choiceWeights[ii];
    }

    // should never reach this point
    return 0;
}

要更深入地了解加权随机数,请查看此 SO 答案: Weighted random numbers

于 2012-11-07T16:49:17.037 回答