Write python code that generates rooms in random order and connects them with passageways
- User
Write python code that generates rooms in random order and connects them with passageways
- Assistant
Write python code that generates rooms in random order and connects them with passageways
Certainly! Below is a Python script that generates a series of rooms placed randomly within a defined space and connects them with passageways (corridors). The script ensures that all rooms are accessible by creating a minimum spanning tree (MST) of the room connections and optionally adds some extra connections to make the layout more interesting.
matplotlib to visualize the rooms and their connecting passageways.matplotlib: For visualization.numpy: For numerical operations.random: For randomness in room generation.networkx: For handling graph operations like MST.You can install the required libraries using pip if you don't have them already:
pip install matplotlib numpy networkx
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import random
import math
import networkx as nx
# Configuration
NUM_ROOMS = 10
MAP_WIDTH = 100
MAP_HEIGHT = 100
ROOM_MIN_SIZE = 5
ROOM_MAX_SIZE = 15
PASSAGEWAY_WIDTH = 1
class Room:
def __init__(self, x, y, width, height):
self.x = x # Bottom-left corner x
self.y = y # Bottom-left corner y
self.width = width
self.height = height
def center(self):
center_x = self.x + self.width / 2
center_y = self.y + self.height / 2
return (center_x, center_y)
def intersects(self, other):
return (self.x < other.x + other.width and
self.x + self.width > other.x and
self.y < other.y + other.height and
self.y + self.height > other.y)
def generate_rooms():
rooms = []
attempts = 0
max_attempts = NUM_ROOMS * 5 # To prevent infinite loops
while len(rooms) < NUM_ROOMS and attempts < max_attempts:
width = random.randint(ROOM_MIN_SIZE, ROOM_MAX_SIZE)
height = random.randint(ROOM_MIN_SIZE, ROOM_MAX_SIZE)
x = random.randint(0, MAP_WIDTH - width)
y = random.randint(0, MAP_HEIGHT - height)
new_room = Room(x, y, width, height)
# Check for overlap
if any(new_room.intersects(other) for other in rooms):
attempts += 1
continue
rooms.append(new_room)
if len(rooms) < NUM_ROOMS:
print(f"Could only place {len(rooms)} rooms after {attempts} attempts.")
return rooms
def connect_rooms(rooms):
"""Connect rooms using a Minimum Spanning Tree to ensure all rooms are connected."""
G = nx.Graph()
for i, room in enumerate(rooms):
G.add_node(i, pos=room.center())
# Add all possible edges with Euclidean distance as weight
for i in range(len(rooms)):
for j in range(i + 1, len(rooms)):
pos_i = rooms[i].center()
pos_j = rooms[j].center()
distance = math.hypot(pos_i[0] - pos_j[0], pos_i[1] - pos_j[1])
G.add_edge(i, j, weight=distance)
# Compute MST
mst = nx.minimum_spanning_tree(G)
# Optionally add some extra edges for more connections
extra_connections = random.randint(0, len(rooms)//2)
potential_extra = set(G.edges()) - set(mst.edges())
extra_edges = random.sample(potential_extra, min(extra_connections, len(potential_extra)))
for edge in extra_edges:
mst.add_edge(*edge, weight=G.edges[edge]['weight'])
return mst
def draw_map(rooms, connections):
fig, ax = plt.subplots(figsize=(10, 10))
# Draw rooms
for room in rooms:
rect = patches.Rectangle((room.x, room.y), room.width, room.height, linewidth=1, edgecolor='black', facecolor='cyan', alpha=0.5)
ax.add_patch(rect)
# Optionally, draw room centers
cx, cy = room.center()
ax.plot(cx, cy, 'ro') # red dot at center
# Draw passageways
for edge in connections.edges():
room_a = rooms[edge[0]]
room_b = rooms[edge[1]]
ax.plot([room_a.center()[0], room_b.center()[0]],
[room_a.center()[1], room_b.center()[1]],
'gray', linewidth=PASSAGEWAY_WIDTH)
ax.set_xlim(0, MAP_WIDTH)
ax.set_ylim(0, MAP_HEIGHT)
ax.set_aspect('equal')
plt.title('Randomly Generated Rooms with Passageways')
plt.show()
def main():
rooms = generate_rooms()
connections = connect_rooms(rooms)
draw_map(rooms, connections)
if __name__ == "__main__":
main()
Room Class: Defines a Room with position (x, y) and size (width, height). It includes methods to compute the center of the room and to check for intersection with another room.
generate_rooms Function:
connect_rooms Function:
draw_map Function:
matplotlib to draw each room as a rectangle.main Function:
NUM_ROOMS variable to create more or fewer rooms.MAP_WIDTH and MAP_HEIGHT to change the overall size of the map.ROOM_MIN_SIZE and ROOM_MAX_SIZE to vary room dimensions.PASSAGEWAY_WIDTH for thicker or thinner passage lines.extra_connections variable determines how many additional random connections are added beyond the MST.Ensure that all dependencies are installed. Save the script to a .py file and run it using Python:
python generate_rooms.py
Upon execution, a window will display the generated map with rooms and their connecting passageways.
The output will be a visual map showing multiple cyan-colored rectangles representing rooms connected by gray lines indicating passageways. Each room's center is marked with a red dot.
[image: Sample Dungeon Layout] open (Replace with actual image if needed)
Feel free to enhance the script further by adding features such as different room shapes, varying passageway styles, or interactive elements.
Not yet included in a published release.