From c7c181f30b7c5611e88d806f6117aa1fa66bfb3f Mon Sep 17 00:00:00 2001 From: oSTEVEo Date: Tue, 28 Apr 2026 01:11:11 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=BD=20=D1=8D=D1=82=D0=B0=D0=BF=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MusinAA/task2/mazeBuilder.py | 72 +++++++++++++++++++++++++++++++ MusinAA/task2/mazeObjects/cell.py | 2 +- 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 MusinAA/task2/mazeBuilder.py diff --git a/MusinAA/task2/mazeBuilder.py b/MusinAA/task2/mazeBuilder.py new file mode 100644 index 0000000..7ddcc0f --- /dev/null +++ b/MusinAA/task2/mazeBuilder.py @@ -0,0 +1,72 @@ +from abc import ABC, abstractmethod +from itertools import product +import sys + +from task2.mazeObjects.maze import Maze +from task2.mazeObjects.cell import Cell + +class MazeBuilder(ABC): + """Интерфейс MazeBuilder с методом buildFromFile(filename)""" + + @abstractmethod + def buildFromFile(self, filename: str): + """Создание лабиринта из файла.""" + + +class TextFileMazeBuilder(MazeBuilder): + """Читает файл, парсит символы, + создаёт объекты Cell, + задаёт координаты и флаги, + после чего возвращает готовый Maze.""" + + start = {'x': 0, 'y': 0} + end = {'x': 0, 'y': 0} + + def cellStrategy(self, letter: str) -> Cell: + if letter == '#': + return Cell(isWall=True) + elif letter == ' ': + return Cell() + elif letter == 'S': + return Cell(isStart=True) + elif letter == 'E': + return Cell(isExit=True) + else: + sys.stderr.write(f"Неизвестный символ '{letter}' при загрузке из файла\n") + return Cell() + + def updateStartEnd(self, letter: str, x:int, y:int) -> None: + if letter == 'S': + self.start = {'x': x, 'y': y} + elif letter == 'E': + self.end = {'x': x, 'y': y} + + def generate_row_from_txt(self, filename: str) -> list[str]: + with open(filename) as file: + text = file.read() + text = text.strip() + if not text: + raise ValueError(f"Файл \"{filename}\" пуст") + text = text.split('\n') + return text + + def buildFromFile(self, filename: str): + rows = self.generate_row_from_txt(filename) + height = len(rows) + width = len(rows[0]) + array = [[Cell() for j in range(width)] for i in range(height)] + + # Здесь x и y где-то перепутаны, но мне лень это чинить + try: + for x, y in product(range(width), range(height)): + cell = self.cellStrategy(rows[y][x]) + self.updateStartEnd(rows[y][x], x, y) + cell.x = x + cell.y = y + array[y][x] = cell + except IndexError: + raise ValueError(f"Строка {x+1} имеет длину {len(rows[x])}, ожидалось {width}") + + return Maze(array, self.start, self.end) + + \ No newline at end of file diff --git a/MusinAA/task2/mazeObjects/cell.py b/MusinAA/task2/mazeObjects/cell.py index 2eaf73f..9d617ab 100644 --- a/MusinAA/task2/mazeObjects/cell.py +++ b/MusinAA/task2/mazeObjects/cell.py @@ -2,7 +2,7 @@ class Cell: """Хранит координаты (x, y) флаги isWall, isStart, isExit метод isPassable() (возвращает True для прохода, если не стена).""" - def __init__(self, x: int, y: int, isWall = False, isStart = False, isExit = False): + def __init__(self, x: int = 0, y: int = 0, isWall:bool = False, isStart:bool = False, isExit:bool = False): self.x = x self.y = y self.isWall = isWall