Craig Fisk .co .uk

Pseudo Random Number Generation for Games using Typescript

During the development of my game 2048 Today I came across a problem that many games have to solve, but I as a developer had not come across before; how do I generate a seemingly random level using a seed (an arbitrary number of arbitrary length) but have that same level be generated every time that same seed is provided.

Typically in single player experiences where the generation of levels doesn't have to be shared between players most developers, myself included would reach for good old Math.random() and use the result of that random number to generate some aspect of the level, e.g. how many of a certain type of enemy should be spawned or which direction should the next room in the level be created?

Unfortunately the results generated by Math.random() are not repeatable and in my solution I did not want to have to involve server side data storage to serve up pre-generated levels to every player that would need to be continually updated. The ideal solution would be to have a serverless function that given a particular seed would generate a configuration for a level that looks seemingly random.

To achieve this I need to leverage the concept of Pseudo Random Number Generators (PRNG). What a PRNG does is it takes a seed value and then using a series of multiplications and divisions using prime numbers (due to their own mathematical randomness) we can generate a consistent pseudo random series of numbers that can be used as values to power our random configuration.

See the Pen Pseudo Random Number Generator by Craig Fisk (@the_fisk) on CodePen.

Above shows an implementation of a simple PRNG written in Typescript

The way the algorithm for 2048 Today uses this style of PRNG is by then splitting the decimal number into an array of numbers using:

Array.from(
 PRN.toString()
 .substring(2))
 .map(numstr => Number(numstr));

To generate an array of all the numbers (number[]) in the decimal that was generated. The algorithm for 2048 Today's level generator then uses this string of numbers in two ways, one to generate a series of tiles using some arbitrary rules, and then again to shuffle the positions of the tiles on the board. This functionality is then all wrapped up into a serverless function that the website can call on game start up to get the days board configuration, all without needing to store any data.

-