forked from UNN/2026-rff_mp
Основная функция main
This commit is contained in:
parent
118945f625
commit
aadb5b2e3b
|
|
@ -533,7 +533,6 @@ def print_analysis():
|
||||||
ВЫВОДЫ ПО ПАТТЕРНАМ:
|
ВЫВОДЫ ПО ПАТТЕРНАМ:
|
||||||
|
|
||||||
BUILDER:
|
BUILDER:
|
||||||
- Скрывает сложность парсинга файлов
|
|
||||||
- Легко добавить новый формат
|
- Легко добавить новый формат
|
||||||
- Код загрузки не смешивается с логикой лабиринта
|
- Код загрузки не смешивается с логикой лабиринта
|
||||||
|
|
||||||
|
|
@ -551,4 +550,107 @@ def print_analysis():
|
||||||
- Позволяет выполнять и отменять действия
|
- Позволяет выполнять и отменять действия
|
||||||
- Удобно для пошагового управления
|
- Удобно для пошагового управления
|
||||||
- История команд позволяет сохранять/загружать состояние
|
- История команд позволяет сохранять/загружать состояние
|
||||||
""")
|
""")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("ЛАБОРАТОРНАЯ РАБОТА №2: ПОИСК ВЫХОДА ИЗ ЛАБИРИНТА")
|
||||||
|
print("Паттерны: Builder, Strategy, Observer, Command")
|
||||||
|
|
||||||
|
# Создание тестовых лабиринтов
|
||||||
|
print("\n1. СОЗДАНИЕ ТЕСТОВЫХ ЛАБИРИНТОВ...")
|
||||||
|
create_test_mazes()
|
||||||
|
print(" Созданы лабиринты: tiny, medium, large, empty, no_exit")
|
||||||
|
|
||||||
|
# Список файлов лабиринтов
|
||||||
|
maze_files = [
|
||||||
|
"mazes/tiny.txt",
|
||||||
|
"mazes/medium.txt",
|
||||||
|
"mazes/large.txt",
|
||||||
|
"mazes/empty.txt",
|
||||||
|
"mazes/no_exit.txt"
|
||||||
|
]
|
||||||
|
|
||||||
|
strategies = [BFSStrategy(), DFSStrategy(), AStarStrategy()]
|
||||||
|
all_results = []
|
||||||
|
|
||||||
|
# Демонстрация Observer и Command на первом лабиринте
|
||||||
|
print("\n2. ДЕМОНСТРАЦИЯ РАБОТЫ ПРОГРАММЫ")
|
||||||
|
|
||||||
|
builder = TextFileMazeBuilder()
|
||||||
|
maze = builder.build_from_file("mazes/tiny.txt")
|
||||||
|
print("Лабиринт tiny.txt:")
|
||||||
|
print(maze)
|
||||||
|
|
||||||
|
logger = ConsoleLogger()
|
||||||
|
solver_with_observer = MazeSolverWithObserver(maze, strategies[0], observers=[logger])
|
||||||
|
path, _ = solver_with_observer.solve()
|
||||||
|
interactive_move_demo(maze, path)
|
||||||
|
|
||||||
|
# Эксперименты
|
||||||
|
print("3. ЭКСПЕРИМЕНТАЛЬНОЕ СРАВНЕНИЕ АЛГОРИТМОВ")
|
||||||
|
|
||||||
|
for maze_file in maze_files:
|
||||||
|
try:
|
||||||
|
results = test_single_maze(maze_file, strategies)
|
||||||
|
for r in results:
|
||||||
|
r['maze'] = maze_file
|
||||||
|
all_results.append(r)
|
||||||
|
print(f"\n{maze_file}:")
|
||||||
|
for r in results:
|
||||||
|
print(f" {r['algorithm']}: {r['avg_time_ms']:.3f} мс, "
|
||||||
|
f"посещено {r['avg_visited']:.1f}, путь {r['avg_path_len']:.1f}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Ошибка при обработке {maze_file}: {e}")
|
||||||
|
|
||||||
|
# Сохранение CSV
|
||||||
|
if all_results:
|
||||||
|
os.makedirs("results", exist_ok=True)
|
||||||
|
with open('results/all_results.csv', 'w', newline='', encoding='utf-8') as f:
|
||||||
|
writer = csv.DictWriter(f, fieldnames=['maze', 'algorithm', 'avg_time_ms', 'avg_visited', 'avg_path_len'])
|
||||||
|
writer.writeheader()
|
||||||
|
writer.writerows(all_results)
|
||||||
|
print("\nРезультаты сохранены в results/all_results.csv")
|
||||||
|
|
||||||
|
# Построение графиков для каждого лабиринта
|
||||||
|
df = pd.DataFrame(all_results)
|
||||||
|
for maze in df['maze'].unique():
|
||||||
|
subset = df[df['maze'] == maze]
|
||||||
|
plt.figure(figsize=(8, 5))
|
||||||
|
bars = plt.bar(subset['algorithm'], subset['avg_time_ms'], color=['blue', 'green', 'red'])
|
||||||
|
plt.title(f'Сравнение алгоритмов на лабиринте {maze}')
|
||||||
|
plt.ylabel('Среднее время (мс)')
|
||||||
|
plt.xlabel('Алгоритм')
|
||||||
|
for bar, val in zip(bars, subset['avg_time_ms']):
|
||||||
|
plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
|
||||||
|
f'{val:.3f}', ha='center', va='bottom', fontsize=9)
|
||||||
|
plt.tight_layout()
|
||||||
|
filename = f'results/plot_{maze.replace("/", "_")}.png'
|
||||||
|
plt.savefig(filename)
|
||||||
|
plt.close()
|
||||||
|
print(f" Сохранён график: {filename}")
|
||||||
|
|
||||||
|
# Сводный график
|
||||||
|
plt.figure(figsize=(12, 6))
|
||||||
|
for alg in df['algorithm'].unique():
|
||||||
|
subset = df[df['algorithm'] == alg]
|
||||||
|
plt.plot(subset['maze'], subset['avg_time_ms'], marker='o', linewidth=2, markersize=8, label=alg)
|
||||||
|
plt.xlabel('Лабиринт')
|
||||||
|
plt.ylabel('Среднее время (мс)')
|
||||||
|
plt.title('Сравнение эффективности алгоритмов на разных лабиринтах')
|
||||||
|
plt.legend()
|
||||||
|
plt.grid(True, alpha=0.3)
|
||||||
|
plt.xticks(rotation=45)
|
||||||
|
plt.tight_layout()
|
||||||
|
plt.savefig('results/summary_comparison.png')
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
print("\nГрафики сохранены в папке results/")
|
||||||
|
print(" - plot_*.png - графики для каждого лабиринта")
|
||||||
|
print(" - summary_comparison.png - сводный график")
|
||||||
|
|
||||||
|
print_analysis()
|
||||||
|
|
||||||
|
print("ЭКСПЕРИМЕНТ ЗАВЕРШЁН")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
15
tseremonnikovaaa/lab2/docs/data/mazes/empty.txt
Normal file
15
tseremonnikovaaa/lab2/docs/data/mazes/empty.txt
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
S
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
E
|
||||||
30
tseremonnikovaaa/lab2/docs/data/mazes/large.txt
Normal file
30
tseremonnikovaaa/lab2/docs/data/mazes/large.txt
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
S # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
E
|
||||||
15
tseremonnikovaaa/lab2/docs/data/mazes/medium.txt
Normal file
15
tseremonnikovaaa/lab2/docs/data/mazes/medium.txt
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
S# # # # #
|
||||||
|
|
||||||
|
# # # # #
|
||||||
|
|
||||||
|
# # # # #
|
||||||
|
|
||||||
|
# # # # #
|
||||||
|
|
||||||
|
# # # # #
|
||||||
|
|
||||||
|
# # # # #
|
||||||
|
|
||||||
|
# # # # #
|
||||||
|
|
||||||
|
# # # # #E
|
||||||
10
tseremonnikovaaa/lab2/docs/data/mazes/no_exit.txt
Normal file
10
tseremonnikovaaa/lab2/docs/data/mazes/no_exit.txt
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
S
|
||||||
|
#########
|
||||||
|
#########
|
||||||
|
#########
|
||||||
|
#########
|
||||||
|
#########
|
||||||
|
#########
|
||||||
|
#########
|
||||||
|
#########
|
||||||
|
#########
|
||||||
10
tseremonnikovaaa/lab2/docs/data/mazes/tiny.txt
Normal file
10
tseremonnikovaaa/lab2/docs/data/mazes/tiny.txt
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
S E
|
||||||
|
#######
|
||||||
|
#########
|
||||||
|
########
|
||||||
|
#######
|
||||||
|
#########
|
||||||
|
########
|
||||||
|
#########
|
||||||
|
########
|
||||||
|
|
||||||
13
tseremonnikovaaa/lab2/docs/data/results/all_results.csv
Normal file
13
tseremonnikovaaa/lab2/docs/data/results/all_results.csv
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
maze,algorithm,avg_time_ms,avg_visited,avg_path_len
|
||||||
|
mazes/tiny.txt,BFSStrategy,0.051900000471505336,12.0,10.0
|
||||||
|
mazes/tiny.txt,DFSStrategy,0.040920000174082816,9.0,10.0
|
||||||
|
mazes/tiny.txt,AStarStrategy,0.07476000027963892,10.0,10.0
|
||||||
|
mazes/medium.txt,BFSStrategy,1.2075799993908731,185.0,29.0
|
||||||
|
mazes/medium.txt,DFSStrategy,0.999220000448986,119.0,113.0
|
||||||
|
mazes/medium.txt,AStarStrategy,1.3635600000270642,176.0,29.0
|
||||||
|
mazes/large.txt,BFSStrategy,3.158179999809363,751.0,59.0
|
||||||
|
mazes/large.txt,DFSStrategy,3.9773199998307973,624.0,583.0
|
||||||
|
mazes/large.txt,AStarStrategy,3.022899999996298,719.0,59.0
|
||||||
|
mazes/empty.txt,BFSStrategy,0.43741999979829416,225.0,29.0
|
||||||
|
mazes/empty.txt,DFSStrategy,0.5842599995958153,224.0,225.0
|
||||||
|
mazes/empty.txt,AStarStrategy,0.6680599992250791,225.0,29.0
|
||||||
|
BIN
tseremonnikovaaa/lab2/docs/data/results/plot_mazes_empty.txt.png
Normal file
BIN
tseremonnikovaaa/lab2/docs/data/results/plot_mazes_empty.txt.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
BIN
tseremonnikovaaa/lab2/docs/data/results/plot_mazes_large.txt.png
Normal file
BIN
tseremonnikovaaa/lab2/docs/data/results/plot_mazes_large.txt.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 41 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 40 KiB |
BIN
tseremonnikovaaa/lab2/docs/data/results/plot_mazes_tiny.txt.png
Normal file
BIN
tseremonnikovaaa/lab2/docs/data/results/plot_mazes_tiny.txt.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
BIN
tseremonnikovaaa/lab2/docs/data/results/summary_comparison.png
Normal file
BIN
tseremonnikovaaa/lab2/docs/data/results/summary_comparison.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 141 KiB |
Loading…
Reference in New Issue
Block a user