исправлены ошибки и проведено тестирование

This commit is contained in:
Proninvv 2026-05-20 22:52:01 +03:00
parent 324333c9aa
commit ad8ae841b1
2 changed files with 34 additions and 9 deletions

View File

@ -1,4 +1,6 @@
import time
from Maze import Maze
from strategy import PathFindingStrategy
class SearchStats:
@ -16,22 +18,32 @@ class SearchStats:
class MazeSolver:
def __init__(self, maze, strategy):
def __init__(self, maze: Maze, strategy: PathFindingStrategy):
self._maze = maze
self._strategy = strategy
self._observers = []
def addObserver(self, observer):
"""Регистрация нового наблюдателя (например, ConsoleView)"""
self._observers.append(observer)
def notify(self, event):
"""Уведомление всех подписчиков о событии"""
for observer in self._observers:
observer.update(event)
def setStrategy(self, strategy):
self._strategy = strategy
def solve(self):
if not self.maze or not self.strategy:
if not self._maze or not self._strategy:
raise ValueError("Не задан лабиринт или стратегия поиска!")
start_time = time.perf_counter()
path, visited_count = self.strategy.findPath(
self.maze, self.maze.start, self.maze.exit)
path, visited_count = self._strategy.findPath(
self._maze, self._maze.start, self._maze.exit)
end_time = time.perf_counter()
@ -39,4 +51,7 @@ class MazeSolver:
path_length = len(path)
from ConsoleView import Event
self.notify(Event("path_found", {"maze": self._maze, "path": path}))
return SearchStats(execution_time_ms, visited_count, path_length, path)

View File

@ -10,11 +10,13 @@ from DepthFirstSearch import DFSStrategy
from BreadthFirstSearch import BFSStrategy
from Deikstra import DeikstraFind
from AStarStrategy import AStarStrategy
from ConsoleView import ConsoleView
def run_benchmarks():
files = ["maze_small.txt", "maze_empty.txt",
"maze_no_exit.txt", "maze_medium.txt", "maze_large.txt"]
files = ["mazes/maze_small.txt", "mazes/maze_empty.txt",
"mazes/maze_no_exit.txt", "mazes/maze_medium.txt", "mazes/maze_large.txt"]
strategies = {
"BFS": BFSStrategy(),
"DFS": DFSStrategy(),
@ -22,6 +24,8 @@ def run_benchmarks():
"Deikstra": DeikstraFind()
}
view = ConsoleView()
NUM_RUNS = 5
results = []
@ -37,6 +41,7 @@ def run_benchmarks():
visited_counts = []
path_lengths = []
print(f" работает {name}")
for _ in range(NUM_RUNS):
# Пересоздаем лабиринт
builder = TextFileMazeBuilder()
@ -44,6 +49,9 @@ def run_benchmarks():
maze = builder.maze
solver = MazeSolver(maze, strategy)
solver.addObserver(view)
stats = solver.solve()
total_time += stats.execution_time
@ -64,7 +72,7 @@ def run_benchmarks():
})
# Запись в CSV
csv_file = "maze_benchmark_results.csv"
csv_file = "results/maze_benchmark_results.csv"
with open(csv_file, mode="w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=[
"лабиринт", "стратегия", "время_мс", "посещено_клеток", "длина_пути"])
@ -98,7 +106,8 @@ def plot_results(results):
ax.set_xticklabels(mazes, rotation=15)
ax.legend()
plt.tight_layout()
plt.savefig("benchmark_visited_cells.png", dpi=300)
plt.savefig("results/benchmark_visited_cells.png", dpi=200)
plt.savefig("results/benchmark_visited_cells.eps", dpi=200)
plt.close()
# График Время выполнения
@ -114,7 +123,8 @@ def plot_results(results):
ax.set_xticklabels(mazes, rotation=15)
ax.legend()
plt.tight_layout()
plt.savefig("benchmark_execution_time.png", dpi=300)
plt.savefig("results/benchmark_execution_time.png", dpi=200)
plt.savefig("results/benchmark_execution_time.eps", dpi=200)
plt.close()
print("Графики сохранены в текущую директорию.")