RANDOM CODE GENERATION                                                as2


    This tutorial shows how to create simple random code generator including numbers, upper and lower case characters, but you can add any other symbols you like. This generator also include function which let you choose the length of the generated code from 1 up to 100 (also changeable) characters. The result should look like this:


    Open new actionscript 2.0 document. Insert dynamic textfield and call it (instance name) TFIELD. Now create button and name it generate_btn. This button will execute the code generation. Last we need NumericStepper component from flash component library. Set its instance name to stepper, select it and press shift+F7 (opens component inspector). Set first three values like this ,maximum to 100, minimum to 1 and stepSize to 1, ofcourse you can change it as you like.



Now open actions window and insert the following actionscript code.


function generateRandomString(newLength:Number):String{
  var a:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  var alphabet:Array = a.split("");
  var randomLetter:String = "";
  for (var i:Number = 0; i < newLength; i++){
    randomLetter += alphabet[Math.floor(Math.random() * alphabet.length)];
  }
  return randomLetter;
}
generate_btn.onRelease = function(){
	n=stepper.value;
	TFIELD.text = generateRandomString(n);
}


    First line is definition of function which will generate the code. Line 2 is string with all the used characters for code generations. You can remove or add symbols as you like. Only characters contained in this string will be used for code generation. Line 3 cuts the string above to single character array pieces. The for loop randomly picks positions from array and adds them to randomLetter variable. Number of characters added to this variable is based on number sent by numeric stepper component. Lines 10-13 assignes the main function to the button, so each time the button is clicked, the new code is generated.



DOWNLOAD SOURCE FILE