Spielerando

First Game With Procedural Generation? Beneath Apple Manor, 1978

The earliest game we can document that builds a new dungeon every time you play is Beneath Apple Manor, written by Don Worth for the Apple II and published in 1978, two years before Rogue. Guinness World Records instead names Elite from 1984 as the first use of procedural generation in a video game, so the answer depends on what you count.

Who claims what?

Source Claim
Wikipedia, Beneath Apple Manor Calls it "one of the first video games to use procedural generation", citing two 2016 academic texts. The article is marked as needing more citations
Summerville and Mateas (2016) Give the earliest known generation of video game levels as Beneath Apple Manor in 1978, without a source for it
The CRPG Addict (2012) Calls it the first "roguelike" game, although it predates Rogue by two years
Guinness World Records First use of procedural generation in a videogame: Elite, 1984
David Braben, co-author of Elite (2016) Asked whether they came up with it, says "I think so. It didn't exist back then"

The Guinness record and Braben's memory do not fit the earlier games on this page, which made dungeons in 1978 and a river in 1982 from random numbers. Elite's claim is stronger for a narrower thing: a whole universe that is never stored, only worked out from numbers.

What came before 1978?

Random contents in a fixed dungeon. The PLATO game pedit5, from late 1975, has a dungeon with a fixed layout, but the monster encounters and treasure are randomly generated. Wikipedia's article on roguelikes says the same: random encounters, one fixed level.

A random maze. The CRPG Addict writes that Worth was inspired by Dragon Maze, a simple maze game that came with the Apple II and seems to have had random mazes too. Wikipedia's roguelike article says Beneath Apple Manor's generation was a modification of Dragon Maze's random maze generator, citing David Craddock's book Dungeon Hacks. We found no date for Dragon Maze.

Did Beneath Apple Manor and Rogue know each other?

Wikipedia says Worth claims that neither he nor the makers of Rogue knew the other game, citing a comment of his on a blog we could not open. The CRPG Addict puts it more carefully: "Don charitably opines that they probably came up with it independently. I'm not so sure." He also notes that Glenn Wichman's account of making Rogue names other games but not this one.

Why did the early makers generate their worlds?

The people who made these games give two different reasons.

  • Surprise and replay. Wichman wrote in 1997 that most adventure games of the time were "canned", exactly the same every time, and that Rogue's program should build the dungeon so that even its creators could be surprised. Michael Toy, his co-author, said it "was never going to be fun playing a game where you knew everything", and that he sees generation and stopping players from reloading a save as inseparable.
  • Memory. Carol Shaw, who made River Raid, said the game had only 4 kilobytes of ROM, with no space to store a lot of graphics, and she used a pseudorandom number generator to decide the width of the river. Braben said of Elite's worlds: "We don't need to store this. We can just generate it."

Wikipedia's roguelike article puts the roguelikes' generation down to limited memory. Rogue's own authors, in the sources above, give surprise and replay instead.

How did procedural generation change over the years?

When Game What changed Source
Late 1975 pedit5 Random monsters and treasure in a fixed dungeon. A precursor: the map itself is not generated Wikipedia
1978 Beneath Apple Manor The player sets how many rooms a level has, and the game builds a new dungeon full of monsters and treasure The CRPG Addict, Wikipedia
1980 Akalabeth The player types a "lucky number" that seeds the random numbers, so the same number gives the same game, down to the starting character The Digital Antiquarian
1980 Rogue Craddock writes that some early algorithms put the stairs down in rooms the player could not reach. In the game Wichman describes, every level is nine rooms in a three-by-three grid Dungeon Hacks, The CRPG Addict for the year
December 1982 River Raid A fixed seed, so every game shows the same river. Shaw says such generators had been used to place objects, not to make the landscape Interview with Carol Shaw, Wikipedia
1984 Elite Galaxies from numbers instead of a stored list. Braben says the design allowed 2 to the power of 48 galaxies, cut to eight "because that was a bit more plausible" GamesBeat
21 Dec 2008 Spelunky Hand-made pieces put together by a generator: each level is a 4 × 4 grid of rooms whose layouts come from templates. Derek Yu says his generator was based on one of his roguelike prototypes Procedural Content Generation in Games, Game Developer, Wikipedia
August 2014 No Man's Sky, before release Sean Murray says every planet is defined by a single 64-bit seed, giving 18,446,744,073,709,551,616 possible planets PlayStation Blog

