Добавил реализацию для классов

- Cell
- Maze
- TextFileMazeBuilder
This commit is contained in:
GordStep 2026-05-20 13:05:52 +03:00
parent 3fbb3cf061
commit c9448652cf
5 changed files with 244 additions and 0 deletions

View File

@ -0,0 +1,64 @@
from abc import ABC, abstractmethod
from source.classes.maze import Maze
from source.classes.cell import Cell
class MazeBuilder(ABC):
@abstractmethod
def buildFromFile(self, filename: str) -> Maze:
pass
class TextFileMazeBuilder(MazeBuilder):
def buildFromFile(self, filename: str) -> Maze:
with open(filename) as f:
data = f.read().splitlines()
x, y = 0, 0
width = len(data[0])
height = len(data)
cells = [[None] * width for _ in range(height)]
start, c_exit = None, None
for line in data:
x = 0
for c in line.strip():
if c == 'S':
cells[y][x] = Cell(x, y, isStart=True)
start = cells[y][x]
x += 1
elif c == 'E':
cells[y][x] = Cell(x, y, isExit=True)
c_exit = cells[y][x]
x += 1
elif c == '#':
cells[y][x] = Cell(x, y, isWall=True)
x += 1
elif c == ' ':
cells[y][x] = Cell(x, y)
x += 1
else:
print(f'Обнаружен неизвестный символ({c}) в файле лабиринта\nfilename: {filename}\nОн заменён на стену')
cells[y][x] = Cell(x, y, isWall=True)
x += 1
y += 1
if start == None:
raise ValueError(f'В файле лабиринта не обнаружен вход!\nfilename: {filename}')
if c_exit == None:
raise ValueError(f'В файле лабиринта не обнаружен выход!\nfilename: {filename}')
return Maze(
cells=cells,
width=width,
height=height,
start=start,
exit=c_exit
)

View File

@ -0,0 +1,38 @@
class Cell:
def __init__(self, x, y, isWall=False, isStart=False, isExit=False):
self.__x = x
self.__y = y
self.isWall = isWall
self.isStart = isStart
self.isExit = isExit
pass
@property
def isPassable(self) -> bool:
"""возвращает `True` для прохода, если клетка не стена"""
return not self.isWall
@property
def x(self) -> int:
"""Возвращает координату клетки по оси X"""
return self.__x
@property
def y(self) -> int:
"""Возвращает координату клетки по оси Y"""
return self.__y
def getXY(self) -> tuple[int, int]:
"""Возвращает кортеж координат в формате `(x, y)`"""
return self.__x, self.__y
def toStr(self):
if self.isWall:
return '#'
elif self.isStart:
return 'S'
elif self.isExit:
return 'E'
else:
return ' '

View File

@ -0,0 +1,39 @@
from source.classes.cell import Cell
class Maze:
def __init__(self, cells, width, height, start, exit):
self.cells = cells
self.width = width
self.height = height
self.start = start
self.exit = exit
pass
def getCell(self, x, y) -> Cell:
return self.cells[x][y]
def getNeighbors(self, cell) -> list[Cell]:
neighbors = []
c_x, c_y = cell.getXY()
if c_x - 1 >= 0 and not self.cells[c_x - 1][c_y].isWall:
neighbors.append(self.cells[c_x - 1][c_y])
if c_x + 1 < self.width and not self.cells[c_x + 1][c_y].isWall:
neighbors.append(self.cells[c_x + 1][c_y])
if c_y - 1 >= 0 and not self.cells[c_x][c_y - 1].isWall:
neighbors.append(self.cells[c_x][c_y - 1])
if c_y + 1 < self.height and not self.cells[c_x][c_y + 1].isWall:
neighbors.append(self.cells[c_x][c_y + 1])
return neighbors
def printer(self):
for line in self.cells:
for c in line:
print(c.toStr(), end='')
print()

View File

@ -0,0 +1,97 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "4489fc7e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S # ###\n",
"## # # E\n",
"# # #\n",
"### ## #\n",
"# #\n",
"########\n"
]
}
],
"source": [
"with open('test_lab.txt') as f:\n",
" data = f.readlines()\n",
" for el in data:\n",
" print(el.rstrip())"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fde1eddb",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S#####\n",
" # # #\n",
" # #\n",
"## #\n",
" # #\n",
"#### #\n",
"# #\n",
"#E####\n"
]
}
],
"source": [
"from source.classes.builder import TextFileMazeBuilder\n",
"\n",
"builder = TextFileMazeBuilder()\n",
"maze = builder.buildFromFile(filename='test_lab.txt')\n",
"\n",
"maze.printer()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "22325f68",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "857c5c04",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,6 @@
S # ###
## # # E
# # #
### ## #
# #
########