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

63 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from abc import ABC, abstractmethod
from source.classes.maze import Maze
from source.classes.cell import Cell
class MazeBuilder(ABC):
@abstractmethod
def buildFromFile(self, filename: str) -> Maze:
pass
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=c_exit
)