What counts as procedural generation?

  • Random contents in a hand-made map. pedit5, 1975, fits.
  • A random maze each game. Dragon Maze fits, but we found no date for it.
  • A new dungeon with rooms, monsters and treasure each game. Beneath Apple Manor, 1978, is the earliest in the sources we read.
  • A world kept as a seed, so it can be played again. Akalabeth's lucky number and River Raid's fixed seed fit, before Elite.
  • A universe generated instead of stored. Elite, 1984, which is what the Guinness record names.

What can we say with confidence?

Beneath Apple Manor, 1978, is the earliest game we can document with a source naming it for a dungeon generated each game, and its generator grew out of a random maze program. Guinness gives Elite, 1984, the record for procedural generation in general, which the 1978 to 1982 examples above contradict unless the record means a generated universe. Whether Worth and the makers of Rogue knew each other's games is not settled by any source we could open.

Build it today

Our procedural dungeons blueprint builds a dungeon from a seed, as Akalabeth's lucky number did, so the same seed always gives the same dungeon and a player can share a run or you can replay a bug. It answers the problem Craddock describes for early Rogue without forcing a fixed grid: rooms are placed without touching, joined left to right so all of them can be reached, and the result is checked for reachability, enough rooms and an exit far enough from the start. A dungeon that fails is made again from the same random sequence, and after a set number of failures a plain, safe dungeon is used, so the job always ends. Hand-made room templates, Spelunky's way, are not in it and would be a change on top.

Add "Procedural Dungeons" to my game.

What it should do: A new dungeon every run keeps a game fresh without a level designer for every floor. A seed makes it repeatable, so a player can share a run and you can replay a bug, and a check makes sure no dungeon is ever impossible to finish.

Build it exactly as this state machine. First check that it fits my game, then build it like this:

```mermaid
stateDiagram-v2
  [*] --> placing
  placing: Placing rooms
  linking: Joining rooms
  checking: Checking
  ready: Ready
  placing --> linking: enough rooms
  linking --> checking: all joined
  checking --> placing: failed, try again
  checking --> ready: good dungeon
  ready --> [*]
```

Use these starting values:
- width: 40 cells
- height: 24 cells
- roomCount: 8 rooms
- maxRoomSize: 8 cells
- minExitDistance: 25 cells
- maxAttempts: 20 tries

Watch out for these common mistakes:
- Using the clock for randomness: Tell your AI: keep the random sequence inside the dungeon's own state and start it from the seed, never from the clock.
- Starting again with the same seed: Tell your AI: when a try fails, carry on with the next numbers of the same sequence, not the seed again.
- A dungeon that cannot be finished: Tell your AI: join the rooms in a line first, then check that every floor cell can be reached and that the exit is far enough.
- A job that never ends: Tell your AI: count the tries, and after the last one use a plain dungeon that always works.
- Rooms too big for the map: Tell your AI: cut the biggest room size down to what fits inside the walls before picking.
- Too many rooms wished for: Tell your AI: stop placing after a fixed number of tries per room, and count a dungeon as too small below about three fifths of the wish.
- Odd seeds: Tell your AI: turn the seed into a whole number first, and use zero for anything that is not a number.

Do not change anything else in the game. Do not claim anything without proof: model what it takes, and show me what your solution rests on and how I can see that it works. If you cannot show something, say you do not know. When you are done, tell me in plain words how to try it.

The button copies this text together with the tested code below, so your AI has everything.

The tested code (TypeScript)
/* Procedural dungeons: a dungeon made from a seed number. The same seed and the same settings always
   give the same dungeon. Making one is a short job in four parts, and each call of `step` does one
   small piece of it, so a game can spread the work over frames and save it half-done:

     placing   rooms are dropped at random places and kept if they do not touch another room
     linking   rooms are joined left to right, so everything is connected, plus one extra loop
     checking  the dungeon is drawn and tested: all of it reachable, enough rooms, the exit far enough
     ready     done

   A dungeon that fails the check is thrown away and made again with the next numbers from the same
   random sequence, not a new seed. After `maxAttempts` failures a plain, safe dungeon is used, so the
   job always ends. Randomness is a value inside the state, never the clock or a global generator. */

