2026-rff_mp/SorokinAD/[2]lab_2/main.py

164 lines
2.5 KiB
Python

from builders import TextFileMazeBuilder
from strategies import (
BFSStrategy,
DFSStrategy,
AStarStrategy
)
from solver import MazeSolver
from visualization import ConsoleView
from commands import (
Player,
MoveCommand
)
def test_strategy(name, strategy, maze):
print()
print("=" * 40)
view = ConsoleView()
solver = MazeSolver(
maze,
strategy
)
solver.add_observer(view)
path, stats = solver.solve()
print()
print(f"Strategy: {name}")
print(
f"Time: {stats.time_ms:.3f} ms"
)
print(
f"Visited cells: {stats.visited_cells}"
)
print(
f"Path length: {stats.path_length}"
)
print()
view.render(
maze,
path
)
# =========================================================
# Manual mode
# =========================================================
def manual_mode(maze):
print()
print("=" * 40)
print("MANUAL MODE")
print("W/A/S/D - move")
print("U - undo")
print("Q - quit")
view = ConsoleView()
player = Player(
maze.start
)
history = []
while True:
print()
view.render(
maze,
current=player.current_cell
)
if player.current_cell == maze.exit:
print()
print("YOU WIN!")
break
command_input = input(
"\nCommand: "
).upper()
if command_input == "Q":
break
if command_input == "U":
if history:
last_command = history.pop()
last_command.undo()
continue
command = MoveCommand(
player,
maze,
command_input
)
success = command.execute()
if success:
history.append(command)
else:
print("Invalid move")
def main():
builder = TextFileMazeBuilder()
maze = builder.build_from_file(
"mazes/small.txt"
)
# =====================================
# Strategies
# =====================================
test_strategy(
"BFS",
BFSStrategy(),
maze
)
test_strategy(
"DFS",
DFSStrategy(),
maze
)
test_strategy(
"A*",
AStarStrategy(),
maze
)
# =====================================
# Manual mode
# =====================================
manual_mode(maze)
if __name__ == "__main__":
main()