Загрузить файлы в «groshevava/docs/data»

This commit is contained in:
groshevava 2026-05-24 14:16:51 +00:00
parent 89e9ab282a
commit 5b3441628a
5 changed files with 443 additions and 0 deletions

View File

@ -0,0 +1,75 @@
# maze_solver/builders.py
from abc import ABC, abstractmethod
from models import Cell, Maze
class MazeBuilder(ABC):
"""Интерфейс строителя лабиринта."""
@abstractmethod
def buildFromFile(self, filename: str) -> Maze:
"""Строит объект Maze из файла."""
pass
class TextFileMazeBuilder(MazeBuilder):
"""Строитель для текстового формата: ■ стена, ' ' проход, S старт, E выход."""
# Поддерживаемые символы стен
WALL_SYMBOLS = {'#', '', '', '', '', ''}
def __init__(self, require_exit: bool = True):
"""
Args:
require_exit: Если False, позволяет создавать лабиринты без выхода
"""
self.require_exit = require_exit
def buildFromFile(self, filename: str) -> Maze:
with open(filename, 'r', encoding='utf-8') as f:
lines = f.readlines()
# Убираем символы новой строки и пустые строки в конце файла
cleaned_lines = [line.rstrip('\n') for line in lines if line.strip() != '']
if not cleaned_lines:
raise ValueError("Файл лабиринта пуст")
height = len(cleaned_lines)
width = len(cleaned_lines[0])
grid = []
start_cell = None
exit_cell = None
for y, line in enumerate(cleaned_lines):
row = []
if len(line) != width:
raise ValueError(
f"Строка {y} имеет длину {len(line)}, ожидалось {width}. "
f"Лабиринт должен быть прямоугольным."
)
for x, char in enumerate(line):
is_wall = char in self.WALL_SYMBOLS
cell = Cell(x, y, is_wall)
if char == 'S':
cell.isStart = True
start_cell = cell
elif char == 'E':
cell.isExit = True
exit_cell = cell
row.append(cell)
grid.append(row)
if not start_cell:
raise ValueError("В лабиринте не найдена стартовая позиция (S)")
if self.require_exit and not exit_cell:
raise ValueError("В лабиринте не найдена выходная позиция (E)")
maze = Maze(width, height, grid)
maze.start = start_cell
maze.exit = exit_cell
return maze

View File

