From 8cb368fdd4946aeb3022c892d6659324dd69822b Mon Sep 17 00:00:00 2001 From: smirnovavyu Date: Fri, 4 Sep 2026 15:01:14 +0000 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2=20=C2=AB?= =?UTF-8?q?SmirnovaVYu/docs/data=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SmirnovaVYu/docs/data/models.py | 79 +++++++++++++++++++++++ SmirnovaVYu/docs/data/observers.py | 66 +++++++++++++++++++ SmirnovaVYu/docs/data/solver.py | 49 ++++++++++++++ SmirnovaVYu/docs/data/strategies.py | 99 +++++++++++++++++++++++++++++ SmirnovaVYu/docs/data/visualize.py | 77 ++++++++++++++++++++++ 5 files changed, 370 insertions(+) create mode 100644 SmirnovaVYu/docs/data/models.py create mode 100644 SmirnovaVYu/docs/data/observers.py create mode 100644 SmirnovaVYu/docs/data/solver.py create mode 100644 SmirnovaVYu/docs/data/strategies.py create mode 100644 SmirnovaVYu/docs/data/visualize.py diff --git a/SmirnovaVYu/docs/data/models.py b/SmirnovaVYu/docs/data/models.py new file mode 100644 index 0000000..5932d5f --- /dev/null +++ b/SmirnovaVYu/docs/data/models.py @@ -0,0 +1,79 @@ +from typing import List, Optional + + +class Cell: + + def __init__(self, x: int, y: int): + self.x = x + self.y = y + self.is_wall = False + self.is_start = False + self.is_exit = False + + def is_passable(self) -> bool: + return not self.is_wall + + def __eq__(self, other) -> bool: + if not isinstance(other, Cell): + return False + return self.x == other.x and self.y == other.y + + def __hash__(self): + return hash((self.x, self.y)) + + def __repr__(self): + return f"Cell({self.x}, {self.y})" + + +class Maze: + + def __init__(self, width: int, height: int): + self.width = width + self.height = height + self._cells: List[List[Optional[Cell]]] = [[None for _ in range(width)] for _ in range(height)] + self.start: Optional[Cell] = None + self.exit: Optional[Cell] = None + + def set_cell(self, x: int, y: int, cell: Cell) -> None: + if 0 <= x < self.width and 0 <= y < self.height: + self._cells[y][x] = cell + if cell.is_start: + self.start = cell + if cell.is_exit: + self.exit = cell + + def get_cell(self, x: int, y: int) -> Optional[Cell]: + if 0 <= x < self.width and 0 <= y < self.height: + return self._cells[y][x] + return None + + def get_neighbors(self, cell: Cell) -> List[Cell]: + neighbors = [] + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + + for dx, dy in directions: + nx, ny = cell.x + dx, cell.y + dy + neighbor = self.get_cell(nx, ny) + if neighbor and neighbor.is_passable(): + neighbors.append(neighbor) + + return neighbors + + def __str__(self) -> str: + result = [] + for y in range(self.height): + row = [] + for x in range(self.width): + cell = self.get_cell(x, y) + if cell is None: + row.append('?') + elif cell.is_start: + row.append('S') + elif cell.is_exit: + row.append('E') + elif cell.is_wall: + row.append('#') + else: + row.append(' ') + result.append(''.join(row)) + return '\n'.join(result) \ No newline at end of file diff --git a/SmirnovaVYu/docs/data/observers.py b/SmirnovaVYu/docs/data/observers.py new file mode 100644 index 0000000..eb10114 --- /dev/null +++ b/SmirnovaVYu/docs/data/observers.py @@ -0,0 +1,66 @@ +from abc import ABC, abstractmethod +from typing import List, Optional +from models import Cell, Maze + + +class Observer(ABC): + + @abstractmethod + def update(self, event: str, data: dict) -> None: + pass + + +class ConsoleView(Observer): + + def render(self, maze: Maze, player_position: Optional[Cell] = None, path: Optional[List[Cell]] = None) -> None: + path_set = set(path) if path else set() + + print("\n+" + "-" * maze.width + "+") + + for y in range(maze.height): + row = [] + for x in range(maze.width): + cell = maze.get_cell(x, y) + if cell is None: + row.append('?') + elif player_position and cell == player_position: + row.append('@') + elif cell.is_start: + row.append('S') + elif cell.is_exit: + row.append('E') + elif cell in path_set: + row.append('*') + elif cell.is_wall: + row.append('#') + else: + row.append(' ') + print("|" + ''.join(row) + "|") + + print("+" + "-" * maze.width + "+") + + def update(self, event: str, data: dict) -> None: + if event == "maze_loaded": + maze = data.get('maze') + print("\n Лабиринт загружен:") + self.render(maze) + + elif event == "search_start": + algorithm = data.get('algorithm', 'Unknown') + print(f"\n Начинаем поиск алгоритмом: {algorithm}") + + elif event == "path_found": + maze = data.get('maze') + path = data.get('path') + stats = data.get('stats') + self.render(maze, path=path) + + elif event == "no_path": + stats = data.get('stats') + print(f"\n {stats}") + + elif event == "player_moved": + maze = data.get('maze') + player = data.get('player') + if player: + self.render(maze, player_position=player.current_cell) \ No newline at end of file diff --git a/SmirnovaVYu/docs/data/solver.py b/SmirnovaVYu/docs/data/solver.py new file mode 100644 index 0000000..137e481 --- /dev/null +++ b/SmirnovaVYu/docs/data/solver.py @@ -0,0 +1,49 @@ +import time +from dataclasses import dataclass +from typing import List, Optional, Tuple +from models import Cell, Maze +from strategies import PathFindingStrategy + + +@dataclass +class SearchStats: + time_ms: float + visited_cells: int + path_length: int + path_found: bool = True + + def __str__(self) -> str: + if not self.path_found: + return f"Путь не найден (время: {self.time_ms:.2f} мс)" + return (f"Время: {self.time_ms:.2f} мс, " + f"Посещено клеток: {self.visited_cells}, " + f"Длина пути: {self.path_length}") + + +class MazeSolver: + + def __init__(self, maze: Maze, strategy: Optional[PathFindingStrategy] = None): + self.maze = maze + self._strategy = strategy + + def set_strategy(self, strategy: PathFindingStrategy) -> None: + self._strategy = strategy + + def solve(self) -> Tuple[List[Cell], SearchStats]: + if self._strategy is None: + raise ValueError("Стратегия не установлена") + + start_time = time.perf_counter() + path = self._strategy.find_path(self.maze, self.maze.start, self.maze.exit) + end_time = time.perf_counter() + + time_ms = (end_time - start_time) * 1000 + + stats = SearchStats( + time_ms=time_ms, + visited_cells=len(path) if path else 0, + path_length=len(path) if path else 0, + path_found=bool(path) + ) + + return path, stats \ No newline at end of file diff --git a/SmirnovaVYu/docs/data/strategies.py b/SmirnovaVYu/docs/data/strategies.py new file mode 100644 index 0000000..ba797ae --- /dev/null +++ b/SmirnovaVYu/docs/data/strategies.py @@ -0,0 +1,99 @@ +from abc import ABC, abstractmethod +from collections import deque +from heapq import heappush, heappop +from typing import List, Dict, Optional +from models import Cell, Maze + + +class PathFindingStrategy(ABC): + + @abstractmethod + def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]: + pass + + +class BFSStrategy(PathFindingStrategy): + + def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]: + queue = deque([start]) + visited = {start} + parent: Dict[Cell, Optional[Cell]] = {start: None} + + while queue: + current = queue.popleft() + + if current == exit_cell: + return self._reconstruct_path(parent, current) + + for neighbor in maze.get_neighbors(current): + if neighbor not in visited: + visited.add(neighbor) + parent[neighbor] = current + queue.append(neighbor) + + return [] + + def _reconstruct_path(self, parent: Dict[Cell, Optional[Cell]], current: Cell) -> List[Cell]: + path = [] + while current is not None: + path.append(current) + current = parent.get(current) + return list(reversed(path)) + + +class DFSStrategy(PathFindingStrategy): + + def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]: + stack = [(start, [start])] + visited = {start} + + while stack: + current, path = stack.pop() + + if current == exit_cell: + return path + + for neighbor in maze.get_neighbors(current): + if neighbor not in visited: + visited.add(neighbor) + stack.append((neighbor, path + [neighbor])) + + return [] + + +class AStarStrategy(PathFindingStrategy): + + def _heuristic(self, cell: Cell, exit_cell: Cell) -> int: + return abs(cell.x - exit_cell.x) + abs(cell.y - exit_cell.y) + + def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]: + counter = 0 + open_set = [(self._heuristic(start, exit_cell), counter, start)] + + g_score: Dict[Cell, float] = {start: 0} + parent: Dict[Cell, Optional[Cell]] = {start: None} + + while open_set: + _, _, current = heappop(open_set) + + if current == exit_cell: + return self._reconstruct_path(parent, current) + + for neighbor in maze.get_neighbors(current): + tentative_g = g_score[current] + 1 + + if neighbor not in g_score or tentative_g < g_score[neighbor]: + parent[neighbor] = current + g_score[neighbor] = tentative_g + counter += 1 + f = tentative_g + self._heuristic(neighbor, exit_cell) + heappush(open_set, (f, counter, neighbor)) + + return [] + + def _reconstruct_path(self, parent: Dict[Cell, Optional[Cell]], current: Cell) -> List[Cell]: + path = [] + while current is not None: + path.append(current) + current = parent.get(current) + return list(reversed(path)) \ No newline at end of file diff --git a/SmirnovaVYu/docs/data/visualize.py b/SmirnovaVYu/docs/data/visualize.py new file mode 100644 index 0000000..70117f6 --- /dev/null +++ b/SmirnovaVYu/docs/data/visualize.py @@ -0,0 +1,77 @@ +import pandas as pd +import matplotlib.pyplot as plt +import numpy as np +from pathlib import Path + + +def plot_results(csv_file='experiment_results.csv'): + + if not Path(csv_file).exists(): + print(f"❌ {csv_file} не найден. Сначала запустите main.py") + return + + df = pd.read_csv(csv_file) + + df = df[df['path_found'] == True] + + if df.empty: + print("Нет данных для графиков") + return + + mazes = [m.replace('.txt', '') for m in df['maze_file'].unique()] + strategies = df['strategy'].unique() + + fig, axes = plt.subplots(1, 3, figsize=(14, 5)) + fig.suptitle('Сравнение алгоритмов поиска в лабиринте', fontsize=14, fontweight='bold') + + x = np.arange(len(mazes)) + width = 0.25 + colors = {'BFS': '#3498db', 'DFS': '#2ecc71', 'A*': '#e74c3c'} + + for i, strategy in enumerate(strategies): + times, visited, lengths = [], [], [] + + for maze in df['maze_file'].unique(): + data = df[(df['strategy'] == strategy) & (df['maze_file'] == maze)] + if not data.empty: + times.append(data['time_mean'].values[0]) + visited.append(data['visited_mean'].values[0]) + lengths.append(data['path_length_mean'].values[0]) + else: + times.append(0) + visited.append(0) + lengths.append(0) + + axes[0].bar(x + i*width, times, width, label=strategy, + color=colors.get(strategy, 'gray'), alpha=0.7) + axes[1].bar(x + i*width, visited, width, label=strategy, + color=colors.get(strategy, 'gray'), alpha=0.7) + axes[2].bar(x + i*width, lengths, width, label=strategy, + color=colors.get(strategy, 'gray'), alpha=0.7) + + axes[0].set_title(' Время выполнения (мс)') + axes[0].set_xticks(x + width) + axes[0].set_xticklabels(mazes, rotation=45, ha='right') + axes[0].legend() + axes[0].grid(True, alpha=0.3) + + axes[1].set_title(' Посещённые клетки') + axes[1].set_xticks(x + width) + axes[1].set_xticklabels(mazes, rotation=45, ha='right') + axes[1].legend() + axes[1].grid(True, alpha=0.3) + + axes[2].set_title(' Длина пути') + axes[2].set_xticks(x + width) + axes[2].set_xticklabels(mazes, rotation=45, ha='right') + axes[2].legend() + axes[2].grid(True, alpha=0.3) + + plt.tight_layout() + plt.savefig('experiment_results.png', dpi=150, bbox_inches='tight') + plt.show() + + + +if __name__ == "__main__": + plot_results() \ No newline at end of file