Page 1 of 1

Math.randomseed lua problem.

Posted: Sun Mar 25, 2012 5:11 am
by Chartre
Hello, this is my first thread here. I have a problem with math.randomseed.

The problem is: math.random DOESN'T DO ANYTHING!
Well, to elaborate, I have a random seed for the x, y, and size of stars in a starfield. But when I try to generate the starfield, a small cluster of stars appear right in the corner of the screen, compared to the seemingly totally random array of stars generated when there is no seed. It doesn't seem to matter how ridiculous the seed is, it will always generate some sort of cluster of stars in the corner. I have tried to even generate the XYS locations for each star every time 10% of a loading sequence has finished, but to no avail.

Please help! If you find the ship controls Shonky Wonky Donkey, it's because I optimised the game for gamepad and don't really care about the keyboard controls. To generate 'new' stars, press F1. If you want to change the sort of control, press F2. Thanks!

Re: Math.randomseed lua problem.

Posted: Sun Mar 25, 2012 8:37 am
by Robin
The thing about a seed is, you need to do it once. Then each call to math.random() will change the internal state of the random number generator.

So, you only need to call math.randomseed() once.

Re: Math.randomseed lua problem.

Posted: Sun Mar 25, 2012 8:45 am
by Boolsheet
It looks like your understanding of the random functions is incomplete.

math.random returns a sequence of seemingly random numbers. math.randomseed sets the position where it will start in the sequence. Equal seeds will return the same random number sequence.
math.randomseed takes an integer from -2147483648 to 2147483647 (smaller and larger values work, but the number gets wrapped to this range anyway). The fraction gets rounded off.

Here's a simplified example how this could work in Lua:

Code: Select all

random_number = 1

function math.randomseed(seed)
	random_number = math.floor(seed)
end

function math.random()
	random_number = (1664525 * random_number + 1013904223) % 2147483648
	return random_number / 2147483648
end
This varies on different platforms, they are free to implement this how they want. Windows' crappy PRNG wraps with 32768 instead of 2147483648.

You either have to set the seed only once like Robin said, or create your own noise function.

Re: Math.randomseed lua problem.

Posted: Mon Mar 26, 2012 2:52 am
by Chartre
Thanks! I suppose the seed was being called all the time, meaning the same number was being generated. It's now quite a pretty star-system generator.

Re: Math.randomseed lua problem.

Posted: Tue Mar 27, 2012 10:14 am
by Lafolie
Nice Aphex reference.

Could post an updated .love file? I can't seem to get this one to do anything other than crash when I press return.