Reputation: 5477
How can I generate a random number in Flash CS5 using AS3, I'd prefer it as simple as possible.
My attempt gives me an error:
day_gross.addEventListener(MouseEvent.CLICK, randomNumber);
function randomNumber(event:MouseEvent):void{
var randint:Number = Math.random();
trace(randint);
}
Upvotes: 0
Views: 28165
Reputation: 10163
Math.random()
returns a random number between 0-1.
The following code create and traces a round number between 0 and the maximum value of uint:
var randomUint:uint = uint(Math.random() * uint.MAX_VALUE);
trace(randomUint);
This next code example defines and logs a rounded number between the minimum and the maximum value of int (with negative numbers too):
var randomInt:int = int.MIN_VALUE + int(Math.random() * Number(int.MAX_VALUE + int.MIN_VALUE));
trace(randomInt);
Upvotes: 9
Reputation: 1
The simplest way to get it to work is this. when you click on a button it generates a random number. it is self explainatery
protected function button1_clickHandler(event:MouseEvent):void
{
var numbers:Array = new Array(49);
for (var i:int = 0; i < numbers.length; i++)
{
numbers[i]=i;
numbers[i] =[Math.round( Math.random()*i)];
resulttxt.text = numbers[i];
}
}
<s:Button top="342" label="Generate" click="button1_clickHandler(event)" horizontalCenter="0"/>
<s:TextInput id="resulttxt" left="10" top="65" width="250"/>
This work for me. try it out
Upvotes: 0
Reputation: 84734
You can use Math.random()
to generate a pseudo-random number.
If you are generating numbers for the purposes of cryptography, however, you should use flash.crypto.generateRandomBytes()
(requires FP11)
Upvotes: 5
Reputation: 8321
private function randomIntBetween(min:int, max:int):int {
return Math.round(Math.random() * (max - min) + min);
}
Upvotes: 2