diff --git a/SmirnovaVYu/docs/data/2/builders.py b/SmirnovaVYu/docs/data/2/builders.py new file mode 100644 index 0000000..6837933 --- /dev/null +++ b/SmirnovaVYu/docs/data/2/builders.py @@ -0,0 +1,56 @@ +from abc import ABC, abstractmethod +from models import Cell, Maze + + +class MazeBuilder(ABC): + + @abstractmethod + def build_from_file(self, filename: str) -> Maze: + pass + + +class TextFileMazeBuilder(MazeBuilder): + + WALL_CHAR = '#' + START_CHAR = 'S' + EXIT_CHAR = 'E' + PASS_CHAR = ' ' + + def build_from_file(self, filename: str) -> Maze: + with open(filename, 'r', encoding='utf-8') as f: + lines = [line.rstrip('\n') for line in f.readlines()] + + if not lines: + raise ValueError("Файл с лабиринтом пуст") + + height = len(lines) + width = max(len(line) for line in lines) + + maze = Maze(width, height) + + for y, line in enumerate(lines): + for x, ch in enumerate(line): + if x >= width: + continue + + cell = Cell(x, y) + + if ch == self.WALL_CHAR: + cell.is_wall = True + elif ch == self.START_CHAR: + cell.is_start = True + elif ch == self.EXIT_CHAR: + cell.is_exit = True + elif ch == self.PASS_CHAR: + pass + else: + cell.is_wall = True + + maze.set_cell(x, y, cell) + + if maze.start is None: + raise ValueError("В лабиринте нет стартовой клетки (S)") + if maze.exit is None: + raise ValueError("В лабиринте нет выхода (E)") + + return maze \ No newline at end of file diff --git a/SmirnovaVYu/docs/data/2/models.py b/SmirnovaVYu/docs/data/2/models.py new file mode 100644 index 0000000..5932d5f --- /dev/null +++ b/SmirnovaVYu/docs/data/2/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/2/observers.py b/SmirnovaVYu/docs/data/2/observers.py new file mode 100644 index 0000000..eb10114 --- /dev/null +++ b/SmirnovaVYu/docs/data/2/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/2/solver.py b/SmirnovaVYu/docs/data/2/solver.py new file mode 100644 index 0000000..137e481 --- /dev/null +++ b/SmirnovaVYu/docs/data/2/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/2/strategies.py b/SmirnovaVYu/docs/data/2/strategies.py new file mode 100644 index 0000000..ba797ae --- /dev/null +++ b/SmirnovaVYu/docs/data/2/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