From 1bcd7318974fb4ce79c187ff5074242b7a07a23a Mon Sep 17 00:00:00 2001 From: Francois Date: Tue, 7 Oct 2025 20:27:07 +0900 Subject: [PATCH] feat: add aldous-broder maze generator --- PROJECT_DESCRIPTION.md | 2 +- README.md | 4 ++-- ROADMAP.md | 2 +- docs/index.d.ts | 8 +++++++ examples/mazeAldous.ts | 11 ++++++++++ src/index.ts | 8 +++++++ src/procedural/maze.ts | 45 ++++++++++++++++++++++++++++++++++++++++ tests/index.test.ts | 2 ++ tests/mazeAldous.test.ts | 25 ++++++++++++++++++++++ 9 files changed, 103 insertions(+), 4 deletions(-) create mode 100644 examples/mazeAldous.ts create mode 100644 tests/mazeAldous.test.ts diff --git a/PROJECT_DESCRIPTION.md b/PROJECT_DESCRIPTION.md index 15403f1..d568f32 100644 --- a/PROJECT_DESCRIPTION.md +++ b/PROJECT_DESCRIPTION.md @@ -36,7 +36,7 @@ npm run build | Need | Algorithm(s) | Module | Example | | ---- | ------------ | ------ | ------- | | Grid pathfinding | `astar`, `dijkstra`, `jumpPointSearch`, `computeFlowField`, `buildNavMesh`, `findNavMeshPath`, `manhattanDistance`, `gridFromString` | `pathfinding/astar.ts`, `pathfinding/dijkstra.ts`, `pathfinding/jumpPointSearch.ts`, `pathfinding/flowField.ts`, `pathfinding/navMesh.ts` | `examples/astar.ts`, `examples/flowField.ts`, `examples/navMesh.ts` | -| Procedural textures & terrain | `perlin`, `perlin3D`, `simplex2D`, `simplex3D`, `worley`, `worleySample`, `waveFunctionCollapse`, `cellularAutomataCave`, `poissonDiskSampling`, `computeVoronoiDiagram`, `diamondSquare`, `generateLSystem`, `generateBspDungeon`, `generateRecursiveMaze`, `generatePrimMaze`, `generateKruskalMaze`, `generateWilsonMaze` | `procedural/*.ts` | `examples/simplex.ts`, `examples/worley.ts`, `examples/waveFunctionCollapse.ts`, `examples/cellularAutomata.ts`, `examples/poissonDisk.ts`, `examples/voronoi.ts`, `examples/diamondSquare.ts`, `examples/lSystem.ts`, `examples/dungeonBsp.ts`, `examples/mazeRecursive.ts`, `examples/mazePrim.ts`, `examples/mazeKruskal.ts`, `examples/mazeWilson.ts` | +| Procedural textures & terrain | `perlin`, `perlin3D`, `simplex2D`, `simplex3D`, `worley`, `worleySample`, `waveFunctionCollapse`, `cellularAutomataCave`, `poissonDiskSampling`, `computeVoronoiDiagram`, `diamondSquare`, `generateLSystem`, `generateBspDungeon`, `generateRecursiveMaze`, `generatePrimMaze`, `generateKruskalMaze`, `generateWilsonMaze`, `generateAldousBroderMaze` | `procedural/*.ts` | `examples/simplex.ts`, `examples/worley.ts`, `examples/waveFunctionCollapse.ts`, `examples/cellularAutomata.ts`, `examples/poissonDisk.ts`, `examples/voronoi.ts`, `examples/diamondSquare.ts`, `examples/lSystem.ts`, `examples/dungeonBsp.ts`, `examples/mazeRecursive.ts`, `examples/mazePrim.ts`, `examples/mazeKruskal.ts`, `examples/mazeWilson.ts`, `examples/mazeAldous.ts` | | Spatial queries & collision | `Quadtree`, `aabbCollision`, `aabbIntersection`, `satCollision`, `circleRayIntersection`, `sweptAABB` | `spatial/*.ts` | `examples/sat.ts` | | Web performance & UI throttling | `debounce`, `throttle`, `LRUCache`, `memoize`, `deduplicateRequest`, `clearRequestDedup`, `calculateVirtualRange` | `util/*.ts` | `examples/requestDedup.ts`, `examples/virtualScroll.ts` | | Text & search | `fuzzySearch`, `fuzzyScore`, `Trie`, `binarySearch`, `levenshteinDistance` | `search/*.ts` | `examples/search.ts` | diff --git a/README.md b/README.md index cf622b7..ac1a67e 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ CDN usage: | Goal | Algorithms | Import From | Example | | ---- | ---------- | ----------- | ------- | | Pathfinding & navigation | `astar`, `dijkstra`, `jumpPointSearch`, `computeFlowField`, `buildNavMesh`, `findNavMeshPath`, `manhattanDistance`, `gridFromString` | `pathfinding/astar.ts`, `pathfinding/dijkstra.ts`, `pathfinding/jumpPointSearch.ts`, `pathfinding/flowField.ts`, `pathfinding/navMesh.ts` | `examples/astar.ts`, `examples/flowField.ts`, `examples/navMesh.ts` | -| Procedural generation | `perlin`, `perlin3D`, `simplex2D`, `simplex3D`, `worley`, `worleySample`, `waveFunctionCollapse`, `cellularAutomataCave`, `poissonDiskSampling`, `computeVoronoiDiagram`, `diamondSquare`, `generateLSystem`, `generateBspDungeon`, `generateRecursiveMaze`, `generatePrimMaze`, `generateKruskalMaze`, `generateWilsonMaze` | `procedural/*.ts` | `examples/simplex.ts`, `examples/worley.ts`, `examples/waveFunctionCollapse.ts`, `examples/cellularAutomata.ts`, `examples/poissonDisk.ts`, `examples/voronoi.ts`, `examples/diamondSquare.ts`, `examples/lSystem.ts`, `examples/dungeonBsp.ts`, `examples/mazeRecursive.ts`, `examples/mazePrim.ts`, `examples/mazeKruskal.ts`, `examples/mazeWilson.ts` | +| Procedural generation | `perlin`, `perlin3D`, `simplex2D`, `simplex3D`, `worley`, `worleySample`, `waveFunctionCollapse`, `cellularAutomataCave`, `poissonDiskSampling`, `computeVoronoiDiagram`, `diamondSquare`, `generateLSystem`, `generateBspDungeon`, `generateRecursiveMaze`, `generatePrimMaze`, `generateKruskalMaze`, `generateWilsonMaze`, `generateAldousBroderMaze` | `procedural/*.ts` | `examples/simplex.ts`, `examples/worley.ts`, `examples/waveFunctionCollapse.ts`, `examples/cellularAutomata.ts`, `examples/poissonDisk.ts`, `examples/voronoi.ts`, `examples/diamondSquare.ts`, `examples/lSystem.ts`, `examples/dungeonBsp.ts`, `examples/mazeRecursive.ts`, `examples/mazePrim.ts`, `examples/mazeKruskal.ts`, `examples/mazeWilson.ts`, `examples/mazeAldous.ts` | | Spatial queries & collision | `Quadtree`, `aabbCollision`, `aabbIntersection`, `satCollision`, `circleRayIntersection`, `sweptAABB` | `spatial/*.ts` | `examples/sat.ts` | | AI behaviours & crowds | `seek`, `flee`, `arrive`, `pursue`, `wander`, `updateBoids`, `BehaviorTree`, `rvoStep` | `ai/steering.ts`, `ai/boids.ts`, `ai/behaviorTree.ts`, `ai/rvo.ts` | `examples/steering.ts`, `examples/boids.ts`, `examples/rvo.ts` | | Web performance & UI | `debounce`, `throttle`, `LRUCache`, `memoize`, `deduplicateRequest`, `clearRequestDedup`, `calculateVirtualRange` | `util/*.ts` | `examples/requestDedup.ts`, `examples/virtualScroll.ts` | @@ -52,7 +52,7 @@ npm run size # Enforce bundle size budget - Milestone 0.2 next targets crowd-flow integrations (RVO + flow fields) and behaviour-tree decorators for richer AI control. - Milestone 0.4 plans a procedural + gameplay systems toolkit (Wave Function Collapse, dungeon suite, L-systems, game loop, camera, particles, inventory, combat, save/load, and more). -Examples live under `examples/` and can be executed with `tsx`/`ts-node` or compiled for the browser. See `examples/astar.ts`, `examples/flowField.ts`, `examples/navMesh.ts`, `examples/cellularAutomata.ts`, `examples/poissonDisk.ts`, `examples/voronoi.ts`, `examples/diamondSquare.ts`, `examples/lSystem.ts`, `examples/dungeonBsp.ts`, `examples/mazeRecursive.ts`, `examples/mazePrim.ts`, `examples/mazeKruskal.ts`, `examples/mazeWilson.ts`, `examples/steering.ts`, `examples/boids.ts`, `examples/requestDedup.ts`, `examples/search.ts`, `examples/graph.ts`, `examples/geometry.ts`, `examples/visual.ts`, `examples/sat.ts`, `examples/simplex.ts`, and `examples/worley.ts` for quick starts. The `examples` registry exported from `src/index.ts` provides a typed index you can traverse programmatically. +Examples live under `examples/` and can be executed with `tsx`/`ts-node` or compiled for the browser. See `examples/astar.ts`, `examples/flowField.ts`, `examples/navMesh.ts`, `examples/cellularAutomata.ts`, `examples/poissonDisk.ts`, `examples/voronoi.ts`, `examples/diamondSquare.ts`, `examples/lSystem.ts`, `examples/dungeonBsp.ts`, `examples/mazeRecursive.ts`, `examples/mazePrim.ts`, `examples/mazeKruskal.ts`, `examples/mazeWilson.ts`, `examples/mazeAldous.ts`, `examples/steering.ts`, `examples/boids.ts`, `examples/requestDedup.ts`, `examples/search.ts`, `examples/graph.ts`, `examples/geometry.ts`, `examples/visual.ts`, `examples/sat.ts`, `examples/simplex.ts`, and `examples/worley.ts` for quick starts. The `examples` registry exported from `src/index.ts` provides a typed index you can traverse programmatically. ## Contributing 1. Fork the repository. diff --git a/ROADMAP.md b/ROADMAP.md index 652e9c2..b45743c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -42,7 +42,7 @@ - [x] Diamond-square terrain height map generator - [x] L-system generator for foliage and organic structures - [x] Dungeon generation suite (BSP subdivision, rooms & corridors variants) - - [ ] Maze algorithms pack (Recursive backtracking ✅, Prim's ✅, Kruskal's ✅, Wilson's ✅, Aldous–Broder, Recursive Division) + - [ ] Maze algorithms pack (Recursive backtracking ✅, Prim's ✅, Kruskal's ✅, Wilson's ✅, Aldous–Broder ✅, Recursive Division) - Gameplay systems & utilities: - [ ] Fixed-timestep game loop utility with interpolation helpers - [ ] Delta-time manager for frame-independent timing diff --git a/docs/index.d.ts b/docs/index.d.ts index 9e1284f..718d14b 100644 --- a/docs/index.d.ts +++ b/docs/index.d.ts @@ -637,6 +637,14 @@ export function generateKruskalMaze(options: MazeOptions): MazeResult; */ export function generateWilsonMaze(options: MazeOptions): MazeResult; +/** + * Generates a maze using the Aldous–Broder algorithm. + * Use for: unbiased random mazes through random walks. + * Performance: O(width × height × visits). + * Import: procedural/maze.ts + */ +export function generateAldousBroderMaze(options: MazeOptions): MazeResult; + /** * Simplex noise generator for smooth gradients without directional artifacts. * Use for: large terrain synthesis, animated textures, volumetric noise. diff --git a/examples/mazeAldous.ts b/examples/mazeAldous.ts new file mode 100644 index 0000000..3b64cd8 --- /dev/null +++ b/examples/mazeAldous.ts @@ -0,0 +1,11 @@ +import { generateAldousBroderMaze } from '../src/index.js'; + +const { grid, start, end } = generateAldousBroderMaze({ + width: 21, + height: 21, + seed: 2048, +}); + +console.log('Start:', start); +console.log('End:', end); +console.log('Middle row:', grid[10]?.join('')); diff --git a/src/index.ts b/src/index.ts index dc221dd..86435aa 100644 --- a/src/index.ts +++ b/src/index.ts @@ -52,6 +52,7 @@ export const examples = { generatePrimMaze: 'examples/mazePrim.ts', generateKruskalMaze: 'examples/mazeKruskal.ts', generateWilsonMaze: 'examples/mazeWilson.ts', + generateAldousBroderMaze: 'examples/mazeAldous.ts', }, spatial: { Quadtree: 'examples/sat.ts', @@ -306,6 +307,13 @@ export { generateKruskalMaze } from './procedural/maze.js'; */ export { generateWilsonMaze } from './procedural/maze.js'; +/** + * Aldous–Broder maze generator using random walks. + * + * Example file: examples/mazeAldous.ts + */ +export { generateAldousBroderMaze } from './procedural/maze.js'; + // ============================================================================ // 🎯 SPATIAL & COLLISION // ============================================================================ diff --git a/src/procedural/maze.ts b/src/procedural/maze.ts index 23ca9bc..0c7cce2 100644 --- a/src/procedural/maze.ts +++ b/src/procedural/maze.ts @@ -251,6 +251,51 @@ export function generateWilsonMaze({ return { grid, start, end }; } +/** + * Generates a maze using the Aldous–Broder random walk algorithm. + * Useful for: unbiased mazes with uniform spanning tree distribution. + */ +export function generateAldousBroderMaze({ + width, + height, + seed = Date.now(), +}: MazeOptions): MazeResult { + validateDimensions(width, height); + + const grid = Array.from({ length: height }, () => Array(width).fill(WALL)); + const random = createLinearCongruentialGenerator(seed); + + const cells: Cell[] = []; + const visited = new Set(); + for (let y = 1; y < height; y += 2) { + for (let x = 1; x < width; x += 2) { + cells.push({ x, y }); + } + } + + let current = cells[Math.floor(random() * cells.length)] ?? { x: 1, y: 1 }; + carveCell(grid, current); + visited.add(cellKey(current.x, current.y)); + + while (visited.size < cells.length) { + const next = randomOddNeighbour(current, grid, random); + const key = cellKey(next.x, next.y); + if (!visited.has(key)) { + carveCorridorBetween(grid, current, next); + carveCell(grid, next); + visited.add(key); + } + current = next; + } + + const start: Cell = { x: 1, y: 1 }; + carveCell(grid, start); + const end = findFarthestCell(start, grid); + carveCell(grid, end); + + return { grid, start, end }; +} + function validateDimensions(width: number, height: number): void { if (!Number.isInteger(width) || !Number.isInteger(height)) { throw new Error('width and height must be integers.'); diff --git a/tests/index.test.ts b/tests/index.test.ts index bea0623..51942f6 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -18,6 +18,7 @@ describe('package entry point', () => { expect(examples.procedural.generatePrimMaze).toBe('examples/mazePrim.ts'); expect(examples.procedural.generateKruskalMaze).toBe('examples/mazeKruskal.ts'); expect(examples.procedural.generateWilsonMaze).toBe('examples/mazeWilson.ts'); + expect(examples.procedural.generateAldousBroderMaze).toBe('examples/mazeAldous.ts'); expect(examples.search.Trie).toBe('examples/search.ts'); expect(examples.pathfinding.buildNavMesh).toBe('examples/navMesh.ts'); }); @@ -66,6 +67,7 @@ describe('package entry point', () => { | 'generatePrimMaze' | 'generateKruskalMaze' | 'generateWilsonMaze' + | 'generateAldousBroderMaze' >(); }); }); diff --git a/tests/mazeAldous.test.ts b/tests/mazeAldous.test.ts new file mode 100644 index 0000000..664ce91 --- /dev/null +++ b/tests/mazeAldous.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest'; + +import { generateAldousBroderMaze } from '../src/index.js'; + +describe('generateAldousBroderMaze', () => { + it('returns deterministic mazes for identical seeds', () => { + const options = { width: 21, height: 21, seed: 888 } as const; + const a = generateAldousBroderMaze(options); + const b = generateAldousBroderMaze(options); + + expect(a.grid).toEqual(b.grid); + expect(a.start).toEqual(b.start); + expect(a.end).toEqual(b.end); + }); + + it('produces walkable paths in a walled grid', () => { + const { grid } = generateAldousBroderMaze({ width: 17, height: 17, seed: 42 }); + expect(grid.length).toBe(17); + expect(grid.every((row) => row.length === 17)).toBe(true); + expect(grid[0].every((cell) => cell === 1)).toBe(true); + expect(grid[grid.length - 1].every((cell) => cell === 1)).toBe(true); + expect(grid.every((row) => row[0] === 1 && row[row.length - 1] === 1)).toBe(true); + expect(grid.flat().some((cell) => cell === 0)).toBe(true); + }); +});