2026-rff_mp/AgapovaDS/docs/data/2-nd/maze.py
2026-09-03 02:12:32 +03:00

105 lines
3.5 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.

# maze.py версия 1: модель лабиринта и загрузка из текстового файла
class Cell:
"""Клетка лабиринта."""
def __init__(self, x, y, is_wall=False, is_start=False, is_exit=False):
self.x = x
self.y = y
self.is_wall = is_wall
self.is_start = is_start
self.is_exit = is_exit
def is_passable(self):
return not self.is_wall
class Maze:
"""Модель лабиринта."""
def __init__(self, width, height):
self.width = width
self.height = height
self.grid = [[Cell(x, y) for y in range(height)] for x in range(width)]
self.start_cell = None
self.exit_cell = None
def get_cell(self, x, y):
if 0 <= x < self.width and 0 <= y < self.height:
return self.grid[x][y]
return None
def get_neighbors(self, cell):
"""Возвращает список проходимых соседей (вверх, вниз, влево, вправо)."""
neighbors = []
for dx, dy in [(-1,0), (1,0), (0,-1), (0,1)]:
nx, ny = cell.x + dx, cell.y + dy
neighbor = self.get_cell(nx, ny)
if neighbor and neighbor.is_passable():
neighbors.append(neighbor)
return neighbors
class MazeBuilder:
"""Интерфейс строителя лабиринта."""
def build_from_file(self, filename):
raise NotImplementedError
class TextFileMazeBuilder(MazeBuilder):
"""Строитель лабиринта из текстового файла."""
def build_from_file(self, filename):
with open(filename, 'r', encoding='utf-8') as f:
lines = f.readlines()
lines = [line.rstrip('\n') for line in lines if line.strip() != '']
if not lines:
raise ValueError("Файл пуст")
height = len(lines)
width = max(len(line) for line in lines)
maze = Maze(width, height)
for y, line in enumerate(lines):
for x, ch in enumerate(line):
if x >= width:
break
cell = maze.get_cell(x, y)
if ch == '#':
cell.is_wall = True
elif ch == 'S':
cell.is_start = True
maze.start_cell = cell
elif ch == 'E':
cell.is_exit = True
maze.exit_cell = cell
if maze.start_cell is None or maze.exit_cell is None:
raise ValueError("В лабиринте должны быть S и E")
return maze
# Тестирование загрузки
if __name__ == '__main__':
# Создаём тестовый файл
test_maze = """#######
#S #
# ### #
# E #
#######"""
with open('test_maze.txt', 'w') as f:
f.write(test_maze)
builder = TextFileMazeBuilder()
maze = builder.build_from_file('test_maze.txt')
print(f"Лабиринт {maze.width}x{maze.height} загружен.")
print(f"Старт: ({maze.start_cell.x},{maze.start_cell.y})")
print(f"Выход: ({maze.exit_cell.x},{maze.exit_cell.y})")
# Вывод карты
for y in range(maze.height):
row = ''
for x in range(maze.width):
cell = maze.get_cell(x, y)
if cell.is_wall:
row += '#'
elif cell.is_start:
row += 'S'
elif cell.is_exit:
row += 'E'
else:
row += ' '
print(row)