forked from UNN/2026-rff_mp
103 lines
2.9 KiB
Python
103 lines
2.9 KiB
Python
import sys
|
|
|
|
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, cells, start=None, exit=None):
|
|
self.width = width
|
|
self.height = height
|
|
self.cells = cells
|
|
self.start = start
|
|
self.exit = exit
|
|
|
|
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 = []
|
|
for dx, dy in ((0, -1), (0, 1), (-1, 0), (1, 0)):
|
|
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:
|
|
@staticmethod
|
|
def build_from_file(filename):
|
|
with open(filename, 'r') as f:
|
|
lines = [line.rstrip('\n') for line in f]
|
|
if not lines:
|
|
raise ValueError("Empty file")
|
|
height = len(lines)
|
|
width = max(len(line) for line in lines)
|
|
cells = []
|
|
start = None
|
|
exit_cell = None
|
|
for y, line in enumerate(lines):
|
|
row = []
|
|
for x in range(width):
|
|
ch = line[x] if x < len(line) else ' '
|
|
is_wall = (ch == '#')
|
|
is_start = (ch == 'S')
|
|
is_exit = (ch == 'E')
|
|
if is_start:
|
|
start = Cell(x, y, False, True, False)
|
|
row.append(start)
|
|
elif is_exit:
|
|
exit_cell = Cell(x, y, False, False, True)
|
|
row.append(exit_cell)
|
|
else:
|
|
row.append(Cell(x, y, is_wall, False, False))
|
|
cells.append(row)
|
|
if start is None:
|
|
raise ValueError("No start cell (S) found")
|
|
if exit_cell is None:
|
|
raise ValueError("No exit cell (E) found")
|
|
return Maze(width, height, cells, start, exit_cell)
|
|
|
|
|
|
def print_maze(maze):
|
|
for y in range(maze.height):
|
|
row = []
|
|
for x in range(maze.width):
|
|
cell = maze.get_cell(x, y)
|
|
if cell.is_start:
|
|
row.append('S')
|
|
elif cell.is_exit:
|
|
row.append('E')
|
|
elif cell.is_wall:
|
|
row.append('#')
|
|
else:
|
|
row.append(' ')
|
|
print(''.join(row))
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) > 1:
|
|
filename = sys.argv[1]
|
|
else:
|
|
filename = 'maze1.txt'
|
|
try:
|
|
maze = MazeBuilder.build_from_file(filename)
|
|
print(f"Maze loaded ({maze.width}x{maze.height})")
|
|
print_maze(maze)
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
|
|
if __name__ == '__main__':
|
|
main()
|