forked from UNN/2026-rff_mp
Compare commits
No commits in common. "LarikovaAA-task2" and "develop" have entirely different histories.
LarikovaAA
...
develop
BIN
LarikovaAA/.DS_Store
vendored
BIN
LarikovaAA/.DS_Store
vendored
Binary file not shown.
BIN
LarikovaAA/task2/.DS_Store
vendored
BIN
LarikovaAA/task2/.DS_Store
vendored
Binary file not shown.
|
|
@ -1,56 +0,0 @@
|
||||||
from abc import ABC, abstractmethod
|
|
||||||
from models import Cell, Maze
|
|
||||||
|
|
||||||
|
|
||||||
class MazeBuilder(ABC):
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def build_from_file(self, filename: str) -> Maze:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class TextFileMazeBuilder(MazeBuilder):
|
|
||||||
|
|
||||||
WALL_CHAR = '#'
|
|
||||||
START_CHAR = 'S'
|
|
||||||
EXIT_CHAR = 'E'
|
|
||||||
PASS_CHAR = ' '
|
|
||||||
|
|
||||||
def build_from_file(self, filename: str) -> Maze:
|
|
||||||
with open(filename, 'r', encoding='utf-8') as f:
|
|
||||||
lines = [line.rstrip('\n') for line in f.readlines()]
|
|
||||||
|
|
||||||
if not lines:
|
|
||||||
raise ValueError("Файл с лабиринтом пуст")
|
|
||||||
|
|
||||||
height = len(lines)
|
|
||||||
width = max(len(line) for line in lines)
|
|
||||||
|
|
||||||
maze = Maze(width, height)
|
|
||||||
|
|
||||||
for y, line in enumerate(lines):
|
|
||||||
for x, ch in enumerate(line):
|
|
||||||
if x >= width:
|
|
||||||
continue
|
|
||||||
|
|
||||||
cell = Cell(x, y)
|
|
||||||
|
|
||||||
if ch == self.WALL_CHAR:
|
|
||||||
cell.is_wall = True
|
|
||||||
elif ch == self.START_CHAR:
|
|
||||||
cell.is_start = True
|
|
||||||
elif ch == self.EXIT_CHAR:
|
|
||||||
cell.is_exit = True
|
|
||||||
elif ch == self.PASS_CHAR:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
cell.is_wall = True
|
|
||||||
|
|
||||||
maze.set_cell(x, y, cell)
|
|
||||||
|
|
||||||
if maze.start is None:
|
|
||||||
raise ValueError("В лабиринте нет стартовой клетки (S)")
|
|
||||||
if maze.exit is None:
|
|
||||||
raise ValueError("В лабиринте нет выхода (E)")
|
|
||||||
|
|
||||||
return maze
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
from abc import ABC, abstractmethod
|
|
||||||
from typing import Optional
|
|
||||||
from models import Cell, Maze
|
|
||||||
|
|
||||||
|
|
||||||
class Player:
|
|
||||||
|
|
||||||
def __init__(self, start_cell: Cell):
|
|
||||||
self.current_cell = start_cell
|
|
||||||
|
|
||||||
def move_to(self, new_cell: Cell) -> None:
|
|
||||||
self.current_cell = new_cell
|
|
||||||
|
|
||||||
|
|
||||||
class Command(ABC):
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def execute(self) -> bool:
|
|
||||||
pass
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def undo(self) -> None:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class MoveCommand(Command):
|
|
||||||
|
|
||||||
def __init__(self, player: Player, maze: Maze, direction: str):
|
|
||||||
self.player = player
|
|
||||||
self.maze = maze
|
|
||||||
self.direction = direction
|
|
||||||
self.previous_cell: Optional[Cell] = None
|
|
||||||
self.new_cell: Optional[Cell] = None
|
|
||||||
|
|
||||||
def _get_target_cell(self) -> Optional[Cell]:
|
|
||||||
x, y = self.player.current_cell.x, self.player.current_cell.y
|
|
||||||
|
|
||||||
if self.direction == 'w':
|
|
||||||
y -= 1
|
|
||||||
elif self.direction == 's':
|
|
||||||
y += 1
|
|
||||||
elif self.direction == 'a':
|
|
||||||
x -= 1
|
|
||||||
elif self.direction == 'd':
|
|
||||||
x += 1
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return self.maze.get_cell(x, y)
|
|
||||||
|
|
||||||
def execute(self) -> bool:
|
|
||||||
self.previous_cell = self.player.current_cell
|
|
||||||
self.new_cell = self._get_target_cell()
|
|
||||||
|
|
||||||
if self.new_cell and self.new_cell.is_passable():
|
|
||||||
self.player.move_to(self.new_cell)
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
def undo(self) -> None:
|
|
||||||
if self.previous_cell:
|
|
||||||
self.player.move_to(self.previous_cell)
|
|
||||||
Binary file not shown.
|
|
@ -1,13 +0,0 @@
|
||||||
maze_file,maze_size,strategy,time_mean,time_min,time_max,visited_mean,path_length_mean,path_found
|
|
||||||
small.txt,10×10,BFS,0.14973321231082082,0.08187501225620508,0.3416250110603869,15.0,15.0,True
|
|
||||||
small.txt,10×10,DFS,0.05074121290817857,0.036958022974431515,0.09620800847187638,21.0,21.0,True
|
|
||||||
small.txt,10×10,A*,0.11340839555487037,0.07800001185387373,0.24145899806171656,15.0,15.0,True
|
|
||||||
medium.txt,20×11,BFS,0.28489179676398635,0.21541700698435307,0.3855000250041485,26.0,26.0,True
|
|
||||||
medium.txt,20×11,DFS,0.22732499055564404,0.16850000247359276,0.396291958168149,90.0,90.0,True
|
|
||||||
medium.txt,20×11,A*,0.2952334121800959,0.290708034299314,0.30733400490134954,26.0,26.0,True
|
|
||||||
large.txt,30×15,BFS,0.5741997971199453,0.4562910180538893,0.8350000134669244,40.0,40.0,True
|
|
||||||
large.txt,30×15,DFS,0.4984830040484667,0.38241699803620577,0.6361660198308527,196.0,196.0,True
|
|
||||||
large.txt,30×15,A*,0.6602250039577484,0.6104999920353293,0.7946669938974082,40.0,40.0,True
|
|
||||||
empty.txt,30×1,BFS,0.06608341354876757,0.04250003257766366,0.11475000064820051,30.0,30.0,True
|
|
||||||
empty.txt,30×1,DFS,0.048741791397333145,0.039041973650455475,0.06312498589977622,30.0,30.0,True
|
|
||||||
empty.txt,30×1,A*,0.06089139496907592,0.055582961067557335,0.07212499622255564,30.0,30.0,True
|
|
||||||
|
Binary file not shown.
|
Before Width: | Height: | Size: 61 KiB |
|
|
@ -1,94 +0,0 @@
|
||||||
import csv
|
|
||||||
import time
|
|
||||||
from typing import List, Dict
|
|
||||||
from models import Maze
|
|
||||||
from builders import TextFileMazeBuilder
|
|
||||||
from strategies import BFSStrategy, DFSStrategy, AStarStrategy
|
|
||||||
from solver import MazeSolver
|
|
||||||
|
|
||||||
|
|
||||||
def run_experiment(maze: Maze, strategy_name: str, strategy, repeats: int = 5) -> Dict:
|
|
||||||
times = []
|
|
||||||
visited_counts = []
|
|
||||||
path_lengths = []
|
|
||||||
path_found = True
|
|
||||||
|
|
||||||
for _ in range(repeats):
|
|
||||||
solver = MazeSolver(maze, strategy)
|
|
||||||
path, stats = solver.solve()
|
|
||||||
|
|
||||||
times.append(stats.time_ms)
|
|
||||||
visited_counts.append(stats.visited_cells)
|
|
||||||
path_lengths.append(stats.path_length)
|
|
||||||
path_found = stats.path_found
|
|
||||||
|
|
||||||
return {
|
|
||||||
'strategy': strategy_name,
|
|
||||||
'time_mean': sum(times) / len(times),
|
|
||||||
'time_min': min(times),
|
|
||||||
'time_max': max(times),
|
|
||||||
'visited_mean': sum(visited_counts) / len(visited_counts),
|
|
||||||
'path_length_mean': sum(path_lengths) / len(path_lengths) if path_found else 0,
|
|
||||||
'path_found': path_found
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def run_all_experiments(maze_files: List[str], repeats: int = 5) -> List[Dict]:
|
|
||||||
builder = TextFileMazeBuilder()
|
|
||||||
strategies = [
|
|
||||||
('BFS', BFSStrategy()),
|
|
||||||
('DFS', DFSStrategy()),
|
|
||||||
('A*', AStarStrategy())
|
|
||||||
]
|
|
||||||
|
|
||||||
results = []
|
|
||||||
|
|
||||||
for maze_file in maze_files:
|
|
||||||
try:
|
|
||||||
maze = builder.build_from_file(maze_file)
|
|
||||||
except (ValueError, FileNotFoundError) as e:
|
|
||||||
print(f" Ошибка: {e}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
print(f" Размер: {maze.width}×{maze.height}")
|
|
||||||
print(f" Старт: ({maze.start.x}, {maze.start.y})")
|
|
||||||
print(f" Выход: ({maze.exit.x}, {maze.exit.y})")
|
|
||||||
|
|
||||||
for strategy_name, strategy in strategies:
|
|
||||||
print(f" Тестирование: {strategy_name}")
|
|
||||||
result = run_experiment(maze, strategy_name, strategy, repeats)
|
|
||||||
result['maze_file'] = maze_file.split('/')[-1]
|
|
||||||
result['maze_size'] = f"{maze.width}×{maze.height}"
|
|
||||||
results.append(result)
|
|
||||||
|
|
||||||
status = "ok" if result['path_found'] else "ne ok"
|
|
||||||
print(f" {status} Время: {result['time_mean']:.2f} мс, "
|
|
||||||
f"Посещено: {result['visited_mean']:.0f}, "
|
|
||||||
f"Путь: {result['path_length_mean']:.0f}")
|
|
||||||
|
|
||||||
return results
|
|
||||||
|
|
||||||
|
|
||||||
def save_results_to_csv(results: List[Dict], filename: str = "experiment_results.csv") -> None:
|
|
||||||
with open(filename, 'w', newline='', encoding='utf-8') as f:
|
|
||||||
writer = csv.DictWriter(f, fieldnames=[
|
|
||||||
'maze_file', 'maze_size', 'strategy',
|
|
||||||
'time_mean', 'time_min', 'time_max',
|
|
||||||
'visited_mean', 'path_length_mean', 'path_found'
|
|
||||||
])
|
|
||||||
writer.writeheader()
|
|
||||||
writer.writerows(results)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def print_results_table(results: List[Dict]) -> None:
|
|
||||||
print("\n" + "=" * 80)
|
|
||||||
print("РЕЗУЛЬТАТЫ ЭКСПЕРИМЕНТОВ")
|
|
||||||
print("=" * 80)
|
|
||||||
|
|
||||||
for res in results:
|
|
||||||
print(f"\nЛабиринт: {res['maze_file']}")
|
|
||||||
print(f" Стратегия: {res['strategy']}")
|
|
||||||
print(f" Время (ср): {res['time_mean']:.2f} мс")
|
|
||||||
print(f" Посещено: {res['visited_mean']:.0f} клеток")
|
|
||||||
print(f" Длина пути: {res['path_length_mean']:.0f}")
|
|
||||||
|
|
@ -1,146 +0,0 @@
|
||||||
import os
|
|
||||||
from builders import TextFileMazeBuilder
|
|
||||||
from strategies import BFSStrategy, DFSStrategy, AStarStrategy
|
|
||||||
from solver import MazeSolver
|
|
||||||
from observers import ConsoleView
|
|
||||||
from commands import Player
|
|
||||||
from experiments import run_all_experiments, save_results_to_csv, print_results_table
|
|
||||||
|
|
||||||
|
|
||||||
def create_test_mazes():
|
|
||||||
os.makedirs("mazes", exist_ok=True)
|
|
||||||
|
|
||||||
small = """##########
|
|
||||||
#S #
|
|
||||||
# ### ## #
|
|
||||||
# # #
|
|
||||||
### # ####
|
|
||||||
# # #
|
|
||||||
# ### # #
|
|
||||||
# # #
|
|
||||||
# # E#
|
|
||||||
##########"""
|
|
||||||
|
|
||||||
medium = """####################
|
|
||||||
#S #
|
|
||||||
# # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # #
|
|
||||||
# E#
|
|
||||||
####################"""
|
|
||||||
|
|
||||||
large = """##############################
|
|
||||||
#S #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# E#
|
|
||||||
##############################"""
|
|
||||||
|
|
||||||
empty = "S" + " " * 28 + "E"
|
|
||||||
|
|
||||||
no_exit = """#######
|
|
||||||
#S #
|
|
||||||
# ### #
|
|
||||||
# # #
|
|
||||||
#######"""
|
|
||||||
|
|
||||||
with open("mazes/small.txt", "w") as f:
|
|
||||||
f.write(small)
|
|
||||||
with open("mazes/medium.txt", "w") as f:
|
|
||||||
f.write(medium)
|
|
||||||
with open("mazes/large.txt", "w") as f:
|
|
||||||
f.write(large)
|
|
||||||
with open("mazes/empty.txt", "w") as f:
|
|
||||||
f.write(empty)
|
|
||||||
with open("mazes/no_exit.txt", "w") as f:
|
|
||||||
f.write(no_exit)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def demo_maze_solver():
|
|
||||||
print("\n" + "=" * 60)
|
|
||||||
print("ДЕМОНСТРАЦИЯ РАБОТЫ MAZE SOLVER")
|
|
||||||
print("=" * 60)
|
|
||||||
|
|
||||||
builder = TextFileMazeBuilder()
|
|
||||||
view = ConsoleView()
|
|
||||||
|
|
||||||
maze = builder.build_from_file("mazes/small.txt")
|
|
||||||
view.update("maze_loaded", {"maze": maze})
|
|
||||||
|
|
||||||
strategies = [
|
|
||||||
("BFS", BFSStrategy(), "BFS"),
|
|
||||||
("DFS", DFSStrategy(), "DFSs"),
|
|
||||||
("A*", AStarStrategy(), "A*")
|
|
||||||
]
|
|
||||||
|
|
||||||
for name, strategy, description in strategies:
|
|
||||||
solver = MazeSolver(maze, strategy)
|
|
||||||
view.update("search_start", {"algorithm": description})
|
|
||||||
|
|
||||||
path, stats = solver.solve()
|
|
||||||
|
|
||||||
if stats.path_found:
|
|
||||||
view.update("path_found", {"maze": maze, "path": path, "stats": stats})
|
|
||||||
else:
|
|
||||||
view.update("no_path", {"stats": stats})
|
|
||||||
|
|
||||||
|
|
||||||
def demo_player_controls():
|
|
||||||
print("\n" + "=" * 60)
|
|
||||||
print("Command + Observer")
|
|
||||||
print("=" * 60)
|
|
||||||
|
|
||||||
builder = TextFileMazeBuilder()
|
|
||||||
view = ConsoleView()
|
|
||||||
maze = builder.build_from_file("mazes/small.txt")
|
|
||||||
|
|
||||||
player = Player(maze.start)
|
|
||||||
|
|
||||||
view.update("maze_loaded", {"maze": maze})
|
|
||||||
view.render(maze, player_position=player.current_cell)
|
|
||||||
|
|
||||||
|
|
||||||
def run_experiments():
|
|
||||||
print("\n" + "=" * 60)
|
|
||||||
print("ЭКСПЕРИМЕНТАЛЬНОЕ СРАВНЕНИЕ АЛГОРИТМОВ")
|
|
||||||
print("=" * 60)
|
|
||||||
|
|
||||||
maze_files = [
|
|
||||||
"mazes/small.txt",
|
|
||||||
"mazes/medium.txt",
|
|
||||||
"mazes/large.txt",
|
|
||||||
"mazes/empty.txt",
|
|
||||||
"mazes/no_exit.txt"
|
|
||||||
]
|
|
||||||
|
|
||||||
results = run_all_experiments(maze_files, repeats=5)
|
|
||||||
save_results_to_csv(results)
|
|
||||||
print_results_table(results)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
print("Объектно-ориентированная реализация с паттернами")
|
|
||||||
print("Паттерны: Builder, Strategy, Observer, Command")
|
|
||||||
|
|
||||||
create_test_mazes()
|
|
||||||
demo_maze_solver()
|
|
||||||
demo_player_controls()
|
|
||||||
run_experiments()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
S E
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
##############################
|
|
||||||
#S #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # # # # # # #
|
|
||||||
# E#
|
|
||||||
##############################
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
####################
|
|
||||||
#S #
|
|
||||||
# # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # #
|
|
||||||
# #
|
|
||||||
# # # # # # # # # #
|
|
||||||
# E#
|
|
||||||
####################
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
#######
|
|
||||||
#S #
|
|
||||||
# ### #
|
|
||||||
# # #
|
|
||||||
#######
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
##########
|
|
||||||
#S #
|
|
||||||
# ### ## #
|
|
||||||
# # #
|
|
||||||
### # ####
|
|
||||||
# # #
|
|
||||||
# ### # #
|
|
||||||
# # #
|
|
||||||
# # E#
|
|
||||||
##########
|
|
||||||
|
|
@ -1,79 +0,0 @@
|
||||||
from typing import List, Optional
|
|
||||||
|
|
||||||
|
|
||||||
class Cell:
|
|
||||||
|
|
||||||
def __init__(self, x: int, y: int):
|
|
||||||
self.x = x
|
|
||||||
self.y = y
|
|
||||||
self.is_wall = False
|
|
||||||
self.is_start = False
|
|
||||||
self.is_exit = False
|
|
||||||
|
|
||||||
def is_passable(self) -> bool:
|
|
||||||
return not self.is_wall
|
|
||||||
|
|
||||||
def __eq__(self, other) -> bool:
|
|
||||||
if not isinstance(other, Cell):
|
|
||||||
return False
|
|
||||||
return self.x == other.x and self.y == other.y
|
|
||||||
|
|
||||||
def __hash__(self):
|
|
||||||
return hash((self.x, self.y))
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
return f"Cell({self.x}, {self.y})"
|
|
||||||
|
|
||||||
|
|
||||||
class Maze:
|
|
||||||
|
|
||||||
def __init__(self, width: int, height: int):
|
|
||||||
self.width = width
|
|
||||||
self.height = height
|
|
||||||
self._cells: List[List[Optional[Cell]]] = [[None for _ in range(width)] for _ in range(height)]
|
|
||||||
self.start: Optional[Cell] = None
|
|
||||||
self.exit: Optional[Cell] = None
|
|
||||||
|
|
||||||
def set_cell(self, x: int, y: int, cell: Cell) -> None:
|
|
||||||
if 0 <= x < self.width and 0 <= y < self.height:
|
|
||||||
self._cells[y][x] = cell
|
|
||||||
if cell.is_start:
|
|
||||||
self.start = cell
|
|
||||||
if cell.is_exit:
|
|
||||||
self.exit = cell
|
|
||||||
|
|
||||||
def get_cell(self, x: int, y: int) -> Optional[Cell]:
|
|
||||||
if 0 <= x < self.width and 0 <= y < self.height:
|
|
||||||
return self._cells[y][x]
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_neighbors(self, cell: Cell) -> List[Cell]:
|
|
||||||
neighbors = []
|
|
||||||
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
|
|
||||||
|
|
||||||
for dx, dy in directions:
|
|
||||||
nx, ny = cell.x + dx, cell.y + dy
|
|
||||||
neighbor = self.get_cell(nx, ny)
|
|
||||||
if neighbor and neighbor.is_passable():
|
|
||||||
neighbors.append(neighbor)
|
|
||||||
|
|
||||||
return neighbors
|
|
||||||
|
|
||||||
def __str__(self) -> str:
|
|
||||||
result = []
|
|
||||||
for y in range(self.height):
|
|
||||||
row = []
|
|
||||||
for x in range(self.width):
|
|
||||||
cell = self.get_cell(x, y)
|
|
||||||
if cell is None:
|
|
||||||
row.append('?')
|
|
||||||
elif cell.is_start:
|
|
||||||
row.append('S')
|
|
||||||
elif cell.is_exit:
|
|
||||||
row.append('E')
|
|
||||||
elif cell.is_wall:
|
|
||||||
row.append('#')
|
|
||||||
else:
|
|
||||||
row.append(' ')
|
|
||||||
result.append(''.join(row))
|
|
||||||
return '\n'.join(result)
|
|
||||||
|
|
@ -1,66 +0,0 @@
|
||||||
from abc import ABC, abstractmethod
|
|
||||||
from typing import List, Optional
|
|
||||||
from models import Cell, Maze
|
|
||||||
|
|
||||||
|
|
||||||
class Observer(ABC):
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def update(self, event: str, data: dict) -> None:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class ConsoleView(Observer):
|
|
||||||
|
|
||||||
def render(self, maze: Maze, player_position: Optional[Cell] = None, path: Optional[List[Cell]] = None) -> None:
|
|
||||||
path_set = set(path) if path else set()
|
|
||||||
|
|
||||||
print("\n+" + "-" * maze.width + "+")
|
|
||||||
|
|
||||||
for y in range(maze.height):
|
|
||||||
row = []
|
|
||||||
for x in range(maze.width):
|
|
||||||
cell = maze.get_cell(x, y)
|
|
||||||
if cell is None:
|
|
||||||
row.append('?')
|
|
||||||
elif player_position and cell == player_position:
|
|
||||||
row.append('@')
|
|
||||||
elif cell.is_start:
|
|
||||||
row.append('S')
|
|
||||||
elif cell.is_exit:
|
|
||||||
row.append('E')
|
|
||||||
elif cell in path_set:
|
|
||||||
row.append('*')
|
|
||||||
elif cell.is_wall:
|
|
||||||
row.append('#')
|
|
||||||
else:
|
|
||||||
row.append(' ')
|
|
||||||
print("|" + ''.join(row) + "|")
|
|
||||||
|
|
||||||
print("+" + "-" * maze.width + "+")
|
|
||||||
|
|
||||||
def update(self, event: str, data: dict) -> None:
|
|
||||||
if event == "maze_loaded":
|
|
||||||
maze = data.get('maze')
|
|
||||||
print("\n Лабиринт загружен:")
|
|
||||||
self.render(maze)
|
|
||||||
|
|
||||||
elif event == "search_start":
|
|
||||||
algorithm = data.get('algorithm', 'Unknown')
|
|
||||||
print(f"\n Начинаем поиск алгоритмом: {algorithm}")
|
|
||||||
|
|
||||||
elif event == "path_found":
|
|
||||||
maze = data.get('maze')
|
|
||||||
path = data.get('path')
|
|
||||||
stats = data.get('stats')
|
|
||||||
self.render(maze, path=path)
|
|
||||||
|
|
||||||
elif event == "no_path":
|
|
||||||
stats = data.get('stats')
|
|
||||||
print(f"\n {stats}")
|
|
||||||
|
|
||||||
elif event == "player_moved":
|
|
||||||
maze = data.get('maze')
|
|
||||||
player = data.get('player')
|
|
||||||
if player:
|
|
||||||
self.render(maze, player_position=player.current_cell)
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
import time
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import List, Optional, Tuple
|
|
||||||
from models import Cell, Maze
|
|
||||||
from strategies import PathFindingStrategy
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class SearchStats:
|
|
||||||
time_ms: float
|
|
||||||
visited_cells: int
|
|
||||||
path_length: int
|
|
||||||
path_found: bool = True
|
|
||||||
|
|
||||||
def __str__(self) -> str:
|
|
||||||
if not self.path_found:
|
|
||||||
return f"Путь не найден (время: {self.time_ms:.2f} мс)"
|
|
||||||
return (f"Время: {self.time_ms:.2f} мс, "
|
|
||||||
f"Посещено клеток: {self.visited_cells}, "
|
|
||||||
f"Длина пути: {self.path_length}")
|
|
||||||
|
|
||||||
|
|
||||||
class MazeSolver:
|
|
||||||
|
|
||||||
def __init__(self, maze: Maze, strategy: Optional[PathFindingStrategy] = None):
|
|
||||||
self.maze = maze
|
|
||||||
self._strategy = strategy
|
|
||||||
|
|
||||||
def set_strategy(self, strategy: PathFindingStrategy) -> None:
|
|
||||||
self._strategy = strategy
|
|
||||||
|
|
||||||
def solve(self) -> Tuple[List[Cell], SearchStats]:
|
|
||||||
if self._strategy is None:
|
|
||||||
raise ValueError("Стратегия не установлена")
|
|
||||||
|
|
||||||
start_time = time.perf_counter()
|
|
||||||
path = self._strategy.find_path(self.maze, self.maze.start, self.maze.exit)
|
|
||||||
end_time = time.perf_counter()
|
|
||||||
|
|
||||||
time_ms = (end_time - start_time) * 1000
|
|
||||||
|
|
||||||
stats = SearchStats(
|
|
||||||
time_ms=time_ms,
|
|
||||||
visited_cells=len(path) if path else 0,
|
|
||||||
path_length=len(path) if path else 0,
|
|
||||||
path_found=bool(path)
|
|
||||||
)
|
|
||||||
|
|
||||||
return path, stats
|
|
||||||
|
|
@ -1,99 +0,0 @@
|
||||||
from abc import ABC, abstractmethod
|
|
||||||
from collections import deque
|
|
||||||
from heapq import heappush, heappop
|
|
||||||
from typing import List, Dict, Optional
|
|
||||||
from models import Cell, Maze
|
|
||||||
|
|
||||||
|
|
||||||
class PathFindingStrategy(ABC):
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class BFSStrategy(PathFindingStrategy):
|
|
||||||
|
|
||||||
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
|
|
||||||
queue = deque([start])
|
|
||||||
visited = {start}
|
|
||||||
parent: Dict[Cell, Optional[Cell]] = {start: None}
|
|
||||||
|
|
||||||
while queue:
|
|
||||||
current = queue.popleft()
|
|
||||||
|
|
||||||
if current == exit_cell:
|
|
||||||
return self._reconstruct_path(parent, current)
|
|
||||||
|
|
||||||
for neighbor in maze.get_neighbors(current):
|
|
||||||
if neighbor not in visited:
|
|
||||||
visited.add(neighbor)
|
|
||||||
parent[neighbor] = current
|
|
||||||
queue.append(neighbor)
|
|
||||||
|
|
||||||
return []
|
|
||||||
|
|
||||||
def _reconstruct_path(self, parent: Dict[Cell, Optional[Cell]], current: Cell) -> List[Cell]:
|
|
||||||
path = []
|
|
||||||
while current is not None:
|
|
||||||
path.append(current)
|
|
||||||
current = parent.get(current)
|
|
||||||
return list(reversed(path))
|
|
||||||
|
|
||||||
|
|
||||||
class DFSStrategy(PathFindingStrategy):
|
|
||||||
|
|
||||||
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
|
|
||||||
stack = [(start, [start])]
|
|
||||||
visited = {start}
|
|
||||||
|
|
||||||
while stack:
|
|
||||||
current, path = stack.pop()
|
|
||||||
|
|
||||||
if current == exit_cell:
|
|
||||||
return path
|
|
||||||
|
|
||||||
for neighbor in maze.get_neighbors(current):
|
|
||||||
if neighbor not in visited:
|
|
||||||
visited.add(neighbor)
|
|
||||||
stack.append((neighbor, path + [neighbor]))
|
|
||||||
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
class AStarStrategy(PathFindingStrategy):
|
|
||||||
|
|
||||||
def _heuristic(self, cell: Cell, exit_cell: Cell) -> int:
|
|
||||||
return abs(cell.x - exit_cell.x) + abs(cell.y - exit_cell.y)
|
|
||||||
|
|
||||||
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
|
|
||||||
counter = 0
|
|
||||||
open_set = [(self._heuristic(start, exit_cell), counter, start)]
|
|
||||||
|
|
||||||
g_score: Dict[Cell, float] = {start: 0}
|
|
||||||
parent: Dict[Cell, Optional[Cell]] = {start: None}
|
|
||||||
|
|
||||||
while open_set:
|
|
||||||
_, _, current = heappop(open_set)
|
|
||||||
|
|
||||||
if current == exit_cell:
|
|
||||||
return self._reconstruct_path(parent, current)
|
|
||||||
|
|
||||||
for neighbor in maze.get_neighbors(current):
|
|
||||||
tentative_g = g_score[current] + 1
|
|
||||||
|
|
||||||
if neighbor not in g_score or tentative_g < g_score[neighbor]:
|
|
||||||
parent[neighbor] = current
|
|
||||||
g_score[neighbor] = tentative_g
|
|
||||||
counter += 1
|
|
||||||
f = tentative_g + self._heuristic(neighbor, exit_cell)
|
|
||||||
heappush(open_set, (f, counter, neighbor))
|
|
||||||
|
|
||||||
return []
|
|
||||||
|
|
||||||
def _reconstruct_path(self, parent: Dict[Cell, Optional[Cell]], current: Cell) -> List[Cell]:
|
|
||||||
path = []
|
|
||||||
while current is not None:
|
|
||||||
path.append(current)
|
|
||||||
current = parent.get(current)
|
|
||||||
return list(reversed(path))
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
import pandas as pd
|
|
||||||
import matplotlib.pyplot as plt
|
|
||||||
import numpy as np
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
|
|
||||||
def plot_results(csv_file='experiment_results.csv'):
|
|
||||||
|
|
||||||
if not Path(csv_file).exists():
|
|
||||||
print(f"❌ {csv_file} не найден. Сначала запустите main.py")
|
|
||||||
return
|
|
||||||
|
|
||||||
df = pd.read_csv(csv_file)
|
|
||||||
|
|
||||||
df = df[df['path_found'] == True]
|
|
||||||
|
|
||||||
if df.empty:
|
|
||||||
print("Нет данных для графиков")
|
|
||||||
return
|
|
||||||
|
|
||||||
mazes = [m.replace('.txt', '') for m in df['maze_file'].unique()]
|
|
||||||
strategies = df['strategy'].unique()
|
|
||||||
|
|
||||||
fig, axes = plt.subplots(1, 3, figsize=(14, 5))
|
|
||||||
fig.suptitle('Сравнение алгоритмов поиска в лабиринте', fontsize=14, fontweight='bold')
|
|
||||||
|
|
||||||
x = np.arange(len(mazes))
|
|
||||||
width = 0.25
|
|
||||||
colors = {'BFS': '#3498db', 'DFS': '#2ecc71', 'A*': '#e74c3c'}
|
|
||||||
|
|
||||||
for i, strategy in enumerate(strategies):
|
|
||||||
times, visited, lengths = [], [], []
|
|
||||||
|
|
||||||
for maze in df['maze_file'].unique():
|
|
||||||
data = df[(df['strategy'] == strategy) & (df['maze_file'] == maze)]
|
|
||||||
if not data.empty:
|
|
||||||
times.append(data['time_mean'].values[0])
|
|
||||||
visited.append(data['visited_mean'].values[0])
|
|
||||||
lengths.append(data['path_length_mean'].values[0])
|
|
||||||
else:
|
|
||||||
times.append(0)
|
|
||||||
visited.append(0)
|
|
||||||
lengths.append(0)
|
|
||||||
|
|
||||||
axes[0].bar(x + i*width, times, width, label=strategy,
|
|
||||||
color=colors.get(strategy, 'gray'), alpha=0.7)
|
|
||||||
axes[1].bar(x + i*width, visited, width, label=strategy,
|
|
||||||
color=colors.get(strategy, 'gray'), alpha=0.7)
|
|
||||||
axes[2].bar(x + i*width, lengths, width, label=strategy,
|
|
||||||
color=colors.get(strategy, 'gray'), alpha=0.7)
|
|
||||||
|
|
||||||
axes[0].set_title(' Время выполнения (мс)')
|
|
||||||
axes[0].set_xticks(x + width)
|
|
||||||
axes[0].set_xticklabels(mazes, rotation=45, ha='right')
|
|
||||||
axes[0].legend()
|
|
||||||
axes[0].grid(True, alpha=0.3)
|
|
||||||
|
|
||||||
axes[1].set_title(' Посещённые клетки')
|
|
||||||
axes[1].set_xticks(x + width)
|
|
||||||
axes[1].set_xticklabels(mazes, rotation=45, ha='right')
|
|
||||||
axes[1].legend()
|
|
||||||
axes[1].grid(True, alpha=0.3)
|
|
||||||
|
|
||||||
axes[2].set_title(' Длина пути')
|
|
||||||
axes[2].set_xticks(x + width)
|
|
||||||
axes[2].set_xticklabels(mazes, rotation=45, ha='right')
|
|
||||||
axes[2].legend()
|
|
||||||
axes[2].grid(True, alpha=0.3)
|
|
||||||
|
|
||||||
plt.tight_layout()
|
|
||||||
plt.savefig('experiment_results.png', dpi=150, bbox_inches='tight')
|
|
||||||
plt.show()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
plot_results()
|
|
||||||
Loading…
Reference in New Issue
Block a user