Seeding in GDevelop

Hello! Here I am with a random JS snippet again! This snippet will let you seed the Randomness. For those unfamiliar with Randomness, let me explain. In computers, true randomness do not exist. Everytime a program wants to randomize something, it uses a pseudorandom generator. To work, it will generate a seed, Wich will depend on the most random things of the device (Date, Mac address, 1.st letter of the name of the last programm to have been opened or things like that) and then use an algorithm that will return a number between 0 and 1 with many decimals depending on that seed. Then the seed is changed by an algorithm in a way that it is extremely unlikely to get the same seed ever again.
But if we control the seed, we can predict what will be generated by the pseudorandom number generator. This is not really useful, but imagine you are working on a procedurally generated world, then you will use randomness to decide the whole process of building the world. Now imagine having the possibility to choose the seed, then with each seed comes a complete world that will be the same on it’s generation.
Anyways, here is the snippet!

Math.setSeed = function(str) { for(var i = 0, h = 1779033703 ^ str.length; i < str.length; i++) h = Math.imul(h ^ str.charCodeAt(i), 3432918353), h = h << 13 | h >>> 19; Math.seed = function() { h = Math.imul(h ^ h >>> 16, 2246822507); h = Math.imul(h ^ h >>> 13, 3266489909); return (h ^= h >>> 16) >>> 0; } };
let variable = runtimeScene.getGame().getVariables().get("RandomSeed");
let val = null;
if (variable.isNumber()){ val = String(variable.getAsNumber());} else {val = variable.getAsString();};
if (val === "" || val === 0 || val === "0") {val = Math.random();};
Math.setSeed(val);
function getRand(a, b, c, d) { return function() { var t = b << 9, r = a * 5; r = (r << 7 | r >>> 25) * 9; c ^= a; d ^= b; b ^= c; a ^= d; c ^= t; d = d << 11 | d >>> 21; return (r >>> 0) / 4294967296; } }
Math.random = getRand(Math.seed(), Math.seed(), Math.seed(), Math.seed())

To use it it’s simple: let the user choose the seed and store it in a global variable named “RandomSeed”. Then just use this snippet Inna Js event as sub event of an event containing conditions so that it executes only once.

I hope this will be useful to you and have a good day!

4 Likes

Hey thanks for making this!
How do I use the created number?

Hey! This is an old snippet. I made this in the meantime: Seeded RNG Extension. It’s an extension for creating Seeded RNGs. It uses basically that snippet but is easier to use and cleaner.

1 Like