{ "cells": [ { "cell_type": "code", "execution_count": 7, "id": "ac02445d-6e74-4f6e-bb96-2c28ccd82d83", "metadata": {}, "outputs": [ { "ename": "ModuleNotFoundError", "evalue": "No module named 'modelsMaze'", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mModuleNotFoundError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[7]\u001b[39m\u001b[32m, line 8\u001b[39m\n\u001b[32m 5\u001b[39m sys.path.insert(\u001b[32m0\u001b[39m, os.getcwd())\n\u001b[32m 7\u001b[39m \u001b[38;5;66;03m# Импорты с вашими именами файлов\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m8\u001b[39m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mmodelsMaze\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m Maze, Cell\n\u001b[32m 9\u001b[39m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mbuildersText_maze_builder\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m TextFieldMazeBuilder\n\u001b[32m 10\u001b[39m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mstrategiesBFS_strategy\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m BFSStrategy\n", "\u001b[31mModuleNotFoundError\u001b[39m: No module named 'modelsMaze'" ] } ], "source": [ "import sys\n", "import os\n", "\n", "# Добавляем текущую папку в путь\n", "sys.path.insert(0, os.getcwd())\n", "\n", "# Импорты с вашими именами файлов\n", "from modelsMaze import Maze, Cell\n", "from buildersText_maze_builder import TextFieldMazeBuilder\n", "from strategiesBFS_strategy import BFSStrategy\n", "from strategiesDFS_strategy import DFSStrategy\n", "from strategiesA_star_strategy import AStarStrategy\n", "from solverMaze_solver import MazeSolver\n", "from visualizationConsole_view import ConsoleView\n", "from commandsPlayer import Player\n", "from commandsMove_command import MoveCommand\n", "from experimentsBenchmark import Benchmark\n", "\n", "def create_test_mazes():\n", " \"\"\"Создать тестовые лабиринты в папке mazes/.\"\"\"\n", " mazes_dir = \"mazes\"\n", " os.makedirs(mazes_dir, exist_ok=True)\n", " \n", " # Маленький лабиринт 10×10\n", " small = [\n", " \"##########\",\n", " \"#S #\",\n", " \"# ##### #\",\n", " \"# # # #\",\n", " \"# # # # #\",\n", " \"# # # #\",\n", " \"##### # #\",\n", " \"# #\",\n", " \"# E#\",\n", " \"##########\",\n", " ]\n", " \n", " # Пустой лабиринт\n", " empty = [\"S\" + \" \" * 48 + \"E\"] + [\" \" * 50 for _ in range(48)]\n", " \n", " # Лабиринт без выхода\n", " no_exit = [\n", " \"##########\",\n", " \"#S #\",\n", " \"# ##### #\",\n", " \"# # # #\",\n", " \"# # # # #\",\n", " \"# # # #\",\n", " \"##### # #\",\n", " \"# #\",\n", " \"##########\",\n", " \"##########\",\n", " ]\n", " \n", " mazes = {\n", " \"small.txt\": small,\n", " \"empty.txt\": empty,\n", " \"no_exit.txt\": no_exit,\n", " }\n", " \n", " for name, content in mazes.items():\n", " path = os.path.join(mazes_dir, name)\n", " with open(path, 'w', encoding='utf-8') as f:\n", " f.write('\\n'.join(content))\n", " print(f\"Создан тестовый лабиринт: {path}\")\n", " \n", " print()\n", "\n", "def demo_builder_and_strategy():\n", " \"\"\"Демонстрация паттернов Builder и Strategy.\"\"\"\n", " print(\"\\n\" + \"=\" * 60)\n", " print(\"ДЕМОНСТРАЦИЯ ПАТТЕРНОВ BUILDER И STRATEGY\")\n", " print(\"=\" * 60)\n", " \n", " builder = TextFieldMazeBuilder()\n", " maze = builder.build_from_file(\"mazes/small.txt\")\n", " \n", " strategies = [\n", " BFSStrategy(),\n", " DFSStrategy(),\n", " AStarStrategy(),\n", " ]\n", " \n", " for strategy in strategies:\n", " print(f\"\\n--- Используем стратегию: {strategy.name} ---\")\n", " solver = MazeSolver(maze, strategy)\n", " path = solver.solve()\n", " \n", " if path:\n", " print(f\" Путь найден! Длина: {len(path)}\")\n", " print(f\" Время: {solver.last_stats.time_ms:.2f} мс\")\n", " print(f\" Посещено клеток: {solver.last_stats.visited_cells}\")\n", " else:\n", " print(\" Путь не найден!\")\n", " \n", " return maze\n", "\n", "def demo_observer(maze: Maze):\n", " \"\"\"Демонстрация паттерна Observer.\"\"\"\n", " print(\"\\n\" + \"=\" * 60)\n", " print(\"ДЕМОНСТРАЦИЯ ПАТТЕРНА OBSERVER\")\n", " print(\"=\" * 60)\n", " \n", " view = ConsoleView(maze)\n", " solver = MazeSolver(maze, BFSStrategy())\n", " solver.attach(view)\n", " \n", " print(\"Запускаем поиск с наблюдателем...\")\n", " path = solver.solve()\n", " \n", " view.set_solution_path(path)\n", " view.render()\n", " \n", " return view\n", "\n", "def demo_command(maze: Maze, view: ConsoleView):\n", " \"\"\"Демонстрация паттерна Command.\"\"\"\n", " print(\"\\n\" + \"=\" * 60)\n", " print(\"ДЕМОНСТРАЦИЯ ПАТТЕРНА COMMAND\")\n", " print(\"=\" * 60)\n", " \n", " player = Player(maze, maze.start_cell)\n", " view.set_player_position(player.position)\n", " \n", " print(\"Управление игроком:\")\n", " print(\" W/A/S/D - движение, Z - отмена, Q - выход\")\n", " \n", " history = []\n", " \n", " while True:\n", " view.render()\n", " \n", " cmd = input(\"Ваш ход: \").strip().lower()\n", " \n", " if cmd == 'q':\n", " break\n", " elif cmd == 'z':\n", " if history:\n", " last_cmd = history.pop()\n", " last_cmd.undo()\n", " view.set_player_position(player.position)\n", " print(\"Последний ход отменён\")\n", " else:\n", " print(\"Нечего отменять\")\n", " elif cmd in MoveCommand.DIRECTIONS:\n", " move_cmd = MoveCommand(player, maze, cmd)\n", " if move_cmd.execute():\n", " history.append(move_cmd)\n", " view.set_player_position(player.position)\n", " \n", " if player.position == maze.exit_cell:\n", " print(\"\\n🎉 ПОБЕДА! ВЫ НАШЛИ ВЫХОД! 🎉\")\n", " view.render()\n", " break\n", " else:\n", " print(\"Туда нельзя пройти\")\n", " else:\n", " print(\"Неизвестная команда\")\n", " \n", " print(\"Игра завершена\")\n", "\n", "def run_experiments():\n", " \"\"\"Запуск экспериментального сравнения.\"\"\"\n", " print(\"\\n\" + \"=\" * 60)\n", " print(\"ЭКСПЕРИМЕНТАЛЬНОЕ СРАВНЕНИЕ АЛГОРИТМОВ\")\n", " print(\"=\" * 60)\n", " \n", " builder = TextFieldMazeBuilder()\n", " benchmark = Benchmark()\n", " \n", " maze_files = [\"small.txt\", \"empty.txt\", \"no_exit.txt\"]\n", " \n", " for maze_file in maze_files:\n", " try:\n", " maze = builder.build_from_file(f\"mazes/{maze_file}\")\n", " print(f\"\\nТестируем: {maze_file} ({maze.width}×{maze.height})\")\n", " benchmark.run_on_maze(maze, maze_file, iterations=5)\n", " except FileNotFoundError:\n", " print(f\"Файл {maze_file} не найден\")\n", " except ValueError as e:\n", " print(f\"Ошибка: {e}\")\n", " \n", " benchmark.print_summary()\n", " benchmark.save_to_csv()\n", "\n", "def main():\n", " \"\"\"Главная функция.\"\"\"\n", " print(\"=\" * 60)\n", " print(\"ПРОГРАММА ПОИСКА ВЫХОДА ИЗ ЛАБИРИНТА\")\n", " print(\"Паттерны: Builder, Strategy, Observer, Command\")\n", " print(\"=\" * 60)\n", " \n", " create_test_mazes()\n", " maze = demo_builder_and_strategy()\n", " view = demo_observer(maze)\n", " demo_command(maze, view)\n", " run_experiments()\n", " \n", " print(\"\\nПрограмма завершена!\")\n", "\n", "if __name__ == \"__main__\":\n", " main()" ] }, { "cell_type": "code", "execution_count": null, "id": "d0972138-e9f0-4612-a87c-741d9d0bea13", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:base] *", "language": "python", "name": "conda-base-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.9" } }, "nbformat": 4, "nbformat_minor": 5 }