2026-rff_mp/SimonovaMS/lab2/maze_model.py
2026-05-02 06:49:44 +03:00

67 lines
1.8 KiB
Python

# maze_model.py
from __future__ import annotations
from typing import List, Optional
from dataclasses import dataclass
@dataclass
class Cell:
x: int
y: int
is_wall: bool = False
is_start: bool = False
is_exit: bool = False
def is_passable(self) -> bool:
return not self.is_wall
def __hash__(self) -> int:
return hash((self.x, self.y))
def __eq__(self, other) -> bool:
if not isinstance(other, Cell):
return False
return self.x == other.x and self.y == other.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 set_cell(self, x: int, y: int, cell: Cell) -> None:
if 0 <= x < self.width and 0 <= y < self.height:
self._cells[y][x] = cell
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 get_neighbors(self, cell: Cell) -> List[Cell]:
neighbors = []
# вверх, вниз, влево, вправо
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
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 get_all_cells(self) -> List[Cell]:
cells = []
for row in self._cells:
cells.extend(row)
return cells