добавлен код builders
This commit is contained in:
parent
d302eea649
commit
9696f6c5f1
59
komissarovgo/docs2/data2/maze_lab/builders.py
Normal file
59
komissarovgo/docs2/data2/maze_lab/builders.py
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import List
|
||||||
|
from models import Cell, Maze
|
||||||
|
|
||||||
|
|
||||||
|
class MazeBuilder(ABC):
|
||||||
|
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def build_from_file(self, filename: str) -> Maze:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TextFileMazeBuilder(MazeBuilder):
|
||||||
|
|
||||||
|
|
||||||
|
def build_from_file(self, filename: str) -> Maze:
|
||||||
|
with open(filename, 'r', encoding='utf-8') as file:
|
||||||
|
lines = [line.rstrip('\n') for line in file.readlines()]
|
||||||
|
|
||||||
|
if not lines:
|
||||||
|
raise ValueError("Файл пуст")
|
||||||
|
|
||||||
|
height = len(lines)
|
||||||
|
width = max(len(line) for line in lines)
|
||||||
|
|
||||||
|
maze = Maze(width, height)
|
||||||
|
cells = []
|
||||||
|
|
||||||
|
for y, line in enumerate(lines):
|
||||||
|
row = []
|
||||||
|
for x in range(width):
|
||||||
|
if x < len(line):
|
||||||
|
char = line[x]
|
||||||
|
else:
|
||||||
|
char = ' '
|
||||||
|
|
||||||
|
cell = Cell(x, y)
|
||||||
|
|
||||||
|
if char == '#':
|
||||||
|
cell.is_wall = True
|
||||||
|
elif char == 'S':
|
||||||
|
cell.is_start = True
|
||||||
|
elif char == 'E':
|
||||||
|
cell.is_exit = True
|
||||||
|
else:
|
||||||
|
cell.is_wall = False
|
||||||
|
|
||||||
|
row.append(cell)
|
||||||
|
cells.append(row)
|
||||||
|
|
||||||
|
maze.set_cells(cells)
|
||||||
|
|
||||||
|
if maze.start is None:
|
||||||
|
raise ValueError("Нет стартовой клетки (S)")
|
||||||
|
if maze.exit is None:
|
||||||
|
raise ValueError("Нет выходной клетки (E)")
|
||||||
|
|
||||||
|
return maze
|
||||||
Loading…
Reference in New Issue
Block a user