101 lines
2.9 KiB
Python
101 lines
2.9 KiB
Python
import sys
|
|
from collections import deque
|
|
import heapq
|
|
import time
|
|
import os
|
|
|
|
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
|
|
|
|
def __repr__(self):
|
|
return f"Cell({self.x}, {self.y})"
|
|
|
|
|
|
class Maze:
|
|
"""лабиринт"""
|
|
def __init__(self, width, height):
|
|
self.width = width
|
|
self.height = height
|
|
self.cells = [[Cell(x, y) for x in range(width)] for y in range(height)]
|
|
self.start = None
|
|
self.exit = None
|
|
|
|
def get_cell(self, x, y):
|
|
if 0 <= x < self.width and 0 <= y < self.height:
|
|
return self.cells[y][x]
|
|
return None
|
|
|
|
def get_neighbors(self, cell):
|
|
neighbors = []
|
|
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
|
|
for dx, dy in directions:
|
|
neighbor = self.get_cell(cell.x + dx, cell.y + dy)
|
|
if neighbor and neighbor.is_passable():
|
|
neighbors.append(neighbor)
|
|
return neighbors
|
|
|
|
def set_start(self, x, y):
|
|
cell = self.get_cell(x, y)
|
|
if cell:
|
|
cell.is_start = True
|
|
self.start = cell
|
|
|
|
def set_exit(self, x, y):
|
|
cell = self.get_cell(x, y)
|
|
if cell:
|
|
cell.is_exit = True
|
|
self.exit = cell
|
|
|
|
|
|
|
|
class MazeBuilder:
|
|
"""интерфейс строителя лабиринта"""
|
|
|
|
def buildFromFile(self, filename):
|
|
raise NotImplementedError
|
|
|
|
|
|
class TextFileMazeBuilder(MazeBuilder):
|
|
"""загрузка лабиринта из текстового файла"""
|
|
|
|
def buildFromFile(self, filename):
|
|
with open(filename, 'r', encoding='utf-8') as f:
|
|
lines = [line.rstrip('\n') for line in f.readlines()]
|
|
|
|
height = len(lines)
|
|
width = max(len(line) for line in lines) if height > 0 else 0
|
|
|
|
for i in range(height):
|
|
if len(lines[i]) < width:
|
|
lines[i] = lines[i] + ' ' * (width - len(lines[i]))
|
|
|
|
maze = Maze(width, height)
|
|
start_count = 0
|
|
exit_count = 0
|
|
|
|
for y, line in enumerate(lines):
|
|
for x, ch in enumerate(line):
|
|
if ch == '#':
|
|
maze.get_cell(x, y).is_wall = True
|
|
elif ch == 'S':
|
|
maze.set_start(x, y)
|
|
start_count += 1
|
|
elif ch == 'E':
|
|
maze.set_exit(x, y)
|
|
exit_count += 1
|
|
else:
|
|
maze.get_cell(x, y).is_wall = False
|
|
|
|
if start_count != 1 or exit_count != 1:
|
|
raise ValueError(f"Ошибка: S={start_count}, E={exit_count} (нужно по одному)")
|
|
|
|
return maze |