Untitled conversation
- Userpython
- Assistant
#!/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()
Почему в коде дублируются конфиги? Убери из кода дубликаты, повторяющиеся участки и структурируй код.
You're correct in observing that the configuration (Config) is being redundantly initialized in the code. Specifically, the Config dataclass provides default values, and these are being overridden in the main function with values that are either the same as the defaults or only slightly modified. This redundancy can lead to confusion, maintenance challenges, and potential inconsistencies.
To address these issues, we'll refactor the code to:
Eliminate Duplicate Configuration Initializations:
main function.Enhance Configuration Flexibility:
Improve Code Structure:
Below is the refactored version of your code with these improvements:
#!/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, asdict
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])
max_split = self.height - config.room_min_size if split_horizontally else 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(config: Config) -> argparse.Namespace:
"""Parse command-line arguments and update the config accordingly."""
parser = argparse.ArgumentParser(
description="Hammer Editor Source Map GENERATOR 2D - Generate and visualize maps with rooms and corridors."
)
# Visualization options
parser.add_argument(
'--view', type=str, default='2d',
choices=['2d'],
help="Type of visualization: '2d'. Default is '2d'."
)
# Random seed for reproducibility
parser.add_argument(
'--seed', type=int,
help="Random seed for reproducibility."
)
# Configuration parameters
parser.add_argument(
'--num_rooms', type=int, default=config.num_rooms,
help=f"Number of rooms to generate. Default is {config.num_rooms}."
)
parser.add_argument(
'--map_width', type=int, default=config.map_width,
help=f"Width of the map. Default is {config.map_width}."
)
parser.add_argument(
'--map_height', type=int, default=config.map_height,
help=f"Height of the map. Default is {config.map_height}."
)
parser.add_argument(
'--room_min_size', type=int, default=config.room_min_size,
help=f"Minimum size of a room. Default is {config.room_min_size}."
)
parser.add_argument(
'--room_max_size', type=int, default=config.room_max_size,
help=f"Maximum size of a room. Default is {config.room_max_size}."
)
parser.add_argument(
'--passageway_width', type=int, default=config.passageway_width,
help=f"Width of the passageways. Default is {config.passageway_width}."
)
parser.add_argument(
'--extra_connections_factor', type=float, default=config.extra_connections_factor,
help=f"Factor to determine extra connections. Default is {config.extra_connections_factor}."
)
parser.add_argument(
'--max_depth', type=int, default=config.max_depth,
help=f"Maximum BSP tree depth. Default is {config.max_depth}."
)
parser.add_argument(
'--split_ratio', type=float, default=config.split_ratio,
help=f"Split ratio for BSP. Default is {config.split_ratio}."
)
# Placeholder for future configuration file support
parser.add_argument(
'--config', type=str, default=None,
help="Path to a configuration file (optional)."
)
args = parser.parse_args()
# Update config with parsed arguments
config.num_rooms = args.num_rooms
config.map_width = args.map_width
config.map_height = args.map_height
config.room_min_size = args.room_min_size
config.room_max_size = args.room_max_size
config.passageway_width = args.passageway_width
config.extra_connections_factor = args.extra_connections_factor
config.max_depth = args.max_depth
config.split_ratio = args.split_ratio
if args.seed is not None:
config.random_seed = args.seed
return args
def main():
# Initialize default configuration
config = Config()
# Parse command-line arguments and update the configuration
args = parse_arguments(config)
# Optionally, load additional configuration from a file here in the future
# 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()
Centralized Configuration Management:
Config: The Config dataclass now holds all default configuration values.parse_arguments function now includes arguments for all configurable parameters. This allows users to override defaults directly from the command line without modifying the script.Config from Arguments: After parsing the arguments, we update the Config instance with any provided values. This ensures that configuration is managed in a single location, eliminating redundancy.Eliminated Hardcoded Configuration in main:
Config in the main function.Config is now initialized with defaults and then updated based on user input from command-line arguments.Enhanced parse_arguments Function:
parse_arguments function to include all configuration parameters, providing comprehensive control over the map generation process via the command line.help description, making the script more user-friendly.Future Configuration File Support:
parse_arguments indicates where you can add functionality to load configuration from a file. This makes the script extensible for future enhancements.Improved Readability and Maintainability:
Using Defaults:
python map_generator.py
Specifying Number of Rooms and Seed:
python map_generator.py --num_rooms 50 --seed 42
Custom Map Size and Room Dimensions:
python map_generator.py --map_width 300 --map_height 300 --room_min_size 10 --room_max_size 30
Adjusting Corridor Properties:
python map_generator.py --passageway_width 5 --extra_connections_factor 0.6
This refactored approach ensures that the configuration is single-sourced, flexible, and maintainable, making it easier to manage and extend the map generation process in the future.
Not yet included in a published release.