export interface Params {
  /** Width of the dungeon, cells. */
  width: number;
  /** Height of the dungeon, cells. */
  height: number;
  /** How many rooms to try for. */
  roomCount: number;
  /** The biggest side of a room, cells. Rooms are at least 3 on a side. */
  maxRoomSize: number;
  /** How far, along the paths, the exit must be from the start, cells. */
  minExitDistance: number;
  /** How many dungeons to try before the plain one is used. */
  maxAttempts: number;
}

export const DEFAULT_PARAMS: Params = { width: 40, height: 24, roomCount: 8, maxRoomSize: 8, minExitDistance: 25, maxAttempts: 20 };

const MIN_ROOM = 3;
/** Placing tries per wanted room before the placing is over. */
const TRIES_PER_ROOM = 30;

export interface Room {
  x: number;
  y: number;
  w: number;
  h: number;
}

export type PhaseId = "placing" | "linking" | "checking" | "ready";

export interface State {
  phase: PhaseId;
  seed: number;
  /** Where the random sequence is. A number, so the state can be saved and continued. */
  rng: number;
  /** Which try this is, from 1. */
  attempt: number;
  rooms: Room[];
  /** Placing tries used in this attempt. */
  tries: number;
  /** Pairs of room numbers joined by a corridor. */
  links: [number, number][];
  /** Rows of "#" (wall) and "." (floor). Empty until the dungeon is ready. */
  grid: string[];
  /** Room numbers of the start and the exit, or -1 before the dungeon is ready. */
  start: number;
  exit: number;
  /** The plain dungeon was used because every try failed. */
  fallback: boolean;
}

/** The next number from 0 up to but not including 1, and the new place in the sequence. */
function next(rng: number): [number, number] {
  const s = (rng + 0x6d2b79f5) >>> 0;
  let t = s;
  t = Math.imul(t ^ (t >>> 15), t | 1);
  t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
  return [((t ^ (t >>> 14)) >>> 0) / 4294967296, s];
}

/** A whole number from lo to hi, both included. */
function pickInt(rng: number, lo: number, hi: number): [number, number] {
  const [v, rng2] = next(rng);
  return [lo + Math.floor(v * (hi - lo + 1)), rng2];
}

/** The settings as whole numbers that fit together. */
function shape(params: Params) {
  const whole = (v: number, fallback: number) => (Number.isFinite(v) ? Math.floor(v) : fallback);
  const width = Math.max(MIN_ROOM + 2, whole(params.width, 40));
  const height = Math.max(MIN_ROOM + 2, whole(params.height, 24));
  return {
    width,
    height,
    roomCount: Math.max(2, whole(params.roomCount, 8)),
    // A room has to fit inside the walls at the edge.
    maxRoom: Math.max(MIN_ROOM, Math.min(whole(params.maxRoomSize, 8), width - 2, height - 2)),
    minExit: Math.max(0, whole(params.minExitDistance, 0)),
    attempts: Math.max(1, whole(params.maxAttempts, 1)),
  };
}

export function initialState(_params: Params = DEFAULT_PARAMS, seed = 1): State {
  const s = Number.isFinite(seed) ? Math.floor(seed) >>> 0 : 0;
  return { phase: "placing", seed: s, rng: s, attempt: 1, rooms: [], tries: 0, links: [], grid: [], start: -1, exit: -1, fallback: false };
}

/** The same phase the diagram shows. */
export const phase = (s: State): PhaseId => s.phase;

const center = (r: Room): [number, number] => [r.x + Math.floor(r.w / 2), r.y + Math.floor(r.h / 2)];

/** Whether two rooms touch or overlap, counting one cell of wall between them as too close. */
function touches(a: Room, b: Room): boolean {
  return a.x - 1 < b.x + b.w && b.x - 1 < a.x + a.w && a.y - 1 < b.y + b.h && b.y - 1 < a.y + a.h;
}

