The id is the level: save files that survive a reordering

A solved level is stored under a name. If that name is a position in a list, the next batch of new levels destroys every save file. How a hash over the puzzle configuration turns it into an identity, why it rules out duplicates along the way – and how to carry old save files across, once.

A puzzle game with generated levels has a file recording what the player has achieved. It does not hold the levels themselves – those live in the level pack – only a list of names marked “solved”. The whole question of this article is: what is that name?

The most convenient answer is the position. Level 7 of difficulty 3 is called d3-0007, or more compactly still: the seventh byte of an array per difficulty is set to 1. That takes ten minutes to write, reads in one beat and works flawlessly – until the first time the list changes.

And the list does change. Forty levels get added. The generator learns a new technique and therefore rates a level differently. The sort order moves from “island count” to “solver steps”, because that maps the difficulty curve better. Every time, what sits at position seven shifts – and whoever solved thirty levels gets, with the next update, thirty check marks on puzzles they have never seen, while their actual work has vanished.

This is not a bug you fix later. By the time it surfaces, the information is already gone: the save file says d3-0007, and nobody can say any more which puzzle that used to be.

The name has to come from the level

The fix is the same as anywhere something needs a lasting name: the name must not describe where a thing sits, but what it is. So, a hash over the puzzle configuration.

I use this in three games, and it is the same pattern every time: a string is built from whatever makes up the puzzle, SHA-256 is taken of it, and the first 16 hex characters are the name.

Star Battle         SB1|5|1|01123/11223/11143/11444/14444/       → f5c99c13a3b3ccde
Sky Bridge Islands  SBI1|2|1,-2,1;-1,-1,1;0,-1,4;0,1,2           → 8032ff4f68ca116f
Shikaku             SHK1|5|5|3,0,5;1,1,5;4,2,5;2,3,3;1,4,3;4,4,4 → 61823ce5080e40e5

For Star Battle that is the edge length, the stars per zone and the division of the board into regions. For Sky Bridge Islands, a Hashiwokakero on hexagons, the radius of the board and every island with its position and number. For Shikaku the size of the grid and every number with its position.

In GDScript this is a handful of lines, because the engine already ships SHA-256:

var parts := PackedStringArray()
for index in order:
	parts.append("%d,%d,%d" % [cells[index].x, cells[index].y, values[index]])
var text := "%s|%d|%s" % [ID_FORMAT, board_radius, ";".join(parts)]
return text.sha256_text().substr(0, ID_LENGTH)

The string is human-readable, and that is deliberate: when two places disagree about an id, you print it and see at once where.

The name 8032ff4f68ca116f belongs to exactly this board, and it stays that way – no matter where in the pack the puzzle ends up in future, in what order the levels get sorted, and how many are added. A save file listing it as solved means this puzzle. Forever.

What goes in and what does not

A hash is trivial. The interesting question is what you hand it – because a hash is unforgiving: one character different in the input and it is a different puzzle. So exactly what constitutes the puzzle has to go into the string, and nothing else.

A level file usually holds considerably more per entry: the solution, the difficulty tier, the seed the puzzle grew from, which techniques the solver needed, how many steps. None of it goes into the id, for one simple reason: it is all derived. The solution follows from the board, the difficulty from the solving path, the reward from the difficulty.

If the difficulty were part of the id, then an improvement to the solver – suddenly noticing that a puzzle can be cracked more easily – would have turned a known puzzle into a stranger. Exactly the case the id exists to prevent, just through the back door. The same goes for the seed: two seeds that happen to grow the same board have produced the same puzzle, and it should carry the same name.

The underlying rule: the hash gets the task, not its assessment.

What is the same has to be named the same

The reverse case is subtler. Two entries that are the same puzzle to the player have to produce the same string – even if they look different in the file.

The simplest example is order. The islands of a Sky Bridge board sit in the file as a list, and a list has an order; the board does not. So before hashing they are sorted, by row, then by column. Shikaku does the same with its numbers. Without that step the name would depend on the order in which the generator happened to place the islands.

In Star Battle the same problem sits one level deeper. The regions of a board are numbered, and those numbers later determine the colours. But whether the region in the top left is 0 or 3 changes nothing about the puzzle. So the regions are relabelled first, in order of first appearance:

# Relabels the regions in order of first appearance (row-major), so two layouts that only
# differ in their region numbering (= colors) produce the same id
static func normalized_regions(p_regions: Array) -> Array[Array]:

The test for it is the actual content of the rule:

#[test]
fn id_ignores_region_numbering() {
    let a = vec![0, 0, 1, 1, 0, 2, 2, 1, 3, 3, 2, 1, 3, 3, 3, 1];
    let b: Vec<usize> = a.iter().map(|r| (r + 2) % 4).collect();
    assert_eq!(puzzle_id(4, 1, &a), puzzle_id(4, 1, &b));
    assert_ne!(puzzle_id(4, 1, &a), puzzle_id(4, 2, &a));
}

The same layout with shifted numbers: same id. The same layout with two stars instead of one: different id, because that is a different puzzle.

