builder pattern

реализованы классы строющие лабиринты
This commit is contained in:
novikovsd 2026-05-25 09:13:49 +00:00
parent 20982d4172
commit da8127d37a

View File

@ -49,8 +49,54 @@ class Maze:
return neighbors
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 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)
start_cell = None
exit_cell = None
for y, line in enumerate(lines):
for x, ch in enumerate(line):
is_wall = (ch == '#')
cell = Cell(x, y, is_wall)
if ch == 'S':
cell.is_start = True
start_cell = cell
elif ch == 'E':
cell.is_exit = True
exit_cell = cell
maze.set_cell(x, y, cell)
if start_cell is None or exit_cell is None:
for y in range(height):
for x in range(width):
cell = maze.get_cell(x, y)
if cell and cell.is_start:
start_cell = cell
if cell and cell.is_exit:
exit_cell = cell
if start_cell is None:
raise ValueError("Нет стартовой клетки (S)")
if exit_cell is None:
raise ValueError("Нет выходной клетки (E)")
maze.start = start_cell
maze.exit = exit_cell
return maze
class PathFindingStrategy(ABC):