Search code examples
javascriptactionscript-3flashrandomflashdevelop

How to make a True Random with equal chance in AS3?


I'm developing a rock-paper-scissor game player vs computer. There's nothing special except player playing 3 rounds per game.

I'm using this code to generate random number from 1 to 3

Math.floor(Math.random()*(1+3-1))+1

1 = Scissor, 2 = Paper, 3 = Rock

I'm not sure but this code favor on Number 2.

Meaning the computer generate Paper-Paper-Paper so the player notice it and taking the advantage and select scissor-scissor-scissor. I bet you will do it also.

How can I generate real randomness in AS3?


Solution

  • Your code is correct, although it could be simplified to just Math.floor(Math.random()*3) + 1. That will return numbers between 1 and 3 and the distribution should be uniform (unless there's a big bug in the Flash player).

    You can verify this by looping on the number and counting the occurrence of each number. For example:

    var count = [0,0,0];
    for (var i = 0; i < 10000; i++) {
        var n = Math.floor(Math.random()*3) + 1;
        count[n-1]++;
    }
    
    trace(count);