terrain

117 procedural dungeon/terrain generation algorithms

terrain
dungeon
procedural-generation
map-generation
roguelike
gamedev
moon add mizchi/terrain@0.1.1
Download zip
Author
Version
0.1.1
License
Apache-2.0
Last updated
5 months ago
Downloads
1K
README

#terrain

117 procedural dungeon/terrain generation algorithms in MoonBit.

#Install

moon add mizchi/terrain

#Usage

Each algorithm is an independent package with a generate(config, rng) function.

fn main {
let rng = @terrain/types.make_rng(42U)

// 2D Grid algorithm
let result = @terrain/bsp.generate(
{ width: 40, height: 20, min_room_size: 4, max_depth: 4 },
rng,
)
println(result.grid.to_ascii())

// Hex algorithm
let rng = @terrain/types.make_rng(42U)
let hex = @terrain/hex_maze.generate(
{ cols: 20, rows: 15, room_chance: 0.15 },
rng,
)
println(hex.grid.to_ascii())

// 3D multi-layer algorithm
let rng = @terrain/types.make_rng(42U)
let d3 = @terrain/multifloor_bsp.generate(
{ width: 40, height: 20, depth: 3, min_room_size: 4, stair_count: 3 },
rng,
)
// Access each layer
for z in 0..<d3.grid.depth {
println("Layer " + z.to_string())
println(d3.grid.to_ascii(z))
}

// Quarter View (isometric) algorithm
let rng = @terrain/types.make_rng(42U)
let iso = @terrain/iso_city.generate(
{ width: 40, height: 20, max_height: 8, building_density: 0.7, street_width: 2 },
rng,
)
println(iso.grid.to_ascii())
// Heights available via iso.grid.heights
}

#Core Types

// Tile types
enum Tile { Floor; Wall; Door; LockedDoor; Key; Start; Goal; Corridor; Water; Empty }

// 2D grid (width x height)
struct Grid2D { width : Int; height : Int; cells : Array[Tile] }

// Hex grid (odd-r offset coordinates)
struct HexGrid { cols : Int; rows : Int; cells : Array[Tile]; orientation : Int }

// 3D multi-layer grid
struct Grid3D { width : Int; height : Int; depth : Int; layers : Array[Grid2D] }

// 2D grid with height data (for isometric rendering)
struct HeightGrid { width : Int; height : Int; cells : Array[Tile]; heights : Array[Int]; max_height : Int }

// Room descriptor
struct Room { x : Int; y : Int; w : Int; h : Int }

// Seeded RNG
struct RNG { .. }
fn make_rng(seed : UInt) -> RNG

#Pattern

Every algorithm package follows the same pattern:

// Each package exports:
pub(all) struct XxxConfig { .. } // Config with defaults
pub(all) struct XxxResult { .. } // Result with grid + rooms
pub fn XxxConfig::default() -> XxxConfig
pub fn generate(config : XxxConfig, rng : @types.RNG) -> XxxResult

Import only what you need in moon.pkg.json:

{ "import": [ "mizchi/terrain/types", "mizchi/terrain/bsp", "mizchi/terrain/cellular" ] }

#Algorithms (117)

#Maze (11)

#NamePackageDescription
0Maze (DFS)mazeRecursive backtracker depth-first search
1Eller's MazeellerRow-by-row generation with set merging
2Kruskal's MazekruskalMinimum spanning tree randomized maze
3Binary Tree Mazebinary_treeTwo-direction bias with diagonal tendency
4Sidewinder MazesidewinderHorizontal runs with random vertical connections
5Recursive Divisionrecursive_divisionRecursive wall placement subdivision
6Growing Treegrowing_treeTunable between DFS and Prim's via weight
7Wilson'swilsonLoop-erased random walk for uniform spanning tree
8Aldous-Broderaldous_broderRandom walk visiting every cell exactly once
9Hunt and Killhunt_and_killWalk until stuck, then scan for unvisited neighbor
10Pac-Man MazepacmanBilaterally symmetric maze with central chamber

#Room Placement (11)

