Random # Generator AS3
I recently created a game that needed a random number generator. Searching the internet, I found many ways to create one. Some seemed overly complicated, but I came across this and it seems to work perfectly, at least for the application I used it in. What I was trying to do was create random behavior for the computer AI when fighting the human player. The way this works is I created a movie clip with all the monster’s animations for his different behaviors. so from from frame 2-20 is his standing still behavior, 21-40 is his attack behavior, 41-60 is dodging behavior, and so on.
I then labeled keyframes with still, attack, dodge, etc. As for the action script, on frame one I put this bit of code
var randNum:Number=Math.floor(Math.random()*4)+1;
What this does is create a random number, 1-4. First it creates a variable “randNumber” which then must be defined as a number , that is a whole number “floor” , that is randomly 0-3. We have to remember computers always start with 0 not 1, so that’s why there’s that +1 at the end otherwise we’d have numbers 0-3 as our output even though we put 4 as the highest place. With the +1 it adds 1 to the output number making them go from 1-4.
From here we need tell the computer what to do with these random numbers. So we add this bit of code after it.
if(randNum==1){gotoAndPlay("still")};
if(randNum==2){gotoAndPlay("attack")};
if(randNum==3){gotoAndPlay("dodge")};
if(randNum==4){gotoAndPlay("still")};
Whats going on here is a simple set of if statements. if the variable we created earlier is 1 then our movie clip jumps to the frame labeled “still”, if it’s 2 it jumps to “attack”, and so on. I realized to make the game a little easier, I should have the monster stand still more often so the player can attack that’s why “still” is called twice. He’s more likely to stand still than do anything else.
So basically, a random number is generated in frame 1 that tells the movieclip where to jump to, it plays those set of frames, then at the end of those set of frames I send the play head back to frame one with
gotoAndStop(1);
to go and do it all over again. There’s more code to go along with this, like testing to see if the monster hit’s the player when he’s attacking, figuring out how much life is lost when hit, and other things I’ll save for another day. I’m not saying this is a great way to do things, but it worked for me.
