2026-rff_mp/romanovpv/task 2/docs/data/builders.py
2026-05-18 00:40:59 +03:00

70 lines
2.0 KiB
Python

from abc import ABC, abstractmethod
from model import Maze, Cell
class MazeBuilder(ABC):
@abstractmethod
def buildFromFile(self, filename):
pass
class TextFileMazeBuilder(MazeBuilder):
def buildFromFile(self, filename):
with open(
filename,
"r",
encoding="utf-8"
) as file:
lines = [
line.rstrip("\n")
for line in file
]
height = len(lines)
width = len(lines[0])
maze = Maze(
width,
height
)
start_count = 0
exit_count = 0
for x, line in enumerate(lines):
row = []
for y, symbol in enumerate(line):
if symbol == "#":
cell = Cell(
x,
y,
is_wall=True
)
elif symbol == "S":
cell = Cell(
x,
y,
is_start=True
)
start_count += 1
elif symbol == "E":
cell = Cell(
x,
y,
is_exit=True
)
exit_count += 1
elif symbol == " ":
cell = Cell(
x,
y
)
else:
raise ValueError(
f"Неизвестный символ: {symbol}"
)
row.append(cell)
maze.add_row(row)
if start_count != 1:
raise ValueError(
"Должен быть ровно один старт S"
)
if exit_count != 1:
raise ValueError(
"Должен быть ровно один выход E"
)
return maze