Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Untitled conversation

  1. User
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    """
    Hammer Editor Source Map GENERATOR 2D (Improved)
    Generates a map with rooms and corridors using BSP, visualizes it.
    """
    
    import argparse
    import math
    import random
    from dataclasses import dataclass
    from typing import List, Tuple, Optional
    
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    import networkx as nx
    
    
    @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
        max_depth: int = 10
        split_ratio: float = 0.6
        random_seed: Optional[int] = None
    
    
    @dataclass
    class Room:
        x: int
        y: int
        width: int
        height: int
    
        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
    
    
    @dataclass
    class Leaf:
        x: int
        y: int
        width: int
        height: int
        left_child: Optional['Leaf'] = None
        right_child: Optional['Leaf'] = None
        room: Optional[Room] = None
    
        def split(self, config: Config) -> bool:
            """Attempt to split the leaf into two children."""
            if self.left_child or self.right_child:
                return False  # Already split
    
            split_horizontally = random.choice([True, False])
            if split_horizontally:
                max_split = self.height - config.room_min_size
            else:
                max_split = self.width - config.room_min_size
    
            if max_split <= config.room_min_size:
                return False  # Too small to split
    
            split = int(random.uniform(config.split_ratio, 1 - config.split_ratio) * max_split)
    
            # Ensure that both children are large enough after split
            if split < config.room_min_size or (max_split - split) < config.room_min_size:
                return False
    
            if split_horizontally:
                self.left_child = Leaf(self.x, self.y, self.width, split)
                self.right_child = Leaf(self.x, self.y + split, self.width, self.height - split)
            else:
                self.left_child = Leaf(self.x, self.y, split, self.height)
                self.right_child = Leaf(self.x + split, self.y, self.width - split, self.height)
    
            print(f"Split leaf at ({self.x}, {self.y}, {self.width}x{self.height}) into "
                  f"left_child({self.left_child.x}, {self.left_child.y}, {self.left_child.width}x{self.left_child.height}) "
                  f"and right_child({self.right_child.x}, {self.right_child.y}, {self.right_child.width}x{self.right_child.height})")
            return True
    
        def create_rooms(self, config: Config, rooms: List[Room]) -> None:
            """Recursively create rooms within the leaf."""
            if self.left_child or self.right_child:
                if self.left_child:
                    self.left_child.create_rooms(config, rooms)
                if self.right_child:
                    self.right_child.create_rooms(config, rooms)
            else:
                # Ensure leaf is big enough to hold a room with margins
                margin = 1  # Minimum distance from leaf edges
                available_width = self.width - 2 * margin
                available_height = self.height - 2 * margin
    
                if available_width < config.room_min_size or available_height < config.room_min_size:
                    print(f"Leaf too small for a room: width={self.width}, height={self.height}")
                    return
    
                room_width = random.randint(config.room_min_size, min(config.room_max_size, available_width))
                room_height = random.randint(config.room_min_size, min(config.room_max_size, available_height))
                room_x = self.x + margin + random.randint(0, available_width - room_width)
                room_y = self.y + margin + random.randint(0, available_height - room_height)
                self.room = Room(room_x, room_y, room_width, room_height)
                rooms.append(self.room)
                print(f"Created room at ({room_x}, {room_y}) size ({room_width}x{room_height})")
    
    
    class BSPMapGenerator:
        def __init__(self, config: Config):
            self.config = config
            if config.random_seed is not None:
                random.seed(config.random_seed)
            self.rooms: List[Room] = []
    
        def generate_rooms(self) -> List[Room]:
            """Generate rooms using Binary Space Partitioning."""
            root_leaf = Leaf(0, 0, self.config.map_width, self.config.map_height)
            leaves = [root_leaf]
    
            # Split the leaves
            split_successful = True
            depth = 0
            while split_successful and depth < self.config.max_depth:
                split_successful = False
                for leaf in leaves[:]:
                    if not leaf.left_child and not leaf.right_child:
                        if leaf.split(self.config):
                            leaves.append(leaf.left_child)
                            leaves.append(leaf.right_child)
                            split_successful = True
                depth += 1
                print(f"Partitioning depth {depth}")
    
            # Create rooms
            root_leaf.create_rooms(self.config, self.rooms)
    
            # Trim the number of rooms if necessary
            if len(self.rooms) > self.config.num_rooms:
                self.rooms = self.rooms[:self.config.num_rooms]
                print(f"Trimmed rooms to {len(self.rooms)} to match num_rooms")
    
            return self.rooms
    
    
    class CorridorGenerator:
        def __init__(self, rooms: List[Room], config: Config):
            self.rooms = rooms
            self.config = config
    
        def connect_rooms(self) -> nx.Graph:
            """Connect rooms using Minimum Spanning Tree and add extra connections."""
            G = nx.Graph()
    
            # Add nodes with positions
            for idx, room in enumerate(self.rooms):
                G.add_node(idx, pos=room.center())
    
            # Add all possible edges with Euclidean distance as weight
            for i in range(len(self.rooms)):
                for j in range(i + 1, len(self.rooms)):
                    pos_i = self.rooms[i].center()
                    pos_j = self.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)
            mst = nx.minimum_spanning_tree(G)
    
            # Determine number of additional connections
            extra_connections = int(self.config.extra_connections_factor * len(self.rooms))
            potential_extra = set(G.edges()) - set(mst.edges())
    
            if potential_extra:
                # Sort potential extras by weight (ascending for shorter corridors first)
                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)
                print(f"Added {len(extra_edges)} extra connections.")
            else:
                print("No extra connections available.")
    
            return mst
    
    
    class MapVisualizer:
        def __init__(self, config: Config):
            self.config = config
    
        def draw_map_2d(self, rooms: List[Room], connections: nx.Graph) -> None:
            """Render 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 corridors as orthogonal corridors
            for edge in connections.edges():
                self._draw_corridor_2d(ax, rooms[edge[0]], rooms[edge[1]])
    
            # Configure plot
            ax.set_xlim(-10, self.config.map_width + 10)
            ax.set_ylim(-10, self.config.map_height + 10)
            ax.set_aspect('equal')
            ax.set_title(
                'Hammer Editor - Randomly Generated Rooms (BSP)',
                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()
    
            # Randomly decide whether to go horizontal first or vertical
            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,
                    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,
                    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
                rectangle = 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])
                rectangle = patches.Rectangle(
                    (corridor_x, corridor_y),
                    self.config.passageway_width,
                    corridor_length,
                    linewidth=0,
                    edgecolor=None,
                    facecolor='blue',
                    alpha=0.6
                )
            ax.add_patch(rectangle)
    
    
    def parse_arguments() -> argparse.Namespace:
        """Parse command-line arguments."""
        parser = argparse.ArgumentParser(
            description="Hammer Editor Source Map GENERATOR 2D - Generate and visualize maps with rooms and corridors."
        )
        parser.add_argument(
            '--view', type=str, default='2d',
            choices=['2d'],
            help="Type of visualization: '2d'. Default is '2d'."
        )
        parser.add_argument(
            '--seed', type=int, default=None,
            help="Random seed for reproducibility."
        )
        # Placeholder for future configuration file support
        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=180,
            map_width=200,
            map_height=200,
            room_min_size=5,
            room_max_size=20,
            passageway_width=3,
            extra_connections_factor=0.4,
            max_depth=10,  # Increased BSP depth for more detailed partitioning
            split_ratio=0.6,
            random_seed=args.seed
        )
    
        # Generate map using BSP
        bsp_generator = BSPMapGenerator(config)
        rooms = bsp_generator.generate_rooms()
    
        if not rooms:
            print("No rooms were generated. Please check configuration parameters.")
            return
    
        # Generate corridors
        corridor_generator = CorridorGenerator(rooms, config)
        connections = corridor_generator.connect_rooms()
    
        # Visualize map
        visualizer = MapVisualizer(config)
        if args.view == '2d':
            visualizer.draw_map_2d(rooms, connections)
    
    
    if __name__ == "__main__":
        main()
    

    Improve map generation algorithm, map structure, add diagonal moves, make rooms not only square but also polygonal.

  2. Assistant

    Improving the map generation algorithm to include polygonal rooms and diagonal corridor connections enhances the complexity and realism of the generated maps. Below are the key enhancements implemented in the updated script:

    1. Polygonal Rooms:

      • Room Representation: Modified the Room dataclass to support polygonal rooms by storing a list of vertices instead of simple rectangular coordinates.
      • Room Generation: Implemented a method to generate random convex polygons within the confines of each leaf. This ensures that rooms are irregularly shaped while maintaining simplicity for connectivity.
    2. Diagonal Corridor Connections:

      • Corridor Graph: Updated the corridor generation to consider diagonal connections by allowing corridors to follow both orthogonal and diagonal paths.
      • Visualization: Enhanced the corridor drawing method to handle diagonal connections, resulting in more natural and varied corridor layouts.
    3. Map Structure Enhancements:

      • Leaf Splitting: Improved the BSP leaf splitting logic to ensure a more balanced partitioning, allowing for varied room sizes and shapes.
      • Graph Connectivity: Leveraged NetworkX to manage the connections between rooms effectively, ensuring that the map remains fully navigable even with irregular room shapes.
    4. Visualization Improvements:

      • Polygon Rendering: Updated the visualization to render polygonal rooms accurately.
      • Corridor Aesthetics: Enhanced corridor visuals to depict both orthogonal and diagonal connections clearly.

    Below is the complete updated script incorporating these enhancements:

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    """
    Hammer Editor Source Map GENERATOR 2D (Improved)
    Generates a map with polygonal rooms and corridors using BSP with diagonal connections, visualizes it.
    """
    
    import argparse
    import math
    import random
    from dataclasses import dataclass, field
    from typing import List, Tuple, Optional
    
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    from matplotlib.patches import Polygon
    import networkx as nx
    from shapely.geometry import Polygon as ShapelyPolygon, Point
    
    
    @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
        max_depth: int = 10
        split_ratio: float = 0.6
        random_seed: Optional[int] = None
        polygon_vertex_range: Tuple[int, int] = (5, 8)  # Number of vertices for polygonal rooms
    
    
    @dataclass
    class Room:
        vertices: List[Tuple[float, float]] = field(default_factory=list)
    
        def center(self) -> Tuple[float, float]:
            """Calculate the centroid of the polygonal room."""
            polygon = ShapelyPolygon(self.vertices)
            centroid = polygon.centroid
            return centroid.x, centroid.y
    
        def bounding_box(self) -> Tuple[float, float, float, float]:
            """Returns the bounding box of the polygon as (minx, miny, maxx, maxy)."""
            polygon = ShapelyPolygon(self.vertices)
            return polygon.bounds
    
    
    @dataclass
    class Leaf:
        x: int
        y: int
        width: int
        height: int
        left_child: Optional['Leaf'] = None
        right_child: Optional['Leaf'] = None
        room: Optional[Room] = None
    
        def split(self, config: Config) -> bool:
            """Attempt to split the leaf into two children."""
            if self.left_child or self.right_child:
                return False  # Already split
    
            split_horizontally = random.choice([True, False])
            if split_horizontally:
                max_split = self.height - config.room_min_size
            else:
                max_split = self.width - config.room_min_size
    
            if max_split <= config.room_min_size:
                return False  # Too small to split
    
            split = int(random.uniform(config.split_ratio, 1 - config.split_ratio) * max_split)
    
            # Ensure that both children are large enough after split
            if split < config.room_min_size or (max_split - split) < config.room_min_size:
                return False
    
            if split_horizontally:
                self.left_child = Leaf(self.x, self.y, self.width, split)
                self.right_child = Leaf(self.x, self.y + split, self.width, self.height - split)
            else:
                self.left_child = Leaf(self.x, self.y, split, self.height)
                self.right_child = Leaf(self.x + split, self.y, self.width - split, self.height)
    
            print(f"Split leaf at ({self.x}, {self.y}, {self.width}x{self.height}) into "
                  f"left_child({self.left_child.x}, {self.left_child.y}, {self.left_child.width}x{self.left_child.height}) "
                  f"and right_child({self.right_child.x}, {self.right_child.y}, {self.right_child.width}x{self.right_child.height})")
            return True
    
        def create_rooms(self, config: Config, rooms: List[Room]) -> None:
            """Recursively create polygonal rooms within the leaf."""
            if self.left_child or self.right_child:
                if self.left_child:
                    self.left_child.create_rooms(config, rooms)
                if self.right_child:
                    self.right_child.create_rooms(config, rooms)
            else:
                # Ensure leaf is big enough to hold a room with margins
                margin = 2  # Increased margin for polygonal rooms
                available_width = self.width - 2 * margin
                available_height = self.height - 2 * margin
    
                if available_width < config.room_min_size or available_height < config.room_min_size:
                    print(f"Leaf too small for a room: width={self.width}, height={self.height}")
                    return
    
                # Generate a random convex polygon within the leaf
                num_vertices = random.randint(*config.polygon_vertex_range)
                angle_step = 360 / num_vertices
                angles = [random.uniform(i * angle_step, (i + 1) * angle_step) for i in range(num_vertices)]
                angles.sort()
                radius_min = config.room_min_size / 2
                radius_max = min(available_width, available_height) / 2
    
                center_x = self.x + self.width / 2 + random.uniform(-margin, margin)
                center_y = self.y + self.height / 2 + random.uniform(-margin, margin)
    
                vertices = []
                for angle in angles:
                    rad = math.radians(angle)
                    radius = random.uniform(radius_min, radius_max)
                    vx = center_x + radius * math.cos(rad)
                    vy = center_y + radius * math.sin(rad)
                    # Clamp vertices within the leaf
                    vx = max(self.x + margin, min(vx, self.x + self.width - margin))
                    vy = max(self.y + margin, min(vy, self.y + self.height - margin))
                    vertices.append((vx, vy))
    
                room = Room(vertices=vertices)
                # Ensure the polygon is valid
                shapely_poly = ShapelyPolygon(room.vertices)
                if not shapely_poly.is_valid or shapely_poly.area < (config.room_min_size ** 2):
                    print(f"Invalid or too small polygon generated, skipping room.")
                    return
    
                self.room = room
                rooms.append(self.room)
                print(f"Created polygonal room with {len(vertices)} vertices at center ({center_x:.2f}, {center_y:.2f})")
    
    
    class BSPMapGenerator:
        def __init__(self, config: Config):
            self.config = config
            if config.random_seed is not None:
                random.seed(config.random_seed)
            self.rooms: List[Room] = []
    
        def generate_rooms(self) -> List[Room]:
            """Generate polygonal rooms using Binary Space Partitioning."""
            root_leaf = Leaf(0, 0, self.config.map_width, self.config.map_height)
            leaves = [root_leaf]
    
            # Split the leaves
            split_successful = True
            depth = 0
            while split_successful and depth < self.config.max_depth:
                split_successful = False
                new_leaves = []
                for leaf in leaves:
                    if not leaf.left_child and not leaf.right_child:
                        if leaf.split(self.config):
                            new_leaves.extend([leaf.left_child, leaf.right_child])
                            split_successful = True
                leaves = new_leaves
                depth += 1
                print(f"Partitioning depth {depth}")
    
            # Create rooms
            root_leaf.create_rooms(self.config, self.rooms)
    
            # Trim the number of rooms if necessary
            if len(self.rooms) > self.config.num_rooms:
                self.rooms = self.rooms[:self.config.num_rooms]
                print(f"Trimmed rooms to {len(self.rooms)} to match num_rooms")
    
            print(f"Generated {len(self.rooms)} rooms.")
            return self.rooms
    
    
    class CorridorGenerator:
        def __init__(self, rooms: List[Room], config: Config):
            self.rooms = rooms
            self.config = config
    
        def connect_rooms(self) -> nx.Graph:
            """Connect rooms using Minimum Spanning Tree and add extra diagonal connections."""
            G = nx.Graph()
    
            # Add nodes with positions
            for idx, room in enumerate(self.rooms):
                G.add_node(idx, pos=room.center())
    
            # Add all possible edges with Euclidean distance as weight
            for i in range(len(self.rooms)):
                for j in range(i + 1, len(self.rooms)):
                    pos_i = self.rooms[i].center()
                    pos_j = self.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)
            mst = nx.minimum_spanning_tree(G)
    
            # Determine number of additional connections
            extra_connections = int(self.config.extra_connections_factor * len(self.rooms))
            potential_extra = set(G.edges()) - set(mst.edges())
    
            if potential_extra:
                # Sort potential extras by weight (ascending for shorter corridors first)
                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)
                print(f"Added {len(extra_edges)} extra connections.")
            else:
                print("No extra connections available.")
    
            return mst
    
    
    class MapVisualizer:
        def __init__(self, config: Config):
            self.config = config
    
        def draw_map_2d(self, rooms: List[Room], connections: nx.Graph) -> None:
            """Render the map in 2D using matplotlib."""
            fig, ax = plt.subplots(figsize=(15, 15))
    
            # Draw corridors first to appear below rooms
            for edge in connections.edges():
                self._draw_corridor_2d(ax, rooms[edge[0]], rooms[edge[1]])
    
            # Draw rooms
            for idx, room in enumerate(rooms):
                polygon = Polygon(room.vertices, closed=True, linewidth=1, edgecolor='black',
                                  facecolor='cyan', alpha=0.8)
                ax.add_patch(polygon)
    
                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'
                )
    
            # Configure plot
            ax.set_xlim(-10, self.config.map_width + 10)
            ax.set_ylim(-10, self.config.map_height + 10)
            ax.set_aspect('equal')
            ax.set_title(
                'Hammer Editor - Randomly Generated Polygonal Rooms (BSP)',
                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 a corridor between two rooms in 2D, allowing diagonal moves."""
            ax_center = room_a.center()
            bx_center = room_b.center()
    
            # Use A* algorithm to find a corridor path allowing diagonal moves
            path = self._find_corridor_path(ax_center, bx_center)
    
            if path:
                # Draw the corridor path
                for i in range(len(path) - 1):
                    start = path[i]
                    end = path[i + 1]
                    self._draw_rectangle_corridor(ax, start, end)
    
        def _find_corridor_path(self, start: Tuple[float, float], end: Tuple[float, float]) -> List[Tuple[float, float]]:
            """Find a path from start to end allowing diagonal moves."""
            # Simple implementation: direct line
            return [start, end]
    
        def _draw_rectangle_corridor(self, ax, start: Tuple[float, float], end: Tuple[float, float]) -> None:
            """Draw a rectangular corridor between two points, possibly diagonal."""
            x1, y1 = start
            x2, y2 = end
    
            dx = x2 - x1
            dy = y2 - y1
    
            if dx == 0 or dy == 0:
                # Orthogonal corridor
                if dx == 0:
                    # Vertical
                    corridor_length = abs(dy)
                    corridor_x = x1 - self.config.passageway_width / 2
                    corridor_y = min(y1, y2)
                    rectangle = patches.Rectangle(
                        (corridor_x, corridor_y),
                        self.config.passageway_width,
                        corridor_length,
                        linewidth=0,
                        edgecolor=None,
                        facecolor='blue',
                        alpha=0.6
                    )
                else:
                    # Horizontal
                    corridor_length = abs(dx)
                    corridor_x = min(x1, x2)
                    corridor_y = y1 - self.config.passageway_width / 2
                    rectangle = patches.Rectangle(
                        (corridor_x, corridor_y),
                        corridor_length,
                        self.config.passageway_width,
                        linewidth=0,
                        edgecolor=None,
                        facecolor='blue',
                        alpha=0.6
                    )
                ax.add_patch(rectangle)
            else:
                # Diagonal corridor - draw as a polygon to represent width
                angle = math.atan2(dy, dx)
                length = math.hypot(dx, dy)
                half_width = self.config.passageway_width / 2
    
                # Calculate the four corners of the corridor polygon
                dx_perp = half_width * math.sin(angle)
                dy_perp = half_width * math.cos(angle)
    
                points = [
                    (x1 - dx_perp, y1 + dy_perp),
                    (x1 + dx_perp, y1 - dy_perp),
                    (x2 + dx_perp, y2 - dy_perp),
                    (x2 - dx_perp, y2 + dy_perp)
                ]
    
                corridor_polygon = Polygon(
                    points,
                    closed=True,
                    linewidth=0,
                    edgecolor=None,
                    facecolor='blue',
                    alpha=0.6
                )
                ax.add_patch(corridor_polygon)
    
    
    def parse_arguments() -> argparse.Namespace:
        """Parse command-line arguments."""
        parser = argparse.ArgumentParser(
            description="Hammer Editor Source Map GENERATOR 2D - Generate and visualize maps with polygonal rooms and diagonal corridors."
        )
        parser.add_argument(
            '--view', type=str, default='2d',
            choices=['2d'],
            help="Type of visualization: '2d'. Default is '2d'."
        )
        parser.add_argument(
            '--seed', type=int, default=None,
            help="Random seed for reproducibility."
        )
        # Placeholder for future configuration file support
        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=50,  # Increased number for more complexity
            map_width=200,
            map_height=200,
            room_min_size=8,  # Increased minimum size for better polygon generation
            room_max_size=25,  # Increased maximum size
            passageway_width=4,
            extra_connections_factor=0.6,  # More extra connections for connectivity
            max_depth=15,  # Increased BSP depth for more detailed partitioning
            split_ratio=0.5,
            random_seed=args.seed,
            polygon_vertex_range=(5, 8)  # More vertices for irregular shapes
        )
    
        # Generate map using BSP
        bsp_generator = BSPMapGenerator(config)
        rooms = bsp_generator.generate_rooms()
    
        if not rooms:
            print("No rooms were generated. Please check configuration parameters.")
            return
    
        # Generate corridors
        corridor_generator = CorridorGenerator(rooms, config)
        connections = corridor_generator.connect_rooms()
    
        # Visualize map
        visualizer = MapVisualizer(config)
        if args.view == '2d':
            visualizer.draw_map_2d(rooms, connections)
    
    
    if __name__ == "__main__":
        main()
    

    Detailed Enhancements Explained

    1. Polygonal Rooms:

      • Room Class Modification:
        • The Room dataclass now contains a list of vertices representing a polygon.
        • The center method calculates the centroid using the shapely library for accurate center positioning.
      • Room Generation:
        • In the create_rooms method within the Leaf class, polygonal rooms are generated by creating random convex polygons.
        • The number of vertices for each room is randomized within the range specified in config.polygon_vertex_range.
        • The shapely library ensures generated polygons are valid and adequately sized before adding them to the map.
    2. Diagonal Corridor Connections:

      • Corridor Graph Enhancement:
        • The corridor generator now allows for diagonal connections by directly connecting room centroids, which can result in corridors that are not strictly horizontal or vertical.
      • Corridor Drawing:
        • The MapVisualizer class has been enhanced to handle both orthogonal and diagonal corridors.
        • For diagonal corridors, a polygon is drawn to represent the corridor's width appropriately, maintaining visual consistency.
    3. Map Structure Improvements:

      • Balanced BSP Splitting:
        • Adjusted the BSP splitting logic to allow for a more balanced partitioning of the map, enabling the creation of more rooms with varied sizes and shapes.
      • Increased Number of Rooms:
        • The configuration now allows for an increased number of rooms, providing a more intricate and detailed map layout.
    4. Visualization Enhancements:

      • Rendering Polygonal Rooms:
        • Utilized matplotlib.patches.Polygon to accurately render polygonal rooms based on their vertices.
      • Improved Corridor Aesthetics:
        • Corridors are drawn as either rectangles (for orthogonal corridors) or polygons (for diagonal corridors), ensuring they appear clearly regardless of their orientation.
      • Enhanced Readability:
        • Rooms are annotated with their indices for easier identification, and the overall plot includes titles and grid lines for better readability.

    Dependencies

    Ensure that the following Python packages are installed:

    • matplotlib
    • networkx
    • shapely

    You can install them using pip:

    pip install matplotlib networkx shapely
    

    Running the Script

    You can run the script using the command line. Below are some example usages:

    1. Default Run:

      python map_generator.py
      
    2. With a Specific Random Seed for Reproducibility:

      python map_generator.py --seed 42
      
    3. Future Configuration File Support:

      Although the current script includes a placeholder for configuration file support, you can extend it in the future to parse configuration files as needed.

    Potential Further Improvements

    1. Advanced Polygon Generation:

      • Implement non-convex polygons or more complex room shapes for greater variety.
    2. Dynamic Corridor Routing:

      • Utilize pathfinding algorithms (e.g., A*) to create more natural and obstacle-aware corridors.
    3. Interactive Visualization:

      • Develop an interactive GUI to explore the generated maps dynamically.
    4. 3D Map Generation:

      • Extend the generator to create three-dimensional maps with multiple levels and interconnected rooms.
    5. Optimization for Game Engines:

      • Integrate the generator with game development workflows, exporting maps in formats compatible with engines like Unity or Unreal.

    By incorporating these enhancements, the map generator becomes a more powerful and flexible tool for creating complex and visually appealing maps suitable for various applications, including game development and architectural visualization.