2026-rff_mp/krasnovia/lab2/docs/data/maze_model.py
2026-05-20 23:04:18 +03:00

64 lines
2.1 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.

"""
Этап 1: Модель лабиринта — классы Cell и Maze
"""
class Cell:
"""Представляет одну клетку лабиринта."""
def __init__(self, x: int, y: int, is_wall: bool = False,
is_start: bool = False, is_exit: bool = 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) -> bool:
"""True, если клетка проходима (не стена)."""
return not self.is_wall
def __repr__(self):
if self.is_start:
return "S"
if self.is_exit:
return "E"
return "#" if self.is_wall else "."
def __eq__(self, other):
return isinstance(other, Cell) and self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
class Maze:
"""Хранит двумерную сетку клеток, размеры и ссылки на старт/выход."""
def __init__(self, width: int, height: int, cells: list[list[Cell]],
start: Cell, exit_cell: Cell):
self.width = width
self.height = height
self.cells = cells # cells[y][x]
self.start = start
self.exit = exit_cell
def get_cell(self, x: int, y: int) -> Cell:
return self.cells[y][x]
def get_neighbors(self, cell: Cell) -> list[Cell]:
"""Возвращает список проходимых соседей (вверх, вниз, влево, вправо)."""
neighbors = []
for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
nx, ny = cell.x + dx, cell.y + dy
if 0 <= nx < self.width and 0 <= ny < self.height:
neighbor = self.cells[ny][nx]
if neighbor.is_passable():
neighbors.append(neighbor)
return neighbors
def __repr__(self):
lines = []
for row in self.cells:
lines.append("".join(str(c) for c in row))
return "\n".join(lines)