diff --git a/komissarovgo/docs2/data2/maze_lab/builders.py b/komissarovgo/docs2/data2/maze_lab/builders.py new file mode 100644 index 0000000..2724eae --- /dev/null +++ b/komissarovgo/docs2/data2/maze_lab/builders.py @@ -0,0 +1,59 @@ +from abc import ABC, abstractmethod +from typing import List +from models import Cell, Maze + + +class MazeBuilder(ABC): + + + @abstractmethod + def build_from_file(self, filename: str) -> Maze: + pass + + +class TextFileMazeBuilder(MazeBuilder): + + + def build_from_file(self, filename: str) -> Maze: + with open(filename, 'r', encoding='utf-8') as file: + lines = [line.rstrip('\n') for line in file.readlines()] + + if not lines: + raise ValueError("Файл пуст") + + height = len(lines) + width = max(len(line) for line in lines) + + maze = Maze(width, height) + cells = [] + + for y, line in enumerate(lines): + row = [] + for x in range(width): + if x < len(line): + char = line[x] + else: + char = ' ' + + cell = Cell(x, y) + + if char == '#': + cell.is_wall = True + elif char == 'S': + cell.is_start = True + elif char == 'E': + cell.is_exit = True + else: + cell.is_wall = False + + row.append(cell) + cells.append(row) + + maze.set_cells(cells) + + if maze.start is None: + raise ValueError("Нет стартовой клетки (S)") + if maze.exit is None: + raise ValueError("Нет выходной клетки (E)") + + return maze \ No newline at end of file