Untitled conversation
- Userpython
- Assistant
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
@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
random_seed: int = None # Установите целое число для воспроизводимых результатов
@dataclass
class Room:
x: int
y: int
width: int
height: int
def center(self) -> Tuple[float, float]:
"""Вычислить координаты центра комнаты."""
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:
"""Проверить, пересекается ли эта комната с другой."""
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]:
"""Генерировать неперекрывающиеся комнаты внутри границ карты."""
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 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:
"""Соединить комнаты с использованием MST и добавить дополнительные соединения на основе конфигурации."""
G = nx.Graph()
# Добавить узлы с позициями
for idx, room in enumerate(rooms):
G.add_node(idx, pos=room.center())
# Добавить все возможные рёбра с евклидовым расстоянием как весом
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)
# Вычислить Минимальное Остовное Дерево (MST)
mst = nx.minimum_spanning_tree(G)
# Определить количество дополнительных соединений
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:
"""Отрисовать карту в 2D с использованием matplotlib."""
fig, ax = plt.subplots(figsize=(15, 15))
# Отрисовка комнат
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') # Красная точка в центре
ax.text(
cx, cy, str(idx + 1),
color='white', ha='center', va='center',
fontsize=8, fontweight='bold'
)
# Отрисовка коридоров как ортогональных коридоров
for edge in connections.edges():
self._draw_corridor_2d(ax, rooms[edge[0]], rooms[edge[1]])
# Настройка графика
ax.set_xlim(0, self.config.map_width)
ax.set_ylim(0, self.config.map_height)
ax.set_aspect('equal')
ax.set_title(
'Случайно сгенерированные комнаты с ортогональными коридорами (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:
"""Отрисовать ортогональный коридор между двумя комнатами в 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:
"""Вспомогательный метод для отрисовки прямоугольного коридора."""
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 parse_arguments() -> argparse.Namespace:
"""Анализировать аргументы командной строки."""
parser = argparse.ArgumentParser(
description="Генерация и визуализация карт с комнатами и коридорами."
)
parser.add_argument(
'--view', type=str, default='2d',
choices=['2d'],
help="Тип визуализации: '2d'. По умолчанию: '2d'."
)
parser.add_argument(
'--seed', type=int, default=None,
help="Случайное семя для воспроизводимости."
)
# Место для будущей поддержки файла конфигурации
parser.add_argument(
'--config', type=str, default=None,
help="Путь к файлу конфигурации (опционально)."
)
return parser.parse_args()
def main():
args = parse_arguments()
# Инициализация конфигурации
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
)
# Генерация карты
generator = MapGenerator(config)
rooms = generator.generate_rooms()
connections = generator.connect_rooms(rooms)
# Визуализация карты
visualizer = MapVisualizer(config)
if args.view in ['2d']:
visualizer.draw_map_2d(rooms, connections)
if __name__ == "__main__":
main()
Сделай чтобы показывало как генерируется карта. Тип как появляется первая комната, как соединяется все.
To visualize the step-by-step generation of the map—showing how each room is added and how connections (corridors) are established—you can enhance your existing code by integrating live updates into the visualization process. This can be achieved using matplotlib's interactive capabilities, such as plt.pause(), to update the plot dynamically as rooms are placed and corridors are connected.
Below is the modified version of your code with the necessary changes to achieve this:
Enable Interactive Mode in Matplotlib:
plt.ion() to turn on the interactive mode, which allows real-time updates to the plot.fig and ax) to update it incrementally.Modify the MapVisualizer Class:
MapVisualizer.plt.pause() to create a brief pause, allowing the plot to update visually.Update the MapGenerator Class:
MapVisualizer instance to the MapGenerator.Adjust the main Function:
MapVisualizer before generating rooms and connections.Here's the complete modified code with detailed comments explaining each change:
import argparse
import math
import random
import time
from dataclasses import dataclass
from typing import List, Tuple
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
random_seed: int = None # Set an integer for reproducible results
@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 (
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 MapVisualizer:
def __init__(self, config: Config):
self.config = config
plt.ion() # Turn on interactive mode
self.fig, self.ax = plt.subplots(figsize=(15, 15))
self.ax.set_xlim(0, self.config.map_width)
self.ax.set_ylim(0, self.config.map_height)
self.ax.set_aspect('equal')
self.ax.set_title(
'Map Generation Process (2D)', fontsize=16
)
self.ax.set_xlabel('X', fontsize=12)
self.ax.set_ylabel('Y', fontsize=12)
self.ax.grid(True, which='both', linestyle='--', linewidth=0.5, alpha=0.7)
self.fig.canvas.draw()
self.fig.canvas.flush_events()
def update_room(self, room: Room, idx: int):
"""Update the plot with a new room."""
rect = patches.Rectangle(
(room.x, room.y),
room.width,
room.height,
linewidth=1,
edgecolor='black',
facecolor='cyan',
alpha=0.8
)
self.ax.add_patch(rect)
cx, cy = room.center()
self.ax.plot(cx, cy, 'ro') # Red dot at center
self.ax.text(
cx, cy, str(idx + 1),
color='white', ha='center', va='center',
fontsize=8, fontweight='bold'
)
self.fig.canvas.draw()
self.fig.canvas.flush_events()
plt.pause(0.1) # Brief pause to visualize the addition
def update_corridor(self, room_a: Room, room_b: Room):
"""Update the plot with a new corridor."""
self._draw_corridor_2d(self.ax, room_a, room_b)
self.fig.canvas.draw()
self.fig.canvas.flush_events()
plt.pause(0.1) # Brief pause to visualize the connection
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 finalize(self):
"""Finalize the plot once generation is complete."""
plt.ioff()
plt.show()
class MapGenerator:
def __init__(self, config: Config, visualizer: MapVisualizer = None):
self.config = config
self.visualizer = visualizer
if config.random_seed is not None:
random.seed(config.random_seed)
def generate_rooms(self) -> List[Room]:
"""Generate non-overlapping rooms within 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 any(new_room.intersects(other) for other in rooms):
rooms.append(new_room)
if self.visualizer:
self.visualizer.update_room(new_room, len(rooms) - 1)
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 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)
mst = nx.minimum_spanning_tree(G)
# Update visualization with MST edges
for edge in mst.edges():
if self.visualizer:
self.visualizer.update_corridor(rooms[edge[0]], rooms[edge[1]])
# 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)
# Update visualization with extra edges
for edge in extra_edges:
if self.visualizer:
self.visualizer.update_corridor(rooms[edge[0]], rooms[edge[1]])
return mst
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='2d',
choices=['2d'],
help="Visualization type: '2d'. Default: '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 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
)
# Initialize visualizer
visualizer = MapVisualizer(config) if args.view == '2d' else None
# Generate map
generator = MapGenerator(config, visualizer)
rooms = generator.generate_rooms()
connections = generator.connect_rooms(rooms)
# Finalize visualization
if visualizer:
visualizer.finalize()
if __name__ == "__main__":
main()
Interactive Mode with plt.ion():
MapVisualizer's __init__ method, plt.ion() is called to enable interactive plotting. This allows the plot to update dynamically without blocking the execution of the script.Initializing the Plot Once:
MapVisualizer with appropriate limits, grid, labels, and title.Updating Rooms and Corridors:
update_room Method:
plt.pause(0.1) introduces a short delay, allowing you to visually perceive each room as it's added.update_corridor Method:
plt.pause(0.1) ensures each corridor connection is visible step-by-step.Modifying MapGenerator to Use the Visualizer:
MapGenerator now accepts an optional visualizer parameter.visualizer.update_room to visualize the addition.visualizer.update_corridor to visualize the connection.Finalizing the Plot:
finalize method is called to turn off interactive mode (plt.ioff()) and display the final plot with plt.show().Main Function Adjustments:
MapVisualizer is instantiated before map generation begins.MapGenerator so that each step of the generation process can be visualized in real-time.To see the step-by-step generation of the map:
Save the Script:
map_generator_visualization.py.Install Dependencies:
pip install matplotlib networkx
Run the Script:
python map_generator_visualization.py --seed 42
--seed argument ensures reproducible results. You can omit it or set it to any integer.Observe the Visualization:
You can further enhance the visualization with the following improvements:
Adjustable Pause Duration:
plt.pause(0.1) duration to speed up or slow down the visualization.Different Visualization Types:
MapVisualizer class to support different types of visualizations (e.g., 3D) if needed in the future.Progress Indicators:
Save the Animation:
matplotlib.animation to save the generation process as a GIF or video file for later review.Enhanced Corridor Drawing:
By incorporating interactive plotting and updating the visualization in real-time as rooms and corridors are generated, you create a dynamic and insightful representation of the map generation process. This not only aids in debugging and understanding the algorithm but also provides an engaging visual experience.
Not yet included in a published release.