2026-rff_mp/stepushovgs/labyrinth/source/builder/text_file_maze_builder.py

54 lines
2.0 KiB
Python
Raw Normal View History

from source.classes.maze import Maze, Cell
from .builder import MazeBuilder
class TextFileMazeBuilder(MazeBuilder):
def buildFromFile(self, filename: str) -> Maze:
"""Получает лабиринт из текстового файла"""
with open(filename) as f:
data = f.read().splitlines()
x, y = 0, 0
width = len(data[0])
height = len(data)
cells = [[None] * width for _ in range(height)]
start, c_exit = None, None
for line in data:
x = 0
for c in line.strip():
if c == 'S':
cells[y][x] = Cell(x, y, isStart=True)
start = cells[y][x]
x += 1
elif c == 'E':
cells[y][x] = Cell(x, y, isExit=True)
c_exit = cells[y][x]
x += 1
elif c == '#':
cells[y][x] = Cell(x, y, isWall=True)
x += 1
elif c == ' ':
cells[y][x] = Cell(x, y)
x += 1
else:
print(f'Обнаружен неизвестный символ({c}) в файле лабиринта\nfilename: {filename}\nОн заменён на стену')
cells[y][x] = Cell(x, y, isWall=True)
x += 1
y += 1
if start == None:
raise ValueError(f'В файле лабиринта не обнаружен вход!\nfilename: {filename}')
if c_exit == None:
raise ValueError(f'В файле лабиринта не обнаружен выход!\nfilename: {filename}')
return Maze(
cells=cells,
width=width,
height=height,
start=start,
exit_cell=c_exit
)