#NamePackageDescription
11BSP TreebspBinary space partition with rooms in leaves
12Poisson DiskpoissonBlue noise distributed room placement
13Rooms and Mazesrooms_and_mazesPlace rooms then fill gaps with maze corridors
14Rogue ClassicrogueGrid-based room layout inspired by original Rogue
15Room AccretionaccretionGrow dungeon by adding rooms one at a time
16TinyKeeptinykeepRandom rooms with physics-based separation
17Feature Growingfeature_growingGrow by attaching rooms and corridors to exits
18BFS Room Expansionbfs_roomsSeed-based parallel flood fill room growing
19Prefab AssemblyprefabPlace predefined room templates randomly
20Gravity Collapsegravity_collapseDrop rooms from top, stack with gravity simulation
21Tetromino PackingtetrominoPack tetris-shaped pieces into grid

#Cave / Organic (15)

#NamePackageDescription
22Cellular AutomatacellularConway-style birth/survival cave generation
23Drunkard's WalkdrunkardRandom walker carving open space
24Noise Cavesnoise_cavesValue noise with octaves for smooth caves
25DLAdlaDiffusion-limited aggregation particle sticking
26Marching Squaresmarching_squaresCellular automata with contour smoothing
27Worm TunnelswormMultiple directional worms carving passages
28ErosionerosionHydraulic erosion simulation on heightmap
29PercolationpercolationRandom fill with connectivity phase transition
30Ant Colonyant_colonyPheromone-guided ant swarm carving paths
31Worley NoiseworleyWorley/cellular noise distance-based caves
32Ridged MultifractalridgedRidged multifractal noise with sharp ridges
33Domain Warpingdomain_warpNoise with coordinate warping for organic shapes
34Reaction-Diffusionreaction_diffusionGray-Scott reaction-diffusion pattern formation
35Slime Moldslime_moldPhysarum-inspired slime mold agent simulation
36LightninglightningLightning bolt branching path generation

#Graph / Structure (10)

#NamePackageDescription
37Graph Grammargraph_grammarRule-based graph rewriting with locks and keys
38DiablodiabloLinear spine with branching side paths and loops
39SpelunkyspelunkyGrid cells with guaranteed solution path
40Arena Chainarena_chainLarge arenas connected by narrow corridors
41Cyclic Dungeoncyclic_dungeonCircular connectivity with key-gate puzzles
42MetroidvaniametroidvaniaMulti-zone layout with ability-gated connections
43Mission Graphmission_graphMission-driven node graph with lock progression
44Ring DungeonringRing corridor with rooms and Dark Souls shortcuts
45Binding of IsaacisaacGrid-based room layout inspired by Isaac
46Dead Cellsdead_cellsBranching biome path layout inspired by Dead Cells

#Space Filling (4)

#NamePackageDescription
47Hilbert CurvehilbertHilbert space-filling curve as corridor backbone
48Gosper CurvegosperFlowsnake L-system curve on hex-like grid
49SpiralspiralArchimedean spiral with rooms at intervals
50Sierpinski DungeonsierpinskiSierpinski carpet recursive subdivision

#Terrain (5)

#NamePackageDescription
51Diamond-Squarediamond_squareFractal heightmap with configurable roughness
52Midpoint Displacementmidpoint_displacementMulti-layer midpoint displacement terrain
53Island/ArchipelagoislandCircular islands connected by bridges
54River/WatershedriverHeightmap with hydraulic river carving
55Crystal GrowthcrystalAxis-aligned crystal seed growth

#Pattern / Tiling (7)

#NamePackageDescription
56WFCwfcWave Function Collapse tile solver
57SuperimpositionsuperimposeOverlapping random shape stamps
58Herringbone Wang TilesherringboneHerringbone pattern tile placement
59L-SystemlsystemLindenmayer system string rewriting paths
60Hex Gridhex_gridHexagonal cell grid with corridor connections
61City Blockcity_blockStreet grid with buildings and dead ends
62Penrose TilingpenrosePenrose-inspired aperiodic tiling dungeon

#Hybrid (6)

#NamePackageDescription
63Voronoi RegionvoronoiVoronoi cell regions with edge corridors
64RadialradialConcentric rings with spokes and gaps
65Space Colonizationspace_colonizationAttractor-based branching path growth
66Parametric TunnelerstunnelerMultiple autonomous tunneling agents
67Platformer LevelplatformerSide-scrolling level with platforms and ladders
68Delaunay + GabrieldelaunayDelaunay triangulation with Gabriel graph pruning

#Hex (10)