/** Draws rooms and corridors. A corridor goes sideways from one room's middle, then up or down. */
export function carve(rooms: readonly Room[], links: readonly (readonly [number, number])[], width: number, height: number): string[] {
  const cells = Array.from({ length: height }, () => Array<string>(width).fill("#"));
  for (const r of rooms) for (let y = r.y; y < r.y + r.h; y++) for (let x = r.x; x < r.x + r.w; x++) cells[y][x] = ".";
  for (const [i, j] of links) {
    const [ax, ay] = center(rooms[i]);
    const [bx, by] = center(rooms[j]);
    for (let x = Math.min(ax, bx); x <= Math.max(ax, bx); x++) cells[ay][x] = ".";
    for (let y = Math.min(ay, by); y <= Math.max(ay, by); y++) cells[y][bx] = ".";
  }
  return cells.map((row) => row.join(""));
}

/** Steps from a cell to every cell that can be reached over floor; -1 where it cannot. */
export function distances(grid: readonly string[], from: [number, number]): number[][] {
  const dist = grid.map((row) => Array<number>(row.length).fill(-1));
  if (grid[from[1]]?.[from[0]] !== ".") return dist;
  dist[from[1]][from[0]] = 0;
  const queue: [number, number][] = [from];
  for (let i = 0; i < queue.length; i++) {
    const [x, y] = queue[i];
    for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
      const nx = x + dx;
      const ny = y + dy;
      if (grid[ny]?.[nx] === "." && dist[ny][nx] === -1) {
        dist[ny][nx] = dist[y][x] + 1;
        queue.push([nx, ny]);
      }
    }
  }
  return dist;
}

/** The plain dungeon: a row of small rooms joined in a line. It needs no luck, so it always works. */
function plain(params: Params): { rooms: Room[]; links: [number, number][] } {
  const p = shape(params);
  const count = Math.max(2, Math.min(p.roomCount, Math.floor((p.width - 2) / (MIN_ROOM + 2))));
  const y = Math.max(1, Math.floor(p.height / 2) - 1);
  const rooms = Array.from({ length: count }, (_, i): Room => ({ x: 1 + i * (MIN_ROOM + 2), y, w: MIN_ROOM, h: MIN_ROOM }));
  return { rooms, links: rooms.slice(1).map((_, i): [number, number] => [i, i + 1]) };
}

function finish(s: State, rooms: Room[], links: [number, number][], params: Params, fallback: boolean): State {
  const p = shape(params);
  const grid = carve(rooms, links, p.width, p.height);
  const dist = distances(grid, center(rooms[0]));
  let exit = 0;
  rooms.forEach((r, i) => {
    const [x, y] = center(r);
    if (dist[y][x] > dist[center(rooms[exit])[1]][center(rooms[exit])[0]]) exit = i;
  });
  return { ...s, phase: "ready", rooms, links, grid, start: 0, exit, fallback };
}

/** Whether a drawn dungeon is good: every floor cell reachable, enough rooms, and the exit far enough. */
export function isGood(rooms: readonly Room[], links: readonly (readonly [number, number])[], params: Params): boolean {
  const p = shape(params);
  if (rooms.length < Math.max(2, Math.ceil(p.roomCount * 0.6))) return false;
  const grid = carve(rooms, links, p.width, p.height);
  const dist = distances(grid, center(rooms[0]));
  const unreached = grid.some((row, y) => [...row].some((c, x) => c === "." && dist[y][x] === -1));
  if (unreached) return false;
  const far = Math.max(...rooms.map((r) => dist[center(r)[1]][center(r)[0]]));
  return far >= p.minExit;
}

