начало реализации dfs, изменение соответствующей логики
This commit is contained in:
parent
0f5089fb24
commit
498d1250b9
|
|
@ -1,6 +1,8 @@
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
from source.classes.cell import Cell
|
||||||
|
|
||||||
|
|
||||||
class Event:
|
class Event:
|
||||||
def __init__(self, event, maze, player_position, path):
|
def __init__(self, event, maze, player_position, path):
|
||||||
|
|
@ -45,7 +47,27 @@ class ConsoleView(Observer):
|
||||||
|
|
||||||
|
|
||||||
def render(self, maze, player_position, path):
|
def render(self, maze, player_position, path):
|
||||||
|
if path and isinstance(path[0], tuple):
|
||||||
|
self.render_xy(maze=maze, player_position=player_position, path=path)
|
||||||
|
return
|
||||||
os.system('cls' if os.name == 'nt' else 'clear')
|
os.system('cls' if os.name == 'nt' else 'clear')
|
||||||
|
|
||||||
|
path_xy = [cell.getXY() for cell in path]
|
||||||
|
|
||||||
|
for line in maze.cells:
|
||||||
|
for c in line:
|
||||||
|
if c.getXY() == player_position:
|
||||||
|
print('P', end='')
|
||||||
|
elif c.getXY() in path_xy:
|
||||||
|
print('*', end='')
|
||||||
|
else:
|
||||||
|
print(c.toStr(), end='')
|
||||||
|
|
||||||
|
print()
|
||||||
|
|
||||||
|
def render_xy(self, maze, player_position, path: list[tuple[int, int]]):
|
||||||
|
os.system('cls' if os.name == 'nt' else 'clear')
|
||||||
|
# path_xy = [cell.getXY() for cell in path]
|
||||||
|
|
||||||
for line in maze.cells:
|
for line in maze.cells:
|
||||||
for c in line:
|
for c in line:
|
||||||
|
|
@ -55,5 +77,4 @@ class ConsoleView(Observer):
|
||||||
print('*', end='')
|
print('*', end='')
|
||||||
else:
|
else:
|
||||||
print(c.toStr(), end='')
|
print(c.toStr(), end='')
|
||||||
|
|
||||||
print()
|
print()
|
||||||
|
|
@ -2,7 +2,7 @@ from source.classes.cell import Cell
|
||||||
|
|
||||||
class Maze:
|
class Maze:
|
||||||
"""Лабиринт"""
|
"""Лабиринт"""
|
||||||
def __init__(self, cells, width, height, start, exit):
|
def __init__(self, cells, width: int, height: int, start: Cell, exit: Cell):
|
||||||
self.cells = cells
|
self.cells = cells
|
||||||
self.width = width
|
self.width = width
|
||||||
self.height = height
|
self.height = height
|
||||||
|
|
|
||||||
|
|
@ -1,50 +1,47 @@
|
||||||
from source.strategy.strategy import PathFindingStrategy
|
from source.strategy.strategy import PathFindingStrategy, reconstruct_path
|
||||||
from source.classes.maze import Maze
|
from source.classes.maze import Maze
|
||||||
from source.classes.cell import Cell
|
from source.classes.cell import Cell
|
||||||
|
|
||||||
class DFS(PathFindingStrategy):
|
class DFS(PathFindingStrategy):
|
||||||
def findPath(self, maze: Maze):
|
@property
|
||||||
pass
|
def name(self) -> str:
|
||||||
def name(self):
|
|
||||||
return "DFS"
|
return "DFS"
|
||||||
|
|
||||||
def __dfs__(self, maze: Maze):
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
# public static Cell SearchInDepth(Cell entry, Cell target)
|
|
||||||
# {
|
|
||||||
# Dictionary<int, Cell> visited = new Dictionary<int, Cell>();
|
|
||||||
# Stack<Cell> toVisit = new Stack<Cell>();
|
|
||||||
# entry.DistanceLeft = (target.Position - entry.Position).magnitude;
|
|
||||||
# toVisit.Push(entry);
|
|
||||||
# visualise(target, VisualAction.Target);
|
|
||||||
# visualise(entry, VisualAction.ToVisit);
|
|
||||||
|
|
||||||
# while (toVisit.Count > 0)
|
def findPath(self, maze: Maze) -> tuple[list[Cell], int]:
|
||||||
# {
|
start_cell = maze.start
|
||||||
# Cell current = toVisit.Pop();
|
exit_cell = maze.exit
|
||||||
# visualise(current, VisualAction.Visiting);
|
|
||||||
# if (current.Equals(target))
|
print(f"Старт: {start_cell.getXY()}")
|
||||||
# {
|
print(f"Выход: {exit_cell.getXY()}")
|
||||||
# return current;
|
print(f"Соседи старта: {[n.getXY() for n in maze.getNeighbors(start_cell)]}")
|
||||||
# }
|
|
||||||
# visited.Add(current.GetHashCode(), current);
|
stack = [start_cell]
|
||||||
# List<Cell> neighbours = GetNeighbours(current);
|
|
||||||
# foreach (Cell neighbour in neighbours)
|
parents = {start_cell.getXY(): Cell(-1, -1)}
|
||||||
# {
|
visited = {start_cell.getXY()}
|
||||||
# if (!visited.ContainsKey(neighbour.GetHashCode()) && !toVisit.Contains(neighbour))
|
count_visited = 0
|
||||||
# {
|
|
||||||
# neighbour.DistanceLeft = (target.Position - neighbour.Position).magnitude;
|
while stack:
|
||||||
# toVisit.Push(neighbour);
|
current = stack.pop()
|
||||||
# visualise(neighbour, VisualAction.ToVisit);
|
|
||||||
# }
|
if current.getXY() == exit_cell.getXY():
|
||||||
# }
|
return reconstruct_path(
|
||||||
|
came_from=parents,
|
||||||
# visualise(current, VisualAction.Visited);
|
start=start_cell,
|
||||||
# }
|
end=current
|
||||||
# return null;
|
), count_visited
|
||||||
# }
|
|
||||||
|
neigbours = maze.getNeighbors(current)
|
||||||
|
print(f"для клекти {current.getXY()} соседи: {[neigbour.getXY() for neigbour in neigbours]}")
|
||||||
|
|
||||||
|
for neighbor in maze.getNeighbors(current):
|
||||||
|
neig_xy = neighbor.getXY()
|
||||||
|
|
||||||
|
if neig_xy not in visited:
|
||||||
|
visited.add(neig_xy)
|
||||||
|
parents[neig_xy] = current
|
||||||
|
count_visited += 1
|
||||||
|
# new_path = current_path + [neigbour]
|
||||||
|
stack.append(neighbor)
|
||||||
|
|
||||||
|
return [], count_visited
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
||||||
from source.strategy.strategy import SearchStats, PathFindingStrategy
|
from source.strategy.strategy import PathFindingStrategy
|
||||||
|
from source.classes.cell import Cell
|
||||||
|
|
||||||
class MazeSolver:
|
class MazeSolver:
|
||||||
def __init__(self, maze, strategy: PathFindingStrategy):
|
def __init__(self, maze, strategy: PathFindingStrategy):
|
||||||
|
|
@ -22,14 +23,16 @@ class MazeSolver:
|
||||||
return SearchStats(
|
return SearchStats(
|
||||||
timeMs=finish_time - start_time,
|
timeMs=finish_time - start_time,
|
||||||
visitedCells=visited_cells,
|
visitedCells=visited_cells,
|
||||||
pathLength=len(path)
|
pathLength=len(path),
|
||||||
|
path=path
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class SearchStats:
|
class SearchStats:
|
||||||
"""Общая информация о тесте алгоритма"""
|
"""Общая информация о тесте алгоритма"""
|
||||||
def __init__(self, timeMs: float, visitedCells: int, pathLength: int):
|
def __init__(self, timeMs: float, visitedCells: int, pathLength: int, path: list[Cell]):
|
||||||
self.timeMs = timeMs
|
self.timeMs = timeMs
|
||||||
self.visitedCells = visitedCells
|
self.visitedCells = visitedCells
|
||||||
self.pathLength = pathLength
|
self.pathLength = pathLength
|
||||||
|
self.path = path
|
||||||
|
|
@ -20,3 +20,23 @@ class PathFindingStrategy(ABC):
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class CellAlgorithm(Cell):
|
||||||
|
def __init__(self, x: int, y: int, parent: Cell, exitDist: float, isWall=False, isStart=False, isExit=False, value=1):
|
||||||
|
super().__init__(x, y, isWall, isStart, isExit, value)
|
||||||
|
self.parent = parent
|
||||||
|
self.ExitDist = exitDist
|
||||||
|
self.weight = self.value + exitDist
|
||||||
|
|
||||||
|
|
||||||
|
def reconstruct_path(came_from: dict, start: Cell, end: Cell) -> list[Cell]:
|
||||||
|
"""Восстановление пути по словарю предшественников"""
|
||||||
|
path = []
|
||||||
|
current = end
|
||||||
|
|
||||||
|
# Идём от конца к началу по цепочке came_from
|
||||||
|
while current.getXY() != start.getXY():
|
||||||
|
path.append(current)
|
||||||
|
current = came_from[current.getXY()]
|
||||||
|
|
||||||
|
path.append(start)
|
||||||
|
return path[::-1]
|
||||||
|
|
@ -65,7 +65,7 @@
|
||||||
"output_type": "stream",
|
"output_type": "stream",
|
||||||
"text": [
|
"text": [
|
||||||
"Загружен лабиринт:\n",
|
"Загружен лабиринт:\n",
|
||||||
"**P# ###\n",
|
"\u001b[H\u001b[2J**P# ###\n",
|
||||||
"## # # E\n",
|
"## # # E\n",
|
||||||
"# # #\n",
|
"# # #\n",
|
||||||
"### ## #\n",
|
"### ## #\n",
|
||||||
|
|
@ -89,10 +89,66 @@
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"id": "857c5c04",
|
"id": "19840429",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": []
|
"source": [
|
||||||
|
"from source.strategy.DFS import DFS\n",
|
||||||
|
"from source.strategy.maze_solver import MazeSolver\n",
|
||||||
|
"\n",
|
||||||
|
"strat = MazeSolver(maze, DFS())\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"id": "857c5c04",
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"0\n",
|
||||||
|
"2\n",
|
||||||
|
"1\n",
|
||||||
|
"3\n",
|
||||||
|
"4\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"{'0', '1', '2', '3', '4'}"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"def dfs(graph, start, visited=None):\n",
|
||||||
|
" if visited is None:\n",
|
||||||
|
" visited = set()\n",
|
||||||
|
" visited.add(start)\n",
|
||||||
|
"\n",
|
||||||
|
" print(start)\n",
|
||||||
|
"\n",
|
||||||
|
" for next in graph[start] - visited:\n",
|
||||||
|
" dfs(graph, next, visited)\n",
|
||||||
|
" return visited\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"graph = {'0': set(['1', '2']),\n",
|
||||||
|
" '1': set(['0', '3', '4']),\n",
|
||||||
|
" '2': set(['0']),\n",
|
||||||
|
" '3': set(['1']),\n",
|
||||||
|
" '4': set(['2', '3'])}\n",
|
||||||
|
"\n",
|
||||||
|
"dfs(graph, '0')"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
|
|
@ -111,7 +167,7 @@
|
||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.10.6"
|
"version": "3.14.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user