Of course! Here is a Python dungeon generator that creates a linear dungeon.
Core Concepts
This generator will follow these steps:
- Initialize a Grid: Create a 2D grid filled with a "solid" character (like
# for a wall).
- Generate a Path: Create a single, non-branching path from the left side of the map to the right side. We'll use a "drunken walk" algorithm that heavily prefers moving right, ensuring it progresses from start to finish.
- Carve Rooms: Place rooms at the start and end of the path. Then, randomly place a few more rooms along the path to add variety. This guarantees all rooms are connected.
- Carve the Path: Turn the grid cells along the generated path into floor tiles (
.).
- Place Start & Finish: Mark the start (
S) and finish (F) points inside their respective rooms.
- Print the Dungeon: Display the final grid.
The Python Code
This code is contained within a single class, LinearDungeonGenerator, making it easy to use and modify.
import random
# --- Configuration ---
# You can change these values to customize the output
DUNGEON_WIDTH = 80
DUNGEON_HEIGHT = 24
MIN_ROOM_SIZE = 5
MAX_ROOM_SIZE = 9
EXTRA_ROOM_ATTEMPTS = 30 # How many times to try and place an extra room
# --- Tile Definitions ---
WALL = '#'
FLOOR = '.'
START = 'S'
FINISH = 'F'
class LinearDungeonGenerator:
"""
Generates a linear dungeon with a guaranteed path from a start room to a finish room.
"""
def __init__(self, width, height):
if width < 20 or height < 15:
raise ValueError("Dungeon dimensions are too small. Recommended minimum is 20x15.")
self.width = width
self.height = height
self.grid = []
self.path = []
self.rooms = []
def generate(self):
"""Orchestrates the dungeon generation process."""
self._initialize_grid()
self._generate_path()
self._create_rooms()
self._carve_path()
self._place_start_finish()
return self.grid
def _initialize_grid(self):
"""Fills the entire grid with solid walls."""
self.grid = [[WALL for _ in range(self.width)] for _ in range(self.height)]
def _generate_path(self):
"""
Creates a "drunken walk" path from the left to the right side of the map.
The walk heavily prefers moving right to ensure it spans the dungeon.
"""
# Start near the middle-left of the map
x = 1
y = self.height // 2
self.path.append((x, y))
while x < self.width - 2:
# Possible moves: (dx, dy)
# We give moving right a much higher chance
moves = [(1, 0), (0, -1), (0, 1)] # Right, Up, Down
weights = [8, 1, 1] # 80% chance to move right, 10% up, 10% down
dx, dy = random.choices(moves, weights)[0]
# Ensure the new position is within bounds (leaving a 1-tile border)
new_x, new_y = x + dx, y + dy
if 1 <= new_x < self.width - 1 and 1 <= new_y < self.height - 1:
x, y = new_x, new_y
if (x, y) not in self.path:
self.path.append((x, y))
def _create_rooms(self):
"""Places rooms along the generated path."""
# Must have a start and finish room
start_pos = self.path[0]
end_pos = self.path[-1]
# Carve start room
start_room = self._carve_room_at(start_pos)
if start_room: self.rooms.append(start_room)
# Carve finish room
end_room = self._carve_room_at(end_pos)
if end_room: self.rooms.append(end_room)
# Attempt to add a few more rooms in the middle of the path
for _ in range(EXTRA_ROOM_ATTEMPTS):
# Pick a random point on the path, not too close to the ends
if len(self.path) > 20:
path_index = random.randint(10, len(self.path) - 11)
pos = self.path[path_index]
new_room = self._carve_room_at(pos)
if new_room:
# Check for overlap with existing rooms
is_overlapping = any(self._rooms_overlap(new_room, r) for r in self.rooms)
if not is_overlapping:
self.rooms.append(new_room)
def _carve_room_at(self, center_pos):
"""Carves a single rectangular room centered at a given position."""
room_width = random.randint(MIN_ROOM_SIZE, MAX_ROOM_SIZE)
room_height = random.randint(MIN_ROOM_SIZE, MAX_ROOM_SIZE)
# Ensure odd dimensions for a clear center
if room_width % 2 == 0: room_width += 1
if room_height % 2 == 0: room_height += 1
center_x, center_y = center_pos
x1 = center_x - room_width // 2
y1 = center_y - room_height // 2
x2 = x1 + room_width
y2 = y1 + room_height
# Check if the room is within the map boundaries
if x1 < 1 or x2 > self.width - 1 or y1 < 1 or y2 > self.height - 1:
return None # Room is out of bounds
# Carve the floor
for y in range(y1, y2):
for x in range(x1, x2):
self.grid[y][x] = FLOOR
return (x1, y1, x2, y2) # Return rect: (x1, y1, x2, y2)
@staticmethod
def _rooms_overlap(r1, r2):
"""Check if two rectangular rooms overlap."""
return not (r1[2] < r2[0] or r1[0] > r2[2] or r1[3] < r2[1] or r1[1] > r2[3])
def _carve_path(self):
"""Carves the 1-tile wide corridor along the generated path."""
for x, y in self.path:
# Don't overwrite room floors that are already there
if self.grid[y][x] == WALL:
self.grid[y][x] = FLOOR
def _place_start_finish(self):
"""Places the Start and Finish markers in their respective rooms."""
start_x, start_y = self.path[0]
self.grid[start_y][start_x] = START
finish_x, finish_y = self.path[-1]
self.grid[finish_y][finish_x] = FINISH
def print_dungeon(self):
"""Prints the generated dungeon to the console."""
for row in self.grid:
print("".join(row))
# --- Main Execution ---
if __name__ == "__main__":
print("--- Generating a new linear dungeon ---")
# Create a generator instance with the configured dimensions
dungeon_gen = LinearDungeonGenerator(DUNGEON_WIDTH, DUNGEON_HEIGHT)
# Generate the dungeon
dungeon_gen.generate()
# Print the result
dungeon_gen.print_dungeon()
print("\nGeneration complete.")
print(f"Legend: '{WALL}'=Wall, '{FLOOR}'=Floor, '{START}'=Start, '{FINISH}'=Finish")
How to Run
- Save the code as a Python file (e.g.,
dungeon_generator.py).
- Run it from your terminal:
python dungeon_generator.py
Each time you run the script, it will produce a new, unique linear dungeon.
Example Output
--- Generating a new linear dungeon ---
################################################################################
#S...................#...#.....................................................#
#.###################...#######################################################
#.#...............#...#.#.....................................................#
#.#.#############.#...#.#.#############.#######################################
#.#.#...........#.#...#.#.#...........#.#.....................................#
#.#.#.#########.#.#...#.#.#.#########.#.#.#####################################
#.#.#.#.......#.#.#####.#.#.#.......#.#.#.#...........#.......................#
#.#.#.#.#####.#.#.......#.#.#.#####.#.#.#.#.#########.#.#######################
#...#...#...#.#.........#...#...#...#...#...#.......#.#...#...................#
#######.#.###.###########.#####.###.#####.###########.###.###################
#.......#.#...#...........#.....#...#...#.#...........#...#.................F.#
#########.#.###################.#####.###.#.###########.###################.###
#.........#.#.................#.#.....#...#.#.........#...#.................#.#
###########.###################.#######.###.#.#########.###.#################.#
#...........#...................#.......#...#.#.........#...#...............#.#
#############.###########################.###.#.#########.###################.#
#.............#...........................#...#.#.............................#
###############.###########################.###.###############################
#...............#...........................#.................................#
#################.#############################################################
#.............................................................................#
################################################################################
Generation complete.
Legend: '#'=Wall, '.'=Floor, 'S'=Start, 'F'=Finish