Certainly! Below is the refactored, optimized, and well-structured version of your Python script. Following the code, you'll find a detailed list of the changes and improvements made.
import argparse
import math
import random
from dataclasses import dataclass
from typing import List, Tuple
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import networkx as nx
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
@dataclass
class Config:
num_rooms: int = 20
map_width: int = 200
map_height: int = 200
room_min_size: int = 5
room_max_size: int = 20
passageway_width: int = 3
extra_connections_factor: float = 0.4
room_height: int = 10
corridor_height: int = 3
max_attempts_multiplier: int = 10
random_seed: int = None # Set to an integer for reproducible results
@dataclass
class Room:
x: int
y: int
width: int
height: int
depth: int = 10 # Default room height
def center(self) -> Tuple[float, float]:
"""Calculate the center coordinates of the room."""
center_x = self.x + self.width / 2
center_y = self.y + self.height / 2
return center_x, center_y
def intersects(self, other: 'Room') -> bool:
"""Check if this room intersects with another room."""
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
)
class MapGenerator:
def __init__(self, config: Config):
self.config = config
if config.random_seed is not None:
random.seed(config.random_seed)
def generate_rooms(self) -> List[Room]:
"""Generate non-overlapping rooms within the map boundaries."""
rooms = []
max_attempts = self.config.num_rooms * self.config.max_attempts_multiplier
attempts = 0
while len(rooms) < self.config.num_rooms and attempts < max_attempts:
width = random.randint(self.config.room_min_size, self.config.room_max_size)
height = random.randint(self.config.room_min_size, self.config.room_max_size)
x = random.randint(0, self.config.map_width - width)
y = random.randint(0, self.config.map_height - height)
new_room = Room(x, y, width, height, self.config.room_height)
if not any(new_room.intersects(other) for other in rooms):
rooms.append(new_room)
attempts += 1
if len(rooms) < self.config.num_rooms:
print(
f"Warning: Only {len(rooms)} out of {self.config.num_rooms} rooms were placed "
f"after {attempts} attempts."
)
return rooms
def connect_rooms(self, rooms: List[Room]) -> nx.Graph:
"""Connect rooms using MST and add extra connections based on the configuration."""
G = nx.Graph()
# Add nodes with positions
for idx, room in enumerate(rooms):
G.add_node(idx, 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 Minimum Spanning Tree
mst = nx.minimum_spanning_tree(G)
# Determine number of extra connections
extra_connections = int(self.config.extra_connections_factor * len(rooms))
potential_extra = set(G.edges()) - set(mst.edges())
if potential_extra:
sorted_extra = sorted(
potential_extra,
key=lambda edge: G.edges[edge]['weight']
)
num_extra = min(extra_connections, len(sorted_extra))
extra_edges = sorted_extra[:num_extra]
mst.add_edges_from(extra_edges)
return mst
class MapVisualizer:
def __init__(self, config: Config):
self.config = config
def draw_map_2d(self, rooms: List[Room], connections: nx.Graph) -> None:
"""Draw the map in 2D using matplotlib."""
fig, ax = plt.subplots(figsize=(15, 15))
# Draw rooms
for idx, room in enumerate(rooms):
rect = patches.Rectangle(
(room.x, room.y),
room.width,
room.height,
linewidth=1,
edgecolor='black',
facecolor='cyan',
alpha=0.8
)
ax.add_patch(rect)
cx, cy = room.center()
ax.plot(cx, cy, 'ro') # Red dot at center
ax.text(
cx, cy, str(idx + 1),
color='white', ha='center', va='center',
fontsize=8, fontweight='bold'
)
# Draw passageways as orthogonal corridors
for edge in connections.edges():
self._draw_corridor_2d(ax, rooms[edge[0]], rooms[edge[1]])
# Configure plot
ax.set_xlim(0, self.config.map_width)
ax.set_ylim(0, self.config.map_height)
ax.set_aspect('equal')
ax.set_title('Randomly Generated Rooms with Orthogonal Corridors (2D)', fontsize=16)
ax.set_xlabel('X', fontsize=12)
ax.set_ylabel('Y', fontsize=12)
ax.grid(True, which='both', linestyle='--', linewidth=0.5, alpha=0.7)
plt.show()
def _draw_corridor_2d(self, ax, room_a: Room, room_b: Room) -> None:
"""Draw an orthogonal corridor between two rooms in 2D."""
ax_center = room_a.center()
bx_center = room_b.center()
horizontal_first = random.choice([True, False])
if horizontal_first:
intermediate_point = (bx_center[0], ax_center[1])
self._draw_rectangle_corridor(
ax,
start=(ax_center[0], ax_center[1]),
end=intermediate_point,
orientation='horizontal'
)
self._draw_rectangle_corridor(
ax,
start=intermediate_point,
end=bx_center,
orientation='vertical'
)
else:
intermediate_point = (ax_center[0], bx_center[1])
self._draw_rectangle_corridor(
ax,
start=(ax_center[0], ax_center[1]),
end=intermediate_point,
orientation='vertical'
)
self._draw_rectangle_corridor(
ax,
start=intermediate_point,
end=bx_center,
orientation='horizontal'
)
def _draw_rectangle_corridor(self, ax, start: Tuple[float, float], end: Tuple[float, float], orientation: str) -> None:
"""Helper method to draw a rectangular corridor."""
if orientation == 'horizontal':
corridor_length = abs(end[0] - start[0])
corridor_x = min(start[0], end[0])
corridor_y = start[1] - self.config.passageway_width / 2
rect = patches.Rectangle(
(corridor_x, corridor_y),
corridor_length,
self.config.passageway_width,
linewidth=0,
edgecolor=None,
facecolor='blue',
alpha=0.6
)
else:
corridor_length = abs(end[1] - start[1])
corridor_x = start[0] - self.config.passageway_width / 2
corridor_y = min(start[1], end[1])
rect = patches.Rectangle(
(corridor_x, corridor_y),
self.config.passageway_width,
corridor_length,
linewidth=0,
edgecolor=None,
facecolor='blue',
alpha=0.6
)
ax.add_patch(rect)
def draw_map_3d(self, rooms: List[Room], connections: nx.Graph) -> None:
"""Draw the map in 3D using matplotlib."""
fig = plt.figure(figsize=(15, 15))
ax = fig.add_subplot(111, projection='3d')
# Draw rooms
for idx, room in enumerate(rooms):
self._create_box(
ax,
x=room.x,
y=room.y,
z=0,
dx=room.width,
dy=room.height,
dz=room.depth,
color='cyan',
alpha=0.8
)
cx, cy = room.center()
ax.text(cx, cy, room.depth + 1, str(idx + 1),
color='white', ha='center', va='center',
fontsize=8, fontweight='bold')
# Draw corridors
for edge in connections.edges():
self._draw_corridor_3d(ax, rooms[edge[0]], rooms[edge[1]])
# Configure plot
ax.set_xlim(0, self.config.map_width)
ax.set_ylim(0, self.config.map_height)
ax.set_zlim(0, self.config.room_height + 5)
ax.set_xlabel('X', fontsize=12)
ax.set_ylabel('Y', fontsize=12)
ax.set_zlabel('Z (Height)', fontsize=12)
ax.set_title('Randomly Generated Rooms with Orthogonal Corridors (3D)', fontsize=16)
ax.view_init(elev=20, azim=30)
plt.show()
def _create_box(self, ax, x: float, y: float, z: float, dx: float, dy: float, dz: float,
color: str, alpha: float) -> None:
"""Create a 3D box (cuboid) and add it to the plot."""
vertices = [
[x, y, z],
[x + dx, y, z],
[x + dx, y + dy, z],
[x, y + dy, z],
[x, y, z + dz],
[x + dx, y, z + dz],
[x + dx, y + dy, z + dz],
[x, y + dy, z + dz]
]
faces = [
[vertices[0], vertices[1], vertices[2], vertices[3]], # Bottom
[vertices[4], vertices[5], vertices[6], vertices[7]], # Top
[vertices[0], vertices[1], vertices[5], vertices[4]], # Front
[vertices[2], vertices[3], vertices[7], vertices[6]], # Back
[vertices[1], vertices[2], vertices[6], vertices[5]], # Right
[vertices[4], vertices[7], vertices[3], vertices[0]] # Left
]
poly3d = Poly3DCollection(faces, facecolors=color, linewidths=1, edgecolors='black', alpha=alpha)
ax.add_collection3d(poly3d)
def _draw_corridor_3d(self, ax, room_a: Room, room_b: Room) -> None:
"""Draw an orthogonal corridor between two rooms in 3D."""
ax_center = room_a.center()
bx_center = room_b.center()
horizontal_first = random.choice([True, False])
if horizontal_first:
intermediate_point = (bx_center[0], ax_center[1])
self._create_corridor_box(ax, ax_center, intermediate_point, 'horizontal')
self._create_corridor_box(ax, intermediate_point, bx_center, 'vertical')
else:
intermediate_point = (ax_center[0], bx_center[1])
self._create_corridor_box(ax, ax_center, intermediate_point, 'vertical')
self._create_corridor_box(ax, intermediate_point, bx_center, 'horizontal')
def _create_corridor_box(self, ax, start: Tuple[float, float], end: Tuple[float, float],
orientation: str) -> None:
"""Helper method to create a 3D corridor box."""
z = 0 # Corridors start at ground level
dz = self.config.corridor_height
if orientation == 'horizontal':
corridor_length = abs(end[0] - start[0])
corridor_x = min(start[0], end[0])
corridor_y = start[1] - self.config.passageway_width / 2
dx, dy = corridor_length, self.config.passageway_width
else:
corridor_length = abs(end[1] - start[1])
corridor_x = start[0] - self.config.passageway_width / 2
corridor_y = min(start[1], end[1])
dx, dy = self.config.passageway_width, corridor_length
self._create_box(
ax,
x=corridor_x,
y=corridor_y,
z=z,
dx=dx,
dy=dy,
dz=dz,
color='blue',
alpha=0.6
)
def parse_arguments() -> argparse.Namespace:
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description="Generate and visualize maps with rooms and corridors."
)
parser.add_argument(
'--view', type=str, default='3d',
choices=['2d', '3d', 'both'],
help="Type of visualization: '2d', '3d', or 'both'. Default is '3d'."
)
parser.add_argument(
'--seed', type=int, default=None,
help="Random seed for reproducibility."
)
parser.add_argument(
'--config', type=str, default=None,
help="Path to a configuration file (optional)."
)
return parser.parse_args()
def main():
args = parse_arguments()
# Initialize configuration
config = Config(
num_rooms=20,
map_width=200,
map_height=200,
room_min_size=5,
room_max_size=20,
passageway_width=3,
extra_connections_factor=0.4,
room_height=10,
corridor_height=3,
random_seed=args.seed
)
# Generate map
generator = MapGenerator(config)
rooms = generator.generate_rooms()
connections = generator.connect_rooms(rooms)
# Visualize map
visualizer = MapVisualizer(config)
if args.view in ['2d', 'both']:
visualizer.draw_map_2d(rooms, connections)
if args.view in ['3d', 'both']:
visualizer.draw_map_3d(rooms, connections)
if __name__ == "__main__":
main()
List of Changes and Improvements
-
Configuration Management with @dataclass:
- Introduced a
Config dataclass to encapsulate all configuration parameters. This enhances code readability and makes it easier to manage and pass around configuration settings.
- Added an optional
random_seed parameter to allow for reproducible results.
-
Enhanced Room Representation:
- Converted the
Room class to a dataclass for better structure and readability.
- Provided type hints for clarity.
-
Map Generation Logic Encapsulated in MapGenerator Class:
- Created a
MapGenerator class to handle room generation and connection logic.
- This class now takes a
Config instance, making it flexible and configurable.
- Improved the room placement logic by moving the
attempts += 1 outside the conditional to ensure all attempts are counted, even if a room is successfully placed.
-
Room Connection Logic Optimized:
- Moved the connection logic into the
MapGenerator class.
- Simplified the extra connections addition by sorting potential extra edges based on weight and selecting the shortest ones.
- Ensured the extra connections do not create duplicate edges.
-
Visualization Encapsulated in MapVisualizer Class:
- Created a
MapVisualizer class to handle both 2D and 3D drawing functionalities.
- This separation of concerns makes the code more modular and easier to maintain.
- Refactored corridor drawing into helper methods (
_draw_corridor_2d, _create_corridor_box, and _draw_rectangle_corridor) to avoid code duplication between 2D and 3D visualizations.
-
Enhanced 3D Visualization:
- Improved the 3D drawing by creating a generic
_create_box method to draw both rooms and corridors.
- Ensured corridors have a consistent height and are properly connected between rooms.
-
Command-Line Argument Parsing Enhanced:
- Added a
--seed argument to allow users to set the random seed for reproducibility.
- Included a placeholder for a argument to accept configuration files in the future (currently not implemented).
These changes collectively enhance the code's efficiency, readability, maintainability, and usability, providing a more robust and flexible tool for generating and visualizing maps with rooms and corridors.