1

so on my flash, I have parts where you have option which way to choose, and that road you choose should have randomization in them, and I am trying to build it so that when user chooses one road, he is thrown into one of the 3 labeled frames randomly, and I have even considered of adding some of the randomization parts a road that has most least chance to happen.

    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();
    }

}

on this test, I have tried to do it so that the user“s choice happens in 9th frame, and when he chooses to click firstroadA he goes to some of the random frames, 10, 11 or 12... so, I hope I have been clear enough; my question is in a nutshell, how do I randomize the gotoAndStop frames, and how do I add some rare frames that has lesser chance to be chosen to gotoAndStop.... thank you!

Esa T. H.
  • 123
  • 1
  • 4
  • 18

1 Answers1

0

You can as you want using weighted random numbers. Check out this code, it does as you want:

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;
}

For a deeper look into weighted random number check this SO answer: Weighted random numbers

Community
  • 1
  • 1
ezekielDFM
  • 1,947
  • 13
  • 26