2026-rff_mp/ivantsovma/maze/builders/text_file_maze_builder.py

37 lines
1.3 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 models import Cell, Maze
from .maze_builder import MazeBuilder
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()]
height = len(lines)
width = len(lines[0]) if height > 0 else 0
maze = Maze(width, height)
for y, line in enumerate(lines):
for x, char in enumerate(line):
is_wall = (char == '#')
is_start = (char == 'S')
is_exit = (char == 'E')
cell = Cell(x, y, is_wall, is_start, is_exit)
maze.set_cell(x, y, cell)
if is_start:
maze.start = cell
if is_exit:
maze.exit = cell
# Валидация
if maze.start is None:
raise ValueError("В лабиринте нет стартовой клетки (S)")
if maze.exit is None:
raise ValueError("В лабиринте нет выходной клетки (E)")
return maze