/** Does one small piece of the job and returns the new state. A ready dungeon stays as it is. */
export function step(s: State, params: Params): State {
  const p = shape(params);
  switch (s.phase) {
    case "ready":
      return s;
    case "placing": {
      let rng = s.rng;
      let w: number;
      let h: number;
      let x: number;
      let y: number;
      [w, rng] = pickInt(rng, MIN_ROOM, p.maxRoom);
      [h, rng] = pickInt(rng, MIN_ROOM, p.maxRoom);
      [x, rng] = pickInt(rng, 1, p.width - w - 1);
      [y, rng] = pickInt(rng, 1, p.height - h - 1);
      const room: Room = { x, y, w, h };
      const rooms = s.rooms.some((r) => touches(r, room)) ? s.rooms : [...s.rooms, room];
      const tries = s.tries + 1;
      const done = rooms.length >= p.roomCount || tries >= p.roomCount * TRIES_PER_ROOM;
      // Numbering the rooms from left to right makes joining them in a line cheap and tidy.
      return { ...s, rng, rooms: done ? [...rooms].sort((a, b) => a.x - b.x || a.y - b.y) : rooms, tries, phase: done ? "linking" : "placing" };
    }
    case "linking": {
      const n = s.rooms.length;
      const wanted = Math.max(0, n - 1) + (n >= 4 ? 1 : 0);
      let links = s.links;
      let rng = s.rng;
      if (links.length < wanted) {
        if (links.length < n - 1) links = [...links, [links.length, links.length + 1]];
        else {
          // One extra corridor between two rooms that are not neighbours in the line makes a loop.
          let a: number;
          let b: number;
          [a, rng] = pickInt(rng, 0, n - 3);
          [b, rng] = pickInt(rng, a + 2, n - 1);
          links = [...links, [a, b]];
        }
      }
      return { ...s, rng, links, phase: links.length >= wanted ? "checking" : "linking" };
    }
    case "checking": {
      if (s.rooms.length >= 2 && isGood(s.rooms, s.links, params)) return finish(s, s.rooms, s.links, params, false);
      if (s.attempt >= p.attempts) {
        const safe = plain(params);
        return finish(s, safe.rooms, safe.links, params, true);
      }
      // Try again from the next number in the same sequence.
      return { ...s, phase: "placing", attempt: s.attempt + 1, rooms: [], tries: 0, links: [] };
    }
  }
}

/** Runs the job to the end. `limit` stops a mistake from looping for ever. */
export function generate(seed: number, params: Params = DEFAULT_PARAMS, limit = 1_000_000): State {
  let s = initialState(params, seed);
  for (let i = 0; i < limit && s.phase !== "ready"; i++) s = step(s, params);
  return s;
}
The tests the reference code passes
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { forAll, int, pick, real, seeded, type Rng } from "../../../proofs/property.ts";
import { DEFAULT_PARAMS, type Params, type Room, type State, distances, generate, initialState, isGood, phase, step } from "./reference.ts";

const P = DEFAULT_PARAMS;
const center = (r: Room): [number, number] => [r.x + Math.floor(r.w / 2), r.y + Math.floor(r.h / 2)];
const impossible: Params = { ...P, minExitDistance: 100, maxAttempts: 3 };

/** Everything a good dungeon must be, whatever the settings. */
function assertSound(s: State, params: Params) {
  assert.equal(s.phase, "ready");
  const width = Math.max(5, Math.floor(params.width));
  const height = Math.max(5, Math.floor(params.height));
  assert.equal(s.grid.length, height);
  assert.ok(s.grid.every((row) => row.length === width));
  // The outer ring is wall.
  assert.ok(s.grid[0].split("").every((c) => c === "#") && s.grid[height - 1].split("").every((c) => c === "#"));
  assert.ok(s.grid.every((row) => row[0] === "#" && row[width - 1] === "#"));
  for (const r of s.rooms) assert.ok(r.x >= 1 && r.y >= 1 && r.x + r.w <= width - 1 && r.y + r.h <= height - 1, `room outside: ${JSON.stringify(r)}`);
  s.rooms.forEach((a, i) => s.rooms.forEach((b, j) => {
    if (i < j) assert.ok(!(a.x - 1 < b.x + b.w && b.x - 1 < a.x + a.w && a.y - 1 < b.y + b.h && b.y - 1 < a.y + a.h), "rooms touch");
  }));
  const dist = distances(s.grid, center(s.rooms[s.start]));
  s.grid.forEach((row, y) => [...row].forEach((c, x) => {
    if (c === ".") assert.ok(dist[y][x] >= 0, `cell ${x},${y} cannot be reached`);
  }));
  assert.ok(s.rooms.length >= 2);
  assert.notEqual(s.start, s.exit);
}

test("the-same-seed-gives-the-same-dungeon", () => {
  assert.deepEqual(generate(7, P), generate(7, P));
  assert.deepEqual(generate(123456, P).grid, generate(123456, P).grid);
});

test("different-seeds-give-different-dungeons", () => {
  const grids = new Set<string>();
  for (let seed = 1; seed <= 20; seed++) grids.add(generate(seed, P).grid.join("/"));
  assert.ok(grids.size >= 18, `only ${grids.size} different dungeons`);
});

test("every-floor-cell-can-be-reached", () => {
  for (let seed = 1; seed <= 30; seed++) assertSound(generate(seed, P), P);
});

