1
0
forked from UNN/2026-rff_mp
2026-rff_mp/pogodinda/lab2/src/maze.py

84 lines
2.5 KiB
Python

from typing import List, Optional
class Cell:
"""Клетка лабиринта."""
def __init__(self, x: int, y: int, is_wall: bool = False,
is_start: bool = False, is_exit: bool = False, weight: int = 1):
self.x = x
self.y = y
self.is_wall = is_wall
self.is_start = is_start
self.is_exit = is_exit
self.weight = weight # для взвешенных лабиринтов
def is_passable(self) -> bool:
return not self.is_wall
def __repr__(self):
if self.is_start:
return 'S'
elif self.is_exit:
return 'E'
elif self.is_wall:
return '#'
else:
return ' '
def __eq__(self, other):
if isinstance(other, Cell):
return self.x == other.x and self.y == other.y
return False
def __hash__(self):
return hash((self.x, self.y))
class Maze:
"""Лабиринт — сетка клеток."""
def __init__(self, width: int, height: int):
self.width = width
self.height = height
self.cells: List[List[Cell]] = []
self.start: Optional[Cell] = None
self.exit: Optional[Cell] = None
for y in range(height):
row = []
for x in range(width):
row.append(Cell(x, y))
self.cells.append(row)
def get_cell(self, x: int, y: int) -> Optional[Cell]:
if 0 <= x < self.width and 0 <= y < self.height:
return self.cells[y][x]
return None
def set_cell(self, x: int, y: int, cell: Cell):
if 0 <= x < self.width and 0 <= y < self.height:
self.cells[y][x] = cell
if cell.is_start:
self.start = cell
if cell.is_exit:
self.exit = cell
def get_neighbors(self, cell: Cell) -> List[Cell]:
"""Соседи сверху/снизу/слева/справа, если проходимы."""
neighbors = []
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
for dx, dy in directions:
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
def __repr__(self):
lines = []
for row in self.cells:
lines.append(''.join(str(cell) for cell in row))
return '\n'.join(lines)