Levels from a seed: randomly generated and still the same for everyone
Nobody wants to build a hundred levels by hand, and purely random levels are worthless to everyone involved. How a seed turns a random generator into a fixed catalogue – and where determinism breaks down in practice.
At some point while working on DataBurst the question came up of how the levels should actually come into being. A bubble shooter lives off having a lot of them – a hundred is not an unusual number, and built by hand that is a week of work in which you start repeating yourself somewhere around level 30.
The obvious way out is to have the levels generated. Except that, in its simplest form, this creates a problem bigger than the one it solves: if level 23 looks different on every start, then “level 23” is no longer a name, just a number.
- Two players cannot compare their results.
- A highscore list per level stops making sense.
- A bug report saying “a node is stuck in the wall on level 73” cannot be reproduced.
- And the difficulty curve, which is the real craftsmanship in a game like this, cannot be shaped if you do not know what you are distributing.
The solution is an old one and consists of a single value: the seed.
Randomness in a computer is not random
What a program hands you as a random number is, as a rule, nothing of the sort. A pseudo-random number generator – PRNG – keeps an internal state and uses a fixed formula to compute the next number from it, which then becomes the new state. The result looks random, passes statistical tests and is nevertheless entirely predetermined. There is no unknown in the calculation.
The only unknown is the initial state. And that is exactly what the seed is.
Everything else follows from this: same seed, same sequence of numbers. Every time, on every device, in every session. A generator is therefore not either random or deterministic – it is always deterministic, and the only question is whether you keep hold of the seed or take it from the clock and throw it away.
In Godot you can see that difference in two lines. The global functions randi() and randf() work on a shared generator that the project seeds once at startup from an unpredictable source. That one is exactly right for particles, variance in sound effects and flicker – and completely unusable for levels, because every other place in the project uses it too.
For anything that is meant to be reproducible, you take your own:
var rng := RandomNumberGenerator.new()
rng.seed = 12345
print(rng.randi_range(1, 100)) # always the same number
That is the whole mechanism. The rest of this article is about what you do with it, and how easily you break it again.
The level number is the seed
The step from a single seed to a catalogue of levels is shorter than you might think: you need a function that turns the level number into a seed.
The obvious choice would be rng.seed = level. That works, but it is a bad idea for two reasons. First, the seeds of neighbouring levels then sit right next to each other, and some generators take a while to mix that out of the first few numbers – levels 1, 2 and 3 end up visibly similar. Second, it leaves you no way of ever changing the generator without every existing level changing along with it.
One line solves both:
const GENERATOR_VERSION := 1
func level_seed(level: int) -> int:
return hash("databurst-v%d-level-%d" % [GENERATOR_VERSION, level])
The hash spreads neighbouring level numbers apart. And the version in the string turns a change to the generator into a deliberate act: as long as GENERATOR_VERSION is 1, every level stays as it is. Anyone who rebuilds the generator and bumps the version throws away the entire catalogue – that should hurt, and above all it should not happen by accident.
With that, level 23 is no longer a number but a promise: the same arrangement, on every device, in every installation, five years from now too.
What should be deterministic – and what should not
Before writing the generator, there is a question worth asking that is easily skipped: what exactly is supposed to be the same?
For DataBurst the answer is not “everything”. The board – which node sits where, in which colour, which special nodes are in play – has to be the same for everyone, otherwise the highscore list is worthless. The order of the nodes pushing in, on the other hand, does not: if that were fixed too, every level would have exactly one optimal sequence, which you memorise once and then play back. That is not a puzzle any more, it is a memory exercise.
The consequence is a rule that runs through the whole topic: one generator per concern. Not one for everything.
var layout_rng := RandomNumberGenerator.new() # tied to the level
var queue_rng := RandomNumberGenerator.new() # free per round
func start_level(level: int) -> void:
layout_rng.seed = level_seed(level)
queue_rng.randomize()
build_board(layout_rng)
That is not only a decision about the game, it is a technical safeguard – which brings us to the most important point.
Why determinism breaks
That the same seed yields the same numbers is always true. That the same seed yields the same level is only true as long as the generator asks the same questions in the same order every time. And that is considerably more fragile than it sounds.
The order of the calls
A PRNG is a tape you unroll numbers from. Draw one extra number somewhere in the middle and everything after it shifts. A line like
if debug_mode:
rng.randi() # "just" a test draw
changes every level from that point on. The same thing happens when a new function starts using the shared generator, when a condition is reordered, or when someone optimises a check and thereby sometimes skips it.
Hence the separate generator per concern: if the incoming nodes come from queue_rng, their logic can be tinkered with at will without the board changing. Two generators are not a luxury, they are the firewall.
Collections without a fixed order
The second classic is less conspicuous. Iterating over a Dictionary, over the result of a search, or over get_children() of a node that was filled at runtime gives you an order that is not guaranteed. If the seed is the same but the order is not, the result differs anyway.
The rule against it is boring and effective: sort everything the generator iterates over.
var colors := available_colors.keys()
colors.sort() # without this the level depends on insertion order
var pick: String = colors[rng.randi() % colors.size()]
Floating point across platforms
The third point only concerns you if you compute positions instead of counting cells. Floating-point operations can differ in the last bit between platforms, compilers and optimisation levels – and one last bit is enough if something is rounded or compared afterwards.
For the structure of a level you therefore use integers wherever possible: not “at which position in pixels” but “in which cell”. Whatever coordinates come out of that may well be floating point – they are only drawn, not used for anything further.
The generator itself
And finally: a seed is only unambiguous together with its algorithm. If the engine swaps out its PRNG in a new major version, the same seed yields different numbers. Godot’s RandomNumberGenerator is stable in this respect, but it is not something to rely on blindly – anyone with a catalogue that is meant to stay the same for years either writes the generator themselves (a PCG or xorshift is a handful of lines) or checks once on every version bump. A test that expects known numbers for three fixed seeds is enough for that.
Not every seed is a good level
A reproducible level is not yet a playable one. A generator reliably produces arrangements that are over in two moves, that cannot be solved at all, or that put every special node in one corner.
The usual way to deal with this is generate-and-reject: you build the level, check it against a few conditions and start over if it does not please – with a seed derived from the first one.
func generate(level: int) -> Board:
var base := level_seed(level)
for attempt in 64:
var rng := RandomNumberGenerator.new()
rng.seed = base + attempt
var board := build_board(rng)
if is_acceptable(board, level):
return board
# If this happens, the conditions are wrong – do not carry on silently.
push_error("No usable level %d after 64 attempts" % level)
return build_board(_fallback_rng(base))
The point is that this procedure stays deterministic. Which attempt gets accepted depends only on the seed and on is_acceptable() – both of which are the same on every device. Rejecting costs computing time, but it is paid once at load time, and a few dozen rounds are done in milliseconds.
is_acceptable() is then where the actual work sits, and it is also where the difficulty curve belongs: a level with a low number may have fewer colours and more room, a late one more of both. The generator rolls the dice, the conditions do the shaping.
The real gain: it is testable
The reason this effort pays off shows up not in the game but beside it.
A bug report no longer reads “sometimes a level does not work” but “level 73” – and level 73 is the same level on the development machine. What can be reproduced can be fixed.
And because generation is a pure function from a level number to a board, the whole catalogue can be computed through in a single test:
func test_all_levels() -> void:
for level in range(1, 201):
var board := generate(level)
assert(board.is_solvable())
assert(board.color_count() <= max_colors_for(level))
assert(board.node_count() >= 12)
Two hundred levels, checked in a few seconds, on every build. Hand-built levels cannot be covered like that – there the only option is to play them yourself.
And the free seed?
Once the catalogue stands, one extra costs almost nothing: you show the seed and let people type one in. The same mechanism turns into a shared puzzle – “try 8F3C21, it’s nasty” – and a daily challenge is then just a seed derived from the date:
func daily_seed() -> int:
var today := Time.get_date_dict_from_system(true) # UTC, not local
return hash("daily-%04d-%02d-%02d" % [today.year, today.month, today.day])
That true is not incidental: with local time every time zone gets a different challenge, and a shared highscore list for the day collapses.
In short
- A PRNG is always deterministic. The only question is whether you keep the seed.
- Put the level number through a hash into the seed, with a generator version in the hash string.
- One generator per concern – that is the firewall against shifted number sequences.
- The order of the calls and the order of collections are the two usual breaking points. Sorting helps.
- Not every seed is a good level: generate, check, reject with
base + attempt. - The payoff is not the effort saved but that a hundred levels can be checked automatically.
In the end it comes down to one sentence that carries the whole thing: the level is not in a file, it is in its number.