@ -0,0 +1,201 @@
from builders import TextFileMazeBuilder
from strategies import BFSStrategy, DFSStrategy, AStarStrategy
from solver import MazeSolver
from observers import ConsoleView
from experiments import run_experiments, save_to_csv
import random
WALL = ''
PASSAGE = ' '
START = 'S'
EXIT = 'E'
def generate_maze_prim(size: int, filename: str, label: str):
random.seed(hash(filename) % 10000)
grid = [[WALL for _ in range(size)] for _ in range(size)]
start_x, start_y = 1, 1
grid[start_y][start_x] = PASSAGE
walls = []
for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
wall_x = start_x + dx
wall_y = start_y + dy
cell_x = start_x + 2*dx
cell_y = start_y + 2*dy
if 0 <= cell_x < size and 0 <= cell_y < size:
if grid[wall_y][wall_x] == WALL:
walls.append((wall_x, wall_y, start_x, start_y, cell_x, cell_y))
while walls:
idx = random.randint(0, len(walls) - 1)
wall_x, wall_y, from_x, from_y, to_x, to_y = walls.pop(idx)
if grid[to_y][to_x] == WALL:
grid[wall_y][wall_x] = PASSAGE
grid[to_y][to_x] = PASSAGE
for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
new_wall_x = to_x + dx
new_wall_y = to_y + dy
new_cell_x = to_x + 2*dx
new_cell_y = to_y + 2*dy
if 0 <= new_cell_x < size and 0 <= new_cell_y < size:
if grid[new_wall_y][new_wall_x] == WALL:
walls.append((new_wall_x, new_wall_y, to_x, to_y, new_cell_x, new_cell_y))
grid[1][1] = START
grid[size-2][size-2] = EXIT
with open(filename, 'w', encoding='utf-8') as f:
for row in grid:
f.write(''.join(row) + '\n')
print(f"{label}: {filename}")
def generate_small_maze(filename='small_maze.txt'):
maze = [
"■■■■■■■■■■",
"■S ■",
"■ ■■■■ ■ ■",
"■ ■ ■ ■ ■",
"■ ■ ■■ ■ ■",
"■ ■ ■ ■",
"■ ■■■■■■ ■",
"■ ■",
"■ ■■■■■■■■",
"■ E■",
"■■■■■■■■■■"
]
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(maze))
print(f"Маленький лабиринт 10x10: {filename}")
def generate_no_exit_maze(filename='no_exit_maze.txt'):
maze = [
"■■■■■■■■■■",
"■S ■",
"■ ■■■■ ■ ■",
"■ ■ ■ ■ ■",
"■ ■ ■■ ■ ■",
"■ ■ ■ ■",
"■ ■■■■■■ ■",
"■ ■",
"■ ■■■■■■■■",
"■ ■■■■■■",
"■■■■■E■■■■"
]
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(maze))
print(f"Лабиринт без выхода 10x10: {filename}")
def generate_empty_maze(filename='empty_maze.txt'):
size = 10
maze = []
maze.append(WALL * size)
for i in range(size - 2):
if i == 0:
row = WALL + START + PASSAGE * (size - 3) + WALL
elif i == size - 3:
row = WALL + PASSAGE * (size - 3) + EXIT + WALL
else:
row = WALL + PASSAGE * (size - 2) + WALL
maze.append(row)
maze.append(WALL * size)
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(maze))
print(f"Пустой лабиринт 10x10: {filename}")
def main():
print("=" * 60)
print("ГЕНЕРАЦИЯ ЛАБИРИНТОВ")
print("=" * 60)
generate_small_maze('small_maze.txt')
generate_maze_prim(50, 'medium_maze.txt', 'Средний лабиринт 50x50')
generate_maze_prim(100, 'large_maze.txt', 'Большой лабиринт 100x100')
generate_no_exit_maze('no_exit_maze.txt')
generate_empty_maze('empty_maze.txt')
print("\n" + "=" * 60)
print("ДЕМОНСТРАЦИЯ НА МАЛЕНЬКОМ ЛАБИРИНТЕ")
print("=" * 60)
builder = TextFileMazeBuilder()
maze = builder.buildFromFile('small_maze.txt')
print(f"Размер: {maze.width}x{maze.height}")
print(f"Старт: ({maze.start.x}, {maze.start.y})")
print(f"Выход: ({maze.exit.x}, {maze.exit.y})")
view = ConsoleView()
solver = MazeSolver(maze)
solver.attach(view)
strategies = {
"BFS (поиск в ширину)": BFSStrategy(),
"DFS (поиск в глубину)": DFSStrategy(),
"A*": AStarStrategy()
}
for name, strat in strategies.items():
print(f"\n{'' * 40}")
print(f"Стратегия: {name}")
solver.setStrategy(strat)
path, stats = solver.solve()
if path:
print(f"Путь найден! Длина: {len(path)} шагов")
print(f" Время: {stats.time_ms:.3f} мс | Посещено: {stats.visited_count}")
view.render(maze, path=path)
else:
print("Путь не найден!")
# Эксперименты
print("\n" + "=" * 60)
print("ЭКСПЕРИМЕНТЫ НА ВСЕХ ЛАБИРИНТАХ")
print("=" * 60)
test_mazes = {}
maze_files = [
("Маленький (10x10)", "small_maze.txt"),
("Средний (50x50)", "medium_maze.txt"),
("Большой (100x100)", "large_maze.txt"),
("Без выхода (10x10)", "no_exit_maze.txt"),
("Пустой (10x10)", "empty_maze.txt")
]
for name, filename in maze_files:
try:
test_mazes[name] = builder.buildFromFile(filename)
m = test_mazes[name]
print(f"{name} загружен ({m.width}x{m.height})")
except Exception as e:
print(f"Ошибка {name}: {e}")
if test_mazes:
print(f"\nЗапуск тестов (по 3 прогона)...")
results = run_experiments(test_mazes, strategies, runs=3)
save_to_csv(results)
print("ГОТОВО! Графики: python visualize_results.py")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,46 @@
# maze_solver/models.py
from typing import Optional, List
class Cell:
"""Представляет одну клетку лабиринта."""
def __init__(self, x: int, y: int, is_wall: bool = False):
self.x = x
self.y = y
self.isWall = is_wall
self.isStart = False
self.isExit = False
def isPassable(self) -> bool:
"""Можно ли пройти через клетку."""
return not self.isWall
def __repr__(self):
return f"Cell({self.x}, {self.y}, Wall={self.isWall})"
class Maze:
"""Хранит полную карту лабиринта."""
def __init__(self, width: int, height: int, grid: Optional[List[List[Cell]]] = None):
self.width = width
self.height = height
self.grid = grid if grid else []
self.start: Optional[Cell] = None
self.exit: Optional[Cell] = None
def getCell(self, x: int, y: int) -> Optional[Cell]:
"""Безопасное получение клетки по координатам."""
if 0 <= x < self.width and 0 <= y < self.height:
return self.grid[y][x]
return None
def getNeighbors(self, cell: Cell) -> List[Cell]:
"""Возвращает список соседних ПРОХОДИМЫХ клеток."""
neighbors = []
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] # up, down, left, right
for dx, dy in directions:
nx, ny = cell.x + dx, cell.y + dy
neighbor = self.getCell(nx, ny)
if neighbor and neighbor.isPassable():
neighbors.append(neighbor)
return neighbors