Think it through and you arrive at a question every game has to answer for itself: a board rotated by 90° is mathematically the same puzzle. Should it get the same id? That would mean forming the canonical form across all symmetries – eight for a square, twelve for a hexagon – and hashing the smallest. I do not do it, because a rotated board feels noticeably different to play and I do not experience it as a repeat. But it is a decision, not a given, and it belongs as a comment right on the function.

The prefix

Every string starts with a short tag and a number – SB1, SBI1, SHK1 – and that deserves its own paragraph, because it is the part you leave out on the first draft.

Suppose a variant arrives – rectangular boards, or islands with a new property. Then the input format changes, and without a prefix a new string could coincidentally look exactly like an old one with a different meaning. With a prefix, every format change becomes a deliberate act: you bump it to 2, and that guarantees no new name can collide with an old one.

## Bumped only when the text behind an id changes shape, so a new id can never
## collide with an old one that meant something else.
const ID_FORMAT := "SBI1"

This is the same idea as the generator version in the seed, which I wrote about in the article on levels from a seed. A version number in the hashed string costs a few characters and saves you a data migration later.

How short may it be?

SHA-256 gives 64 hex characters. As a name, 16 of them go into the file, so 64 bits, and that is not sloppiness but a calculation.

Collisions follow the birthday problem, the same arithmetic as with UUIDs in distributed systems: for n values out of b bits, the probability that two meet somewhere is roughly n² / 2^(b+1). At 64 bits and 10,000 levels that is about 1 in 370 billion. At a million levels – absurd for a puzzle game – it would still be 1 in 37 million.

What matters is why truncating is permissible here at all. This hash keeps nothing secret and protects against nobody – it only names. A collision would be an annoyance (two puzzles sharing one save entry), not a security problem, and nobody gains anything from hunting for one. That is why the probability argument suffices. For a hash signing a save file against tampering, the same truncation would be a mistake.

For the same reason the choice of algorithm hardly matters. An FNV-1a over the numbers would name things just as well. I still use SHA-256 because Godot already has it on board as sha256_text(): the game side is then one line, and there is no 64-bit arithmetic that has to overflow correctly twice, in two languages.

As a side effect: there can be no two identical levels

The benefit that pays off fastest in practice is really a by-product. If the name comes from the content, then two identical puzzles have the same name – and a duplicate is no longer a question but an entry that is already taken:

// One set across both pools: no puzzle ever shows up in both. The level id
// is a hash of the board, so "already taken" and "same puzzle" are one test.
let mut taken: HashSet<String> = HashSet::new();

The generator keeps a single set across everything it ships: the regular level list and the pool of daily puzzles. Any candidate whose id is already in it is discarded – whatever seed it grew from and whatever tier it was meant for. That rules out a daily puzzle also being level 23, or a puzzle sitting in the list twice. Not because somebody was paying attention, but because the mechanism does not allow it.

If the generator loads the already-shipped pack first and fills the set from it, the same holds across updates: whatever was out there once does not come back as a “new” level.

Without a content hash this check is unpleasant. You would have to compare boards pairwise and rebuild the normalisation from above by hand anyway; with just under 2,000 puzzles that is almost two million comparisons. With a hash it is a set lookup.

The id is not believed, it is recomputed

A detail that costs little and gives a lot: on load, the game recomputes every level’s id from its board instead of taking the one from the file.

id = compute_id(radius, island_cell, island_value)
var stored_id := str(level.get("id", ""))
if not stored_id.is_empty() and stored_id != id:
	return false

If the two disagree, the entry is broken and gets discarded rather than entering the game under a false identity. That way a wrong id cannot reach the save file at all – and this is exactly where a content hash is more than a name: it is a checksum over the entry at the same time.

The calculation exists twice, in the generator in Rust and in the game in GDScript. Two implementations of the same calculation in two languages drift apart if nobody is watching. So on both sides a test pins the same board to the same string and the same id:

#[test]
fn id_is_a_hash_of_this_exact_text() {
    let puzzle = Puzzle::new(2, vec![island(1, -2, 1), island(-1, -1, 1), island(0, -1, 4), island(0, 1, 2)]);
    assert_eq!(puzzle.id_text(), "SBI1|2|1,-2,1;-1,-1,1;0,-1,4;0,1,2");
    assert_eq!(puzzle.id(), "8032ff4f68ca116f");
}
check(PuzzleState.compute_id(2, cells, values) == "8032ff4f68ca116f",
	"and it is the one the generator writes")

Change one side and the other side’s test breaks. That is the real contract between generator and game – not the file format, but this one string.

Order becomes presentation

Once the name is separated from the slot, what the order in the game means changes: nothing any more beyond presentation. The list may be resorted, extended and regenerated from scratch; the save file never asks “is slot 7 solved?”, but “is this board solved?”.

The position does not disappear. The screen still says “Puzzle 7 of 110”, because people think in numbers. But the number is translated into an id at the moment the question is asked:

