68 lines
1.8 KiB
Python
68 lines
1.8 KiB
Python
class Cell:
|
|
def __init__(self, x, y, is_wall=False, is_start=False, is_exit=False):
|
|
self.x = x
|
|
self.y = y
|
|
self.isWall = is_wall
|
|
self.isStart = is_start
|
|
self.isExit = is_exit
|
|
|
|
def isPassable(self):
|
|
return not self.isWall
|
|
|
|
def __repr__(self):
|
|
return f"Cell({self.x},{self.y})"
|
|
|
|
def __eq__(self, other):
|
|
if isinstance(other, Cell) and self.x == other.x and self.y == other.y:
|
|
return True
|
|
return False
|
|
|
|
def __hash__(self):
|
|
return hash((self.x, self.y))
|
|
|
|
|
|
class Maze:
|
|
def __init__(self, width, height):
|
|
self.width = width
|
|
self.height = height
|
|
self.cells = []
|
|
self.start = None
|
|
self.exit = None
|
|
|
|
def add_row(self, row):
|
|
self.cells.append(row)
|
|
for cell in row:
|
|
if cell.isStart:
|
|
self.start = cell
|
|
if cell.isExit:
|
|
self.exit = cell
|
|
|
|
def getCell(self, x, y):
|
|
if 0 <= x < self.height and 0 <= y < self.width:
|
|
return self.cells[x][y]
|
|
return None
|
|
|
|
def getNeighbors(self, cell):
|
|
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
|
|
neighbors = []
|
|
for dx, dy in directions:
|
|
nx = cell.x + dx
|
|
ny = cell.y + dy
|
|
neighbor = self.getCell(nx, ny)
|
|
if neighbor != None and neighbor.isPassable():
|
|
neighbors.append(neighbor)
|
|
return neighbors
|
|
|
|
def printMaze(self):
|
|
for row in self.cells:
|
|
line = ""
|
|
for cell in row:
|
|
if cell.isStart:
|
|
line += "S"
|
|
elif cell.isExit:
|
|
line += "E"
|
|
elif cell.isWall:
|
|
line += "#"
|
|
else:
|
|
line += " "
|
|
print(line) |