Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion PROJECT_DESCRIPTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions docs/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.
Expand Down
11 changes: 11 additions & 0 deletions examples/mazePrim.ts
Original file line number Diff line number Diff line change
@@ -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(''));
8 changes: 8 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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
// ============================================================================
Expand Down
84 changes: 82 additions & 2 deletions src/procedural/maze.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number>(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.');
Expand All @@ -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 });
}
}
Expand All @@ -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) {
Expand Down
4 changes: 4 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
Expand Down Expand Up @@ -58,6 +60,8 @@ describe('package entry point', () => {
| 'diamondSquare'
| 'generateLSystem'
| 'generateBspDungeon'
| 'generateRecursiveMaze'
| 'generatePrimMaze'
>();
});
});
29 changes: 29 additions & 0 deletions tests/mazePrim.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});