63 lines
1.8 KiB
Python
63 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.is_wall = is_wall
|
|
self.is_start = is_start
|
|
self.is_exit = is_exit
|
|
|
|
def is_passable(self):
|
|
return not self.is_wall
|
|
|
|
def __repr__(self):
|
|
if self.is_wall:
|
|
return '#'
|
|
if self.is_start:
|
|
return 'S'
|
|
if self.is_exit:
|
|
return 'E'
|
|
return ' '
|
|
|
|
|
|
class Maze:
|
|
def __init__(self, width, height, cells, start, exit_cell):
|
|
self.width = width
|
|
self.height = height
|
|
self._cells = cells
|
|
self.start = start
|
|
self.exit = exit_cell
|
|
|
|
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):
|
|
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
|
|
neighbors = []
|
|
for dx, dy in directions:
|
|
neighbor = self.get_cell(cell.x + dx, cell.y + dy)
|
|
if neighbor is not None and neighbor.is_passable():
|
|
neighbors.append(neighbor)
|
|
return neighbors
|
|
|
|
def render(self, path=None, player_pos=None):
|
|
path_set = set((c.x, c.y) for c in path) if path else set()
|
|
|
|
for row in self._cells:
|
|
line = ''
|
|
for cell in row:
|
|
if player_pos and cell.x == player_pos.x and cell.y == player_pos.y:
|
|
line += 'P'
|
|
elif cell.is_wall:
|
|
line += '#'
|
|
elif cell.is_start:
|
|
line += 'S'
|
|
elif cell.is_exit:
|
|
line += 'E'
|
|
elif (cell.x, cell.y) in path_set:
|
|
line += '.'
|
|
else:
|
|
line += ' '
|
|
print(line)
|