```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Hammer Editor Source Map GENERATOR 2D
Generates a map with rooms and corridors, visualizes it.
"""

import argparse
import math
import random
from dataclasses import dataclass
from typing import List, Tuple, Optional, Set

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_attempts_multiplier: int = 10
    # Seed for reproducible results
    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

    def intersects(self, other: 'Room') -> bool:
        """Check if this room intersects with another room."""
        return not (
            self.x + self.width <= other.x or
            self.x >= other.x + other.width or
            self.y + self.height <= other.y or
            self.y >= other.y + other.height
        )


class SpatialGrid:
    """Spatial grid for efficient room collision detection."""

    def __init__(self, map_width: int, map_height: int, cell_size: int):
        self.cell_size = cell_size
        self.cols = math.ceil(map_width / cell_size)
        self.rows = math.ceil(map_height / cell_size)
        self.grid = [[[] for _ in range(self.rows)] for _ in range(self.cols)]

    def _get_cells_for_room(self, room: Room) -> Set[Tuple[int, int]]:
        """Determine which grid cells the room occupies."""
        start_col = room.x // self.cell_size
        end_col = (room.x + room.width) // self.cell_size
        start_row = room.y // self.cell_size
        end_row = (room.y + room.height) // self.cell_size
        cells = set()
        for col in range(start_col, end_col + 1):
            for row in range(start_row, end_row + 1):
                if 0 <= col < self.cols and 0 <= row < self.rows:
                    cells.add((col, row))
        return cells

    def add_room(self, room: Room):
        """Add a room to the grid."""
        cells = self._get_cells_for_room(room)
        for col, row in cells:
            self.grid[col][row].append(room)

    def has_intersection(self, room: Room) -> bool:
        """Check if the room intersects with any existing rooms in relevant grid cells."""
        cells = self._get_cells_for_room(room)
        for col, row in cells:
            for existing_room in self.grid[col][row]:
                if room.intersects(existing_room):
                    return True
        return False


class MapGenerator:
    def __init__(self, config: Config):
        self.config = config
        if config.random_seed is not None:
            random.seed(config.random_seed)
        # Initialize spatial grid with cell size equal to the max room size
        self.spatial_grid = SpatialGrid(
            config.map_width,
            config.map_height,
            config.room_max_size
        )

    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)

            if not self.spatial_grid.has_intersection(new_room):
                rooms.append(new_room)
                self.spatial_grid.add_room(new_room)
                print(f"Placed room {len(rooms)} at ({x}, {y}) size ({width}x{height})")
            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 Minimum Spanning Tree and add extra connections."""
        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)
        mst = nx.minimum_spanning_tree(G)

        # Determine number of additional connections
        extra_connections = int(
            self.config.extra_connections_factor * len(rooms))
        potential_extra = set(G.edges()) - set(mst.edges())

        if potential_extra:
            # Sort potential extras by weight (can also shuffle for randomness)
            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',
            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=20,
        map_width=200,
        map_height=200,
        room_min_size=5,
        room_max_size=20,
        passageway_width=3,
        extra_connections_factor=0.4,
        max_attempts_multiplier=10,
        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 == '2d':
        visualizer.draw_map_2d(rooms, connections)


if __name__ == "__main__":
    main()
```
Улучши алгоритм генерации комнат и коридоров.
Улучши код, структурируй и оптимизируй код