## Positions are what the screen shows ("Puzzle 7 of 110"); whether one is solved is asked of its
## id, so the answer follows the puzzle and not the slot it happens to sit in.
func is_level_done(difficulty_id: int, index: int) -> bool:
	var ids := _ids(difficulty_id)
	return index >= 0 and index < ids.size() and solved_ids.has(ids[index])

Progress is therefore a set of ids. If a solved puzzle slides from slot 39 to slot 42, the check mark simply sits at slot 42. A test that just reverses the list checks exactly that.

There is only one way left to lose progress: a level is taken out of the list. Then its entry in the save file is a name with no puzzle behind it – and that is honest, because there is nothing left that could be solved.

The switch: translating old save files once

It gets interesting when a game is already out and save files with positional names exist. They have to be translated into ids once, at the update, and there is a catch: a position only tells the truth as long as the list it was written against is unchanged.

A translation table next to the levels, not inside them

The obvious idea is to give every level its old name as an extra field. That works exactly until the next generator run – which hands out fresh positions, and the field is no longer right.

More robust is a file of its own, built once from the old pack and never generated again:

{"regular": {"d1-0003": "8032ff4f68ca116f", "d1-0005": "d03e309f656be926", ...},
 "daily":   {"day-0000": "...", ...}}

It does not describe today’s list but the old one, and that is exactly why it sits alongside: the levels may be resorted and regenerated afterwards, and the table stays right. That the old names in it really are the shipped ones is ensured by building it from the shipped file – not from a new run that ought to come out “the same”.

Once, on load, with a version number

The save file gets a new version. When the game reads an old one, the translation runs exactly once:

for key: String in solved.keys():
	var id := table.resolve_id(key, "regular")
	if id.is_empty():
		id = table.resolve_id(key, "daily")
	if id.is_empty():
		lost += 1
		continue
	lifted[id] = solved[key]
solved = lifted

A name the table does not know, or whose level is no longer shipped, is dropped. Guessing would be worse than forgetting.

resolve_id() is built so that an id resolves to itself. That makes the translation idempotent: run it twice and the second pass changes nothing. It also allows the same function to be used in the places that have no version number of their own – the last level played in the settings, the half-solved puzzle in the resume file. Those are simply resolved on every read: old names become ids, ids stay ids.

When the translation has to wait

The nastiest case is the one you think of last: the game loads an old save file, but the table is not available just then. Keep the old names and write the save back under the new version, and you have frozen them – on the next start it looks like a new one, and nobody translates any more.

So a save whose translation had to wait stays old:

"version": 2 if _migration_pending else VERSION,

It is written with the old names and the old version number, and the next start tries again. Until then nothing is lost.

And then gone again

The table is scaffolding, not foundation. Once no save file older than the switch can still be in circulation, the table, the translation and the minimum version go out together. So that nobody forgets, it is written in the file itself – in an about field that says what it is and when it may go.

A number is a recipe, not a name

That leaves the obvious objection: if every level grows from a seed anyway – why not just use the seed as the name? It is short, unique and already in the file.

Because a seed does not describe what a level is, but how to make it. Seed 7381920183 produces this board only together with exactly this random number generator and exactly this generator code. Change anything about them – a better algorithm, one more number drawn from the generator – and the same seed produces a different board, and every save file listing it as solved points at a puzzle nobody solved.

Whoever makes the seed the name therefore has to freeze the algorithm – typically with a file of pinned results that every build has to reproduce and that must never be changed. That holds, but it is the exact opposite of what you want from generated levels: you want to keep working on the generator.

The content hash turns this around. The seed only determines where the generator looked, not what it found. What gets shipped is what was found, named after itself. After that you may touch everything: the random number generator, the rating, the sort order, the size of the pools. Whatever levels remain keep their name and their progress. The one thing the mechanism cannot prevent is a level dropping out – and then that is a deliberate decision, not an accident.

In short

  • A save file stores names. If the name is a position, it does not survive the first reordering.
  • The name has to come from the content: a hash over the puzzle configuration, here SHA-256 truncated to 64 bits.
  • The hash gets the task, not its assessment. Solution, difficulty, seed and reward are derived and stay out.
  • Normalise first: whatever is not a property of the task – storage order, region numbers – gets computed away. Whether rotations are the same puzzle is a decision you write down.
  • Put a format version in the hashed string, so a format change never hits old names.
  • 64 bits are enough because this hash names rather than protects.
  • Duplicates solve themselves: same content, same name, one set across all pools.
  • Recompute the id on load and discard on mismatch – then the name is a checksum as well. If the calculation exists twice, a test on each side pins the same string.
  • Positions stay for display; the question is always asked of the id.
  • Translate old save files once: through a separate, frozen table next to the levels, idempotently, with a version number – and if the table is missing, wait rather than freeze.
  • A seed is a recipe, not a name. Make it the name and you have to freeze the algorithm; name by content and you may touch everything.

What comes out of it is a sentence suspiciously similar to the one from the seed article, and yet pointing the other way: a level does not live at its place in the list – it carries its name with it.