#NamePackageGridDescription
69Hex Mazehex_mazeHexGridDFS maze on hexagonal grid
70Hex CAhex_caHexGridCellular automata on hex grid
71Hex Voronoihex_voronoiHexGridVoronoi regions on hex grid
72Hex WFChex_wfcHexGridWave Function Collapse on hex grid
73Hex Spiralhex_spiralHexGridSpiral path on hex grid
74Hex Territoryhex_territoryHexGridFaction territory expansion on hex grid
75Hex River Deltahex_river_deltaHexGridBranching river channels from center
76Hex Fortresshex_fortressHexGridConcentric hex walls with gates and towers
77Hex Biomehex_biomeHexGridVoronoi biome regions with roads
78Hex Snowflakehex_snowflakeHexGridFractal snowflake crystal pattern

#3D Multi-Layer (10)

#NamePackageGridDescription
79Multi-Floor BSPmultifloor_bspGrid3DBSP rooms on multiple floors with stairs
803D Drunkarddrunkard_3dGrid3DRandom walk across layers
813D CAcellular_3dGrid3D3D cellular automata caves
82Vertical Shaftvertical_shaftGrid3DVertical shafts connecting horizontal rooms
83Layered Caveslayered_cavesGrid3DConnected cave systems across layers
843D Mazemaze_3dGrid3DPerfect maze with vertical passages
85Underwater Baseunderwater_baseGrid3DPressurized chambers with airlocks
86Tree Rootstree_rootsGrid3DOrganic branching roots descending through layers
87Ant Nest 3Dant_nest_3dGrid3DAnt colony with tunnels and chambers
88Space Stationspace_stationGrid3DRing habitat with central hub and spokes

#Quarter View / Isometric (16)

#NamePackageGridDescription
89Isometric Cityiso_cityHeightGridCity blocks with variable building heights
90Cliff Dungeoncliff_dungeonHeightGridRooms carved into cliff faces
91Layered Plateaulayered_plateauHeightGridEroded plateau terraces
92Castle Generatorcastle_genHeightGridCastle with towers, walls, and courtyards
93Terraced Minesterraced_minesHeightGridOpen-pit mine with ore veins
94Floating Islandsfloating_islandsHeightGridSky islands connected by bridges
95Ziggurat TemplezigguratHeightGridStepped pyramid with inner chambers
96Canyon RavinecanyonHeightGridDeep canyon with bridges and caves
97Harbor Townharbor_townHeightGridCoastal town with waterfront buildings
98Tower Dungeontower_dungeonHeightGridVertical tower with stacked floors
99Volcanic Cratervolcanic_craterHeightGridVolcanic crater with lava vents
100AmphitheateramphitheaterHeightGridTiered seating around central arena
101AqueductaqueductHeightGridRoman aqueduct with arched supports
102Treehouse VillagetreehouseHeightGridTree platforms connected by bridges
103Mineshaft ElevatormineshaftHeightGridCentral shaft with radiating tunnels
104GlacierglacierHeightGridIce field with crevasses and caves

#Biome (6)

#NamePackageDescription
105ContinentcontinentOcean, beach, forest, mountain concentric rings
106Dungeon EcosystemecosystemCave to underground river to lava biome transition
107Seasonal Forestseasonal_forestNorth-to-south tree density gradient
108Swamp LabyrinthswampIntertwined water channels and land paths
109Desert Oasisdesert_oasisDesert with scattered oases and caravan routes
110Tundra OutposttundraFrozen outposts connected by underground tunnels

#Puzzle / Progression (6)

#NamePackageDescription
111Sokoban LayoutsokobanPush-block puzzle grid rooms
112One-Way Gateoneway_gateDirected tree dungeon with one-way doors
113Teleporter MazeteleporterDisconnected room clusters linked by teleporters
114Lock Cascadelock_cascadeDeep key-lock chain progression
115Gravity Puzzlegravity_puzzleSplit gravity zones with inverted platforms
116Mirror Dungeonmirror_dungeonSymmetric dungeon with corrupted mirror half

#Development

# Install MoonBit curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash # Check moon check --deny-warn --target js # Test moon test --target js # Build web playground moon build --target js # Serve locally python3 -m http.server 8080 # Open http://localhost:8080

#License

Apache-2.0

Powered by MoonBit

Site sourceReport issuePackagesBuild queueSkillsStatistics

© 2026 mooncakes.io