diff --git a/PROJECT_DESCRIPTION.md b/PROJECT_DESCRIPTION.md index 63a79e3..027e52e 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` | `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` | +| Procedural textures & terrain | `perlin`, `perlin3D`, `simplex2D`, `simplex3D`, `worley`, `worleySample`, `waveFunctionCollapse`, `cellularAutomataCave`, `poissonDiskSampling`, `computeVoronoiDiagram`, `diamondSquare`, `generateLSystem`, `generateBspDungeon`, `generateRecursiveMaze`, `generatePrimMaze` | `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` | | 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 affaafc..3fd95be 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` | `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` | +| Procedural generation | `perlin`, `perlin3D`, `simplex2D`, `simplex3D`, `worley`, `worleySample`, `waveFunctionCollapse`, `cellularAutomataCave`, `poissonDiskSampling`, `computeVoronoiDiagram`, `diamondSquare`, `generateLSystem`, `generateBspDungeon`, `generateRecursiveMaze`, `generatePrimMaze` | `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` | | 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/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/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 40ab4a0..aefe592 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 e3532c2..9d5dc56 100644 --- a/docs/index.d.ts +++ b/docs/index.d.ts @@ -53,6 +53,7 @@ export const examples: { readonly generateLSystem: 'examples/lSystem.ts'; readonly generateBspDungeon: 'examples/dungeonBsp.ts'; readonly generateRecursiveMaze: 'examples/mazeRecursive.ts'; + readonly generatePrimMaze: 'examples/mazePrim.ts'; }; readonly spatial: { readonly Quadtree: 'examples/sat.ts'; @@ -610,6 +611,14 @@ export interface MazeResult { */ export function generateRecursiveMaze(options: MazeOptions): MazeResult; +/** + * Generates a maze using Prim's algorithm. + * Use for: compact mazes with branching corridors, alternative structures. + * Performance: O(width × height). + * Import: procedural/maze.ts + */ +export function generatePrimMaze(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/mazePrim.ts b/examples/mazePrim.ts new file mode 100644 index 0000000..0eda14c --- /dev/null +++ b/examples/mazePrim.ts @@ -0,0 +1,11 @@ +import { generatePrimMaze } from '../src/index.js'; + +const { grid, start, end } = generatePrimMaze({ + width: 21, + height: 21, + seed: 512, +}); + +console.log('Start:', start); +console.log('End:', end); +console.log('Middle row preview:', grid[10]?.join('')); diff --git a/src/index.ts b/src/index.ts index 282eb7c..918d586 100644 --- a/src/index.ts +++ b/src/index.ts @@ -49,6 +49,7 @@ export const examples = { generateLSystem: 'examples/lSystem.ts', generateBspDungeon: 'examples/dungeonBsp.ts', generateRecursiveMaze: 'examples/mazeRecursive.ts', + generatePrimMaze: 'examples/mazePrim.ts', }, spatial: { Quadtree: 'examples/sat.ts', @@ -282,6 +283,13 @@ export { generateBspDungeon } from './procedural/dungeonBsp.js'; */ export { generateRecursiveMaze } from './procedural/maze.js'; +/** + * Prim's maze generator for alternative maze structures. + * + * Example file: examples/mazePrim.ts + */ +export { generatePrimMaze } from './procedural/maze.js'; + // ============================================================================ // 🎯 SPATIAL & COLLISION // ============================================================================ diff --git a/src/procedural/maze.ts b/src/procedural/maze.ts index 5ccc07f..d3965f8 100644 --- a/src/procedural/maze.ts +++ b/src/procedural/maze.ts @@ -63,6 +63,53 @@ export function generateRecursiveMaze({ return { grid, start, end }; } +/** + * Generates a maze using randomized Prim's algorithm. + * Useful for: maze layouts with different structural characteristics than DFS. + */ +export function generatePrimMaze({ + 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 start: Cell = { x: 1, y: 1 }; + carveCell(grid, start); + + const frontier: Cell[] = []; + addFrontierCells(start, grid, frontier); + + while (frontier.length > 0) { + const index = Math.floor(random() * frontier.length); + const [cell] = frontier.splice(index, 1); + if (!cell) { + continue; + } + + const neighbours = shuffledNeighbours(cell, grid, random).filter((candidate) => !isWall(candidate, grid)); + if (neighbours.length === 0) { + continue; + } + + const neighbour = neighbours[Math.floor(random() * neighbours.length)]; + if (!neighbour) { + continue; + } + carveCorridorBetween(grid, cell, neighbour); + carveCell(grid, cell); + addFrontierCells(cell, grid, frontier); + } + + 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.'); @@ -88,10 +135,11 @@ function shuffledNeighbours(cell: Cell, grid: number[][], random: () => number): } const neighbours: Cell[] = []; + const width = grid[0]?.length ?? 0; for (const [dx, dy] of offsets) { const nx = cell.x + dx; const ny = cell.y + dy; - if (ny > 0 && ny < grid.length && nx > 0 && nx < grid[0]!.length) { + if (ny > 0 && ny < grid.length && nx > 0 && nx < width) { neighbours.push({ x: nx, y: ny }); } } @@ -108,11 +156,43 @@ function carveCell(grid: number[][], cell: Cell): void { } } +function carveCorridorBetween(grid: number[][], from: Cell, to: Cell): void { + const mid = { + x: from.x + (to.x - from.x) / 2, + y: from.y + (to.y - from.y) / 2, + }; + carveCell(grid, mid); + carveCell(grid, to); +} + +function addFrontierCells(cell: Cell, grid: number[][], frontier: Cell[]): void { + const height = grid.length; + const width = grid[0]?.length ?? 0; + const offsets: Array<[number, number]> = [ + [0, -2], + [2, 0], + [0, 2], + [-2, 0], + ]; + + for (const [dx, dy] of offsets) { + const nx = cell.x + dx; + const ny = cell.y + dy; + if (ny > 0 && ny < height && nx > 0 && nx < width && grid[ny][nx] === WALL) { + const alreadyFrontier = frontier.some((frontierCell) => frontierCell.x === nx && frontierCell.y === ny); + if (!alreadyFrontier) { + frontier.push({ x: nx, y: ny }); + } + } + } +} + function findFarthestCell(start: Cell, grid: number[][]): Cell { let farthest = start; let maxDistance = -1; + const width = grid[0]?.length ?? 0; for (let y = 1; y < grid.length; y += 2) { - for (let x = 1; x < grid[0]!.length; x += 2) { + for (let x = 1; x < width; x += 2) { if (grid[y][x] === PATH) { const distance = Math.abs(start.x - x) + Math.abs(start.y - y); if (distance > maxDistance) { diff --git a/tests/index.test.ts b/tests/index.test.ts index 2699f9a..1cacc9d 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -14,6 +14,8 @@ describe('package entry point', () => { expect(examples.procedural.diamondSquare).toBe('examples/diamondSquare.ts'); expect(examples.procedural.generateLSystem).toBe('examples/lSystem.ts'); expect(examples.procedural.generateBspDungeon).toBe('examples/dungeonBsp.ts'); + expect(examples.procedural.generateRecursiveMaze).toBe('examples/mazeRecursive.ts'); + expect(examples.procedural.generatePrimMaze).toBe('examples/mazePrim.ts'); expect(examples.search.Trie).toBe('examples/search.ts'); expect(examples.pathfinding.buildNavMesh).toBe('examples/navMesh.ts'); }); @@ -58,6 +60,8 @@ describe('package entry point', () => { | 'diamondSquare' | 'generateLSystem' | 'generateBspDungeon' + | 'generateRecursiveMaze' + | 'generatePrimMaze' >(); }); }); diff --git a/tests/mazePrim.test.ts b/tests/mazePrim.test.ts new file mode 100644 index 0000000..bef4edd --- /dev/null +++ b/tests/mazePrim.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest'; + +import { generatePrimMaze } from '../src/index.js'; + +describe('generatePrimMaze', () => { + it('is deterministic for identical seeds', () => { + const options = { width: 21, height: 21, seed: 333 } as const; + const a = generatePrimMaze(options); + const b = generatePrimMaze(options); + + expect(a.grid).toEqual(b.grid); + expect(a.start).toEqual(b.start); + expect(a.end).toEqual(b.end); + }); + + it('carves corridors bounded by walls', () => { + const { grid } = generatePrimMaze({ width: 15, height: 15, seed: 99 }); + expect(grid.length).toBe(15); + expect(grid.every((row) => row.length === 15)).toBe(true); + + const borderTop = grid[0].every((cell) => cell === 1); + const borderBottom = grid[grid.length - 1].every((cell) => cell === 1); + const borderSides = grid.every((row) => row[0] === 1 && row[row.length - 1] === 1); + expect(borderTop && borderBottom && borderSides).toBe(true); + + const walkableTiles = grid.flat().filter((cell) => cell === 0).length; + expect(walkableTiles).toBeGreaterThan(0); + }); +});