View File

@ -0,0 +1,60 @@
import os
from abc import ABC, abstractmethod
from typing import Optional, List
from models import Maze, Cell
class Observer(ABC):
@abstractmethod
def update(self, event: str, data=None):
pass
class ConsoleView(Observer):
WALL_CHAR = ''
START_CHAR = 'S'
EXIT_CHAR = 'E'
PATH_CHAR = ''
PLAYER_CHAR = 'P'
PASSAGE_CHAR = ' '
def update(self, event: str, data=None):
if event == "search_started":
print(f"\n Запущен поиск с помощью: {data['strategy']}")
elif event == "path_found":
stats = data['stats']
print(f" Путь найден! {stats}")
elif event == "path_not_found":
stats = data['stats']
print(f" Путь НЕ найден. {stats}")
elif event == "step":
self.render(data['maze'], data['current'], data.get('path'))
@staticmethod
def render(maze: Maze, player_pos: Optional[Cell] = None, path: Optional[List[Cell]] = None):
os.system('cls' if os.name == 'nt' else 'clear')
path_set = set(path) if path else set()
print("" + "" * maze.width + "")
for y in range(maze.height):
row_str = ""
for x in range(maze.width):
cell = maze.getCell(x, y)
if player_pos and cell == player_pos:
row_str += ConsoleView.PLAYER_CHAR
elif cell.isStart:
row_str += ConsoleView.START_CHAR
elif cell.isExit:
row_str += ConsoleView.EXIT_CHAR
elif cell in path_set:
row_str += ConsoleView.PATH_CHAR
elif cell.isWall:
row_str += ConsoleView.WALL_CHAR
else:
row_str += ConsoleView.PASSAGE_CHAR
row_str += ""
print(row_str)
print("" + "" * maze.width + "")

View File

@ -0,0 +1,61 @@
import time
from typing import List, Tuple, Optional
from models import Maze, Cell
from strategies import PathFindingStrategy
class SearchStats:
def __init__(self, time_ms: float, visited: int, path_length: int):
self.time_ms = time_ms
self.visited_count = visited
self.path_length = path_length
def __str__(self):
return (f"Время: {self.time_ms:.4f} мс | "
f"Посещено: {self.visited_count} | "
f"Длина пути: {self.path_length}")
class MazeSolver:
def __init__(self, maze: Maze, strategy: Optional[PathFindingStrategy] = None):
self.maze = maze
self.strategy = strategy
self._observers = []
def setStrategy(self, strategy: PathFindingStrategy):
self.strategy = strategy
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def _notify(self, event: str, data=None):
for observer in self._observers:
observer.update(event, data)
def solve(self) -> Tuple[List[Cell], SearchStats]:
if not self.strategy:
raise ValueError("Стратегия поиска не установлена.")
if not self.maze.start or not self.maze.exit:
raise ValueError("В лабиринте не определены старт или выход.")
self._notify("search_started", {"strategy": type(self.strategy).__name__})
start_time = time.perf_counter()
path = self.strategy.findPath(self.maze, self.maze.start, self.maze.exit)
end_time = time.perf_counter()
elapsed_ms = (end_time - start_time) * 1000
visited = self.strategy.visited_count
path_len = len(path)
stats = SearchStats(elapsed_ms, visited, path_len)
if path:
self._notify("path_found", {"path": path, "stats": stats})
else:
self._notify("path_not_found", {"stats": stats})
return path, stats