HTML5 game publishing

Procedural Puzzle Levels That Are Always Solvable: Using a Solver to Build a Difficulty Curve

Generate, solve, score and select: a build-time pipeline for puzzle levels that are always solvable and get harder in a controlled way.

PlayKovo Team5 min read
Games currently available on PlayKovo. Open a title to see its current listing.

Procedural levels sound like a shortcut: write a generator once and get a thousand levels. In practice, a generator without checks produces levels that are impossible, trivial, or all the same. Players hit an unsolvable level 47, decide the game is broken, and leave. This post describes how to make generated puzzle levels that are always solvable and that get harder in a controlled way, using a solver inside your build process.

The core idea: generate, solve, keep or throw away

Instead of trusting the generator, treat it as a source of candidates:

  1. Generate a random level from a seed.
  2. Run a solver on it.
  3. If there is no solution, throw it away.
  4. If there is, measure how hard it is.
  5. Keep it only if the difficulty fits the slot you are filling.

This is cheap for most puzzle games. A breadth-first search over a small sliding puzzle or a sorting puzzle runs in milliseconds. Even if you throw away 90% of candidates, generating a hundred good levels takes seconds.

Write the solver first

The solver is just your game rules without graphics. If your game logic is already separated from rendering (and it should be), you can reuse it directly:

function solve(start, maxStates = 200000) {
  const key = s => s.serialize();
  const seen = new Set([key(start)]);
  let frontier = [{ state: start, depth: 0 }];
  while (frontier.length) {
    const next = [];
    for (const { state, depth } of frontier) {
      if (state.isWon()) return { solvable: true, moves: depth, explored: seen.size };
      for (const move of state.legalMoves()) {
        const s2 = state.apply(move);
        const k = key(s2);
        if (!seen.has(k)) {
          seen.add(k);
          if (seen.size > maxStates) return { solvable: null };
          next.push({ state: s2, depth: depth + 1 });
        }
      }
    }
    frontier = next;
  }
  return { solvable: false };
}

Breadth-first search gives you the shortest solution length, which is a useful difficulty signal. The maxStates limit stops it from running forever on huge levels. Treat "unknown" as "throw away".

The serialize function matters a lot. Two states that are the same for the player should give the same key. In a water sort puzzle, for example, the order of the tubes does not matter, so sort the tube strings before joining them. That alone can shrink the search by a large factor.

Generate backward when you can

For many puzzles, there is a smarter way to generate than pure randomness: start from a solved state and apply reverse moves. A sorting puzzle starts with every tube sorted, then you make random "un-pours". A sliding puzzle starts with the target free, then you slide blocks into the way.

Levels made this way are always solvable, so you can skip the solvability check. You still need the solver to measure difficulty, because a level made with 30 reverse moves might be solvable in 4 real moves.

One trap: reverse generation can produce states that look unnatural, or that are only reachable in ways players would never think of. Look at a sample of them before you ship.

Measuring difficulty

Solution length alone is a weak measure. A 20-move level where every move is obvious is easier than an 8-move level with one hidden trick. Combine a few signals:

  • Shortest solution length. From the BFS.
  • Branching at the start. How many legal moves exist at the first step? More options mean more to think about.
  • Dead ends. How many moves lead to states where the level can no longer be won? You can count this by running the solver from each first move. A level where most first moves lose is hard.
  • Explored states. How many states did the solver need to visit? It roughly tracks how big the problem space is.
  • Required "non-greedy" moves. Moves that make the board look worse before it gets better. Humans find these hard.

Combine these into one score with weights you tune by hand. Do not overthink the formula at first. Its job is to sort levels roughly, and you will adjust it after playtests.

Building the curve

With scored levels, you can build a difficulty curve instead of hoping for one:

  1. Decide the target score for each level number. A slowly rising line with small dips works well. After a hard level, give an easier one so the player feels progress.
  2. Generate many candidates for each band of difficulty.
  3. For each level slot, pick the candidate closest to the target.
  4. Avoid near-duplicates: compare a simple fingerprint (board size, piece counts, solution length) with the previous few levels.

Introduce mechanics at fixed points, not randomly. If level 20 is the first with locked tubes, make sure levels 20 to 23 use them in simple ways before mixing them with everything else.

Bake levels, don't generate at runtime

You can run the whole pipeline at build time and ship the result as a JSON file of seeds or level data. This has real advantages:

  • Every player sees the same level 47, so you can fix a bad one.
  • Bug reports make sense: "level 47 is impossible" means something.
  • There is no solver running on a slow phone.
  • You can review the levels before release.

Storing seeds instead of full levels keeps the file tiny, but then the generator must be deterministic. Use your own seeded random function (a small PRNG like mulberry32), never Math.random(), and never change the generator after release, or every saved level changes.

For endless modes, you can still generate at runtime. Run a light check, such as a capped solver, and fall back to a baked level if the check takes too long.

Test the generator, not just the levels

A few automated checks catch most problems:

  • Every shipped level is solvable (run the solver over the whole file in CI).
  • The difficulty score rises roughly with the level number.
  • No two consecutive levels are identical.
  • The first levels can be solved in very few moves.

Then play them. A solver can tell you a level is valid. It cannot tell you it is fun. Play the first twenty and a random sample of later ones, and remove anything that feels like busywork.

Where this does not work well

Solvers struggle with real-time games, physics and huge state spaces. For those, use a simpler check, such as a bot that plays the level with some randomness, and count how often it wins. If the bot almost never wins, the level is probably too hard for humans. If it always wins with random input, it is probably too easy.

Several PlayKovo original puzzle games were built with solver-checked levels in exactly this way. If you have built something similar and want players to see it, start with the submission rules and the other posts on the developer blog.

We use optional cookies for site analytics and site advertising. You can change your choice later. Privacy policy.