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

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 import time
from Maze import Maze
from strategy import PathFindingStrategy
class SearchStats: class SearchStats:
@ -16,22 +18,32 @@ class SearchStats:
class MazeSolver: class MazeSolver:
def __init__(self, maze, strategy): def __init__(self, maze: Maze, strategy: PathFindingStrategy):
self._maze = maze self._maze = maze
self._strategy = strategy 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): def setStrategy(self, strategy):
self._strategy = strategy self._strategy = strategy
def solve(self): def solve(self):
if not self.maze or not self.strategy: if not self._maze or not self._strategy:
raise ValueError("Не задан лабиринт или стратегия поиска!") raise ValueError("Не задан лабиринт или стратегия поиска!")
start_time = time.perf_counter() start_time = time.perf_counter()
path, visited_count = self.strategy.findPath( path, visited_count = self._strategy.findPath(
self.maze, self.maze.start, self.maze.exit) self._maze, self._maze.start, self._maze.exit)
end_time = time.perf_counter() end_time = time.perf_counter()
@ -39,4 +51,7 @@ class MazeSolver:
path_length = len(path) 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) 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 BreadthFirstSearch import BFSStrategy
from Deikstra import DeikstraFind from Deikstra import DeikstraFind
from AStarStrategy import AStarStrategy from AStarStrategy import AStarStrategy
from ConsoleView import ConsoleView
def run_benchmarks(): 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 = { strategies = {
"BFS": BFSStrategy(), "BFS": BFSStrategy(),
"DFS": DFSStrategy(), "DFS": DFSStrategy(),
@ -22,6 +24,8 @@ def run_benchmarks():
"Deikstra": DeikstraFind() "Deikstra": DeikstraFind()
} }
view = ConsoleView()
NUM_RUNS = 5 NUM_RUNS = 5
results = [] results = []
@ -37,6 +41,7 @@ def run_benchmarks():
visited_counts = [] visited_counts = []
path_lengths = [] path_lengths = []
print(f" работает {name}")
for _ in range(NUM_RUNS): for _ in range(NUM_RUNS):
# Пересоздаем лабиринт # Пересоздаем лабиринт
builder = TextFileMazeBuilder() builder = TextFileMazeBuilder()
@ -44,6 +49,9 @@ def run_benchmarks():
maze = builder.maze maze = builder.maze
solver = MazeSolver(maze, strategy) solver = MazeSolver(maze, strategy)
solver.addObserver(view)
stats = solver.solve() stats = solver.solve()
total_time += stats.execution_time total_time += stats.execution_time
@ -64,7 +72,7 @@ def run_benchmarks():
}) })
# Запись в CSV # Запись в 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: with open(csv_file, mode="w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=[ writer = csv.DictWriter(f, fieldnames=[
"лабиринт", "стратегия", "время_мс", "посещено_клеток", "длина_пути"]) "лабиринт", "стратегия", "время_мс", "посещено_клеток", "длина_пути"])
@ -98,7 +106,8 @@ def plot_results(results):
ax.set_xticklabels(mazes, rotation=15) ax.set_xticklabels(mazes, rotation=15)
ax.legend() ax.legend()
plt.tight_layout() 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() plt.close()
# График Время выполнения # График Время выполнения
@ -114,7 +123,8 @@ def plot_results(results):
ax.set_xticklabels(mazes, rotation=15) ax.set_xticklabels(mazes, rotation=15)
ax.legend() ax.legend()
plt.tight_layout() 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() plt.close()
print("Графики сохранены в текущую директорию.") print("Графики сохранены в текущую директорию.")