test("rooms-stay-inside-the-edges-and-never-touch", () => {
  for (let seed = 100; seed < 130; seed++) {
    const s = generate(seed, P);
    assertSound(s, P);
    assert.ok(s.rooms.length <= P.roomCount);
  }
});

test("the-exit-is-far-from-the-start", () => {
  let checked = 0;
  for (let seed = 1; seed <= 40; seed++) {
    const s = generate(seed, P);
    if (s.fallback) continue;
    const dist = distances(s.grid, center(s.rooms[s.start]));
    const [ex, ey] = center(s.rooms[s.exit]);
    assert.ok(dist[ey][ex] >= P.minExitDistance, `exit only ${dist[ey][ex]} away`);
    checked++;
  }
  assert.ok(checked >= 20, "too many dungeons fell back to the plain one");
});

test("the-job-always-ends-even-when-the-demands-cannot-be-met", () => {
  const s = generate(5, impossible);
  assert.equal(s.phase, "ready");
  assert.equal(s.fallback, true);
  assert.equal(s.attempt, 3);
  assertSound(s, impossible);
});

test("a-failed-try-goes-on-with-the-same-random-sequence", () => {
  let s = initialState(impossible, 9);
  let first: Room[] = [];
  while (s.attempt === 1) {
    if (s.phase === "checking") first = s.rooms;
    s = step(s, impossible);
  }
  assert.equal(s.attempt, 2);
  assert.equal(s.phase, "placing");
  assert.notEqual(s.rng, s.seed);
  assert.deepEqual(s.rooms, []);
  while (s.phase !== "checking") s = step(s, impossible);
  assert.notDeepEqual(s.rooms, first);
});

test("the-plain-dungeon-is-always-a-good-one", () => {
  const a = generate(1, impossible);
  const b = generate(2, impossible);
  assert.deepEqual(a.grid, b.grid);
  assert.ok(isGood(a.rooms, a.links, { ...impossible, minExitDistance: 5 }));
  assertSound(a, impossible);
});

test("no-more-rooms-than-wished", () => {
  for (const wish of [3, 5, 12]) {
    const params = { ...P, roomCount: wish };
    for (let seed = 1; seed <= 10; seed++) assert.ok(generate(seed, params).rooms.length <= wish);
  }
});

test("a-half-made-dungeon-can-be-saved-and-continued", () => {
  let s = initialState(P, 42);
  for (let i = 0; i < 200 && s.phase !== "ready"; i++) s = step(s, P);
  const saved: State = JSON.parse(JSON.stringify(s));
  let again = saved;
  while (s.phase !== "ready") s = step(s, P);
  while (again.phase !== "ready") again = step(again, P);
  assert.deepEqual(again, s);
  assert.deepEqual(s, generate(42, P));
});

test("edge-seed-zero-a-negative-seed-and-a-broken-seed-all-work", () => {
  for (const seed of [0, -5, 2 ** 40, 3.7, Number.NaN]) assertSound(generate(seed, P), P);
  assert.deepEqual(generate(Number.NaN, P).grid, generate(0, P).grid);
});

test("edge-rooms-as-big-as-the-smallest-map-allows", () => {
  const tight = { ...P, width: 20, height: 14, maxRoomSize: 12 };
  for (let seed = 1; seed <= 10; seed++) assertSound(generate(seed, tight), tight);
});

test("edge-more-rooms-wished-than-the-map-can-hold", () => {
  const crowded = { ...P, width: 20, height: 14, roomCount: 20 };
  for (let seed = 1; seed <= 5; seed++) {
    const s = generate(seed, crowded);
    assertSound(s, crowded);
    assert.ok(s.rooms.length < 20);
  }
});

test("edge-a-ready-dungeon-does-not-change-when-stepped-again", () => {
  const s = generate(3, P);
  assert.equal(step(s, P), s);
});

test("edge-one-attempt-allowed-and-it-fails", () => {
  const once = { ...P, minExitDistance: 100, maxAttempts: 1 };
  const s = generate(11, once);
  assert.equal(s.fallback, true);
  assert.equal(s.attempt, 1);
});

test("edge-stepping-never-changes-the-state-it-was-given", () => {
  let s = initialState(P, 8);
  for (let i = 0; i < 400 && s.phase !== "ready"; i++) {
    const snapshot = JSON.stringify(s);
    const next = step(s, P);
    assert.equal(JSON.stringify(s), snapshot);
    s = next;
  }
});

const LISTED: { name: keyof Params; min: number; max: number }[] = JSON.parse(readFileSync(new URL("./mechanic.json", import.meta.url), "utf8")).spec.parameters;

function anyParams(r: Rng): Params {
  const values = LISTED.map(({ name, min, max }) => [name, pick(r, [min, max, Math.round(real(r, min, max)), Math.round(real(r, min, max))])]);
  return Object.fromEntries(values);
}

test("property: the job always ends with a sound dungeon, whatever the settings", (t) => {
  forAll(t, 181, 150, (r) => {
    const params = anyParams(r);
    const s = generate(int(r, 0, 4_000_000_000), params, 200_000);
    assertSound(s, params);
    assert.ok(s.attempt <= Math.max(1, params.maxAttempts));
    assert.ok(s.rooms.length <= Math.max(2, params.roomCount) || s.fallback);
  });
});

test("property: a dungeon is the plain one only when every try failed", (t) => {
  forAll(t, 182, 150, (r) => {
    const params = anyParams(r);
    const s = generate(int(r, 0, 100000), params, 200_000);
    if (s.fallback) assert.equal(s.attempt, Math.max(1, params.maxAttempts));
    else assert.ok(isGood(s.rooms, s.links, params));
  });
});

test("property: the same seed and settings always make the same dungeon", (t) => {
  forAll(t, 183, 60, (r) => {
    const params = anyParams(r);
    const seed = int(r, 0, 1_000_000);
    assert.deepEqual(generate(seed, params, 200_000), generate(seed, params, 200_000));
  });
});

/* The diagram in mechanic.json. Staying in the same state is not a move, so only changes count. */
const MODEL: { states: { id: string; start?: boolean }[]; moves: { from: string; to: string }[] } = JSON.parse(readFileSync(new URL("./mechanic.json", import.meta.url), "utf8")).model;

function observe(params: Params, seed: number): { changes: Set<string>; seen: Set<string> } {
  const r = seeded(seed);
  const changes = new Set<string>();
  const seen = new Set<string>();
  for (let episode = 0; episode < 25; episode++) {
    let s = initialState(params, int(r, 0, 1_000_000));
    seen.add(phase(s));
    for (let n = 0; n < 200_000 && s.phase !== "ready"; n++) {
      const before = phase(s);
      s = step(s, params);
      const after = phase(s);
      seen.add(after);
      if (after !== before) changes.add(`${before}>${after}`);
    }
    assert.equal(s.phase, "ready");
  }
  return { changes, seen };
}

test("model-matches-code", () => {
  assert.equal(phase(initialState()), MODEL.states.find((s) => s.start)?.id);
  const listed = new Set(MODEL.moves.map((m) => `${m.from}>${m.to}`));
  const ids = new Set(MODEL.states.map((s) => s.id));
  const cases: Params[] = [P];
  for (const { name, min, max } of LISTED) for (const value of [min, max]) cases.push({ ...P, [name]: value });
  const allChanges = new Set<string>();
  const allSeen = new Set<string>();
  cases.forEach((params, i) => {
    const { changes, seen } = observe(params, 1100 + i);
    for (const move of changes) assert.ok(listed.has(move), `the code does a move the diagram does not list: ${move} (case ${i})`);
    for (const id of seen) assert.ok(ids.has(id), `the code reaches a state the diagram does not list: ${id}`);
    changes.forEach((c) => allChanges.add(c));
    seen.forEach((c) => allSeen.add(c));
  });
  for (const id of ids) assert.ok(allSeen.has(id), `the diagram lists a state the code never reaches: ${id}`);
  for (const move of listed) assert.ok(allChanges.has(move), `the diagram lists a move the code never makes: ${move}`);
});

Open the blueprint: Procedural Dungeons

Was this page helpful?

One click, no account. It shows us which pages help.

Next step

Origins

Which Game Had the First Double Jump? Namco's Dragon Buster

Earliest documented: Dragon Buster (Namco), December 1984 per Guinness, early 1985 per others. With a sourced timeline to 2018 and tested code to build it.

Sources

Last updated: 2026-11-26