Google will tell you several methods, but I tested them and they may have different flaws, such as:
- You can't get two random numbers without waiting one second for the os.time() refreshes. This is a big flaw when you need many random nums in little time.
- The first random number in every sequence is always the same.
So I managed to get a simple yet powerful method to get true random numbers without the need to wait 1 second, and all of them different, even the first in every sequence.
The method uses Löve API and will not work without it.
It's composed by two methods. The first one is a milliseconds chronometer, the second one returns a random number between A and B, which are passed as parameters.
Code: Select all
-- set this variable as global visivility
miliseconds = nil
function chronometer()
-- count miliseconds based on game time, usually a bit milliseconds per frame
miliseconds = miliseconds + love.timer.getDelta()
-- we don't know how much the game will last, so we better restart the counter to zero
-- to avoid possible overflows
if millisecond * 1000 >= 1 then milliseconds = 0 end
end
function randomNumber(A, B)
-- generate a new random seed using our milliseconds chronometer
-- you can omit os.time() here next. It's just to illustrate that you can use whatever method you want plus the milliseconds
math.randomseed(os.time() + milliseconds)
return math.random(A, B)
end
Next, include everything in your code, and call it like this: "print ( randomNumber(min, max) )"
The only drawback is if the game generates numbers faster than millisecond speeds, which I think could be easily avoided by generating numbers only once per frame.