2026-rff_mp/BudakovIS/docs/data/2-nd-exercize/main.py

505 lines
15 KiB
Python
Raw Normal View History

2026-05-15 05:05:17 +00:00
import sys
from collections import deque
2026-05-15 05:52:56 +00:00
import heapq
2026-05-15 06:02:06 +00:00
import time
2026-05-15 06:16:11 +00:00
import os
2026-05-15 05:05:17 +00:00
class Cell:
2026-05-15 06:16:11 +00:00
def __init__(self, x, y):
2026-05-15 05:05:17 +00:00
self._x = x
self._y = y
self._is_wall = False
self._is_start = False
self._is_exit = False
@property
2026-05-15 06:16:11 +00:00
def x(self):
2026-05-15 05:05:17 +00:00
return self._x
@property
2026-05-15 06:16:11 +00:00
def y(self):
2026-05-15 05:05:17 +00:00
return self._y
@property
2026-05-15 06:16:11 +00:00
def is_wall(self):
2026-05-15 05:05:17 +00:00
return self._is_wall
@is_wall.setter
2026-05-15 06:16:11 +00:00
def is_wall(self, value):
2026-05-15 05:05:17 +00:00
self._is_wall = value
@property
2026-05-15 06:16:11 +00:00
def is_start(self):
2026-05-15 05:05:17 +00:00
return self._is_start
@is_start.setter
2026-05-15 06:16:11 +00:00
def is_start(self, value):
2026-05-15 05:05:17 +00:00
self._is_start = value
@property
2026-05-15 06:16:11 +00:00
def is_exit(self):
2026-05-15 05:05:17 +00:00
return self._is_exit
@is_exit.setter
2026-05-15 06:16:11 +00:00
def is_exit(self, value):
2026-05-15 05:05:17 +00:00
self._is_exit = value
2026-05-15 06:16:11 +00:00
def is_passable(self):
2026-05-15 05:05:17 +00:00
return not self._is_wall
class Maze:
2026-05-15 06:16:11 +00:00
def __init__(self, width, height):
2026-05-15 05:05:17 +00:00
self._width = width
self._height = height
self._cells = [[Cell(x, y) for x in range(width)] for y in range(height)]
self._start = None
self._exit = None
@property
2026-05-15 06:16:11 +00:00
def width(self):
2026-05-15 05:05:17 +00:00
return self._width
@property
2026-05-15 06:16:11 +00:00
def height(self):
2026-05-15 05:05:17 +00:00
return self._height
@property
2026-05-15 06:16:11 +00:00
def start(self):
2026-05-15 05:05:17 +00:00
return self._start
@property
2026-05-15 06:16:11 +00:00
def exit(self):
2026-05-15 05:05:17 +00:00
return self._exit
2026-05-15 06:16:11 +00:00
def get_cell(self, x, y):
2026-05-15 05:05:17 +00:00
if 0 <= x < self._width and 0 <= y < self._height:
return self._cells[y][x]
return None
2026-05-15 06:16:11 +00:00
def set_cell(self, x, y, cell_type):
2026-05-15 05:05:17 +00:00
cell = self.get_cell(x, y)
if cell is None:
return
if cell_type == 'wall':
cell.is_wall = True
elif cell_type == 'start':
if self._start:
self._start.is_start = False
cell.is_start = True
cell.is_wall = False
self._start = cell
elif cell_type == 'exit':
if self._exit:
self._exit.is_exit = False
cell.is_exit = True
cell.is_wall = False
self._exit = cell
elif cell_type == 'path':
cell.is_wall = False
2026-05-15 06:16:11 +00:00
def get_neighbors(self, cell):
2026-05-15 05:05:17 +00:00
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
class MazeBuilder:
2026-05-15 06:16:11 +00:00
def build_from_file(self, filename):
raise NotImplementedError("Need to realise in calss")
2026-05-15 06:02:06 +00:00
2026-05-15 05:05:17 +00:00
class TextFileMazeBuilder(MazeBuilder):
2026-05-15 06:16:11 +00:00
def build_from_file(self, filename):
with open(filename, 'r') as f:
2026-05-15 06:42:46 +00:00
lines = [line.rstrip('\n') for line in f.readlines()]
2026-05-15 05:05:17 +00:00
height = len(lines)
2026-05-15 06:16:11 +00:00
width = max(len(line) for line in lines) if height > 0 else 0
start_en = 0
exit_en = 0
2026-05-15 05:05:17 +00:00
maze = Maze(width, height)
2026-05-15 06:16:11 +00:00
2026-05-15 06:42:46 +00:00
for y, line in enumerate(lines):
2026-05-15 05:05:17 +00:00
for x, ch in enumerate(line):
2026-05-15 06:16:11 +00:00
if ch == "#":
2026-05-15 06:42:46 +00:00
maze.set_cell(x, y, "wall")
2026-05-15 06:16:11 +00:00
elif ch == "S":
2026-05-15 06:42:46 +00:00
maze.set_cell(x, y, "start")
start_en += 1
2026-05-15 06:16:11 +00:00
elif ch == "E":
2026-05-15 06:42:46 +00:00
maze.set_cell(x, y, "exit")
exit_en += 1
2026-05-15 05:05:17 +00:00
else:
maze.set_cell(x, y, 'path')
2026-05-15 06:42:46 +00:00
if start_en != 1 or exit_en != 1:
raise ValueError(f"Labirint must have one S and one E. Found: S={start_en}, E={exit_en}")
2026-05-15 05:05:17 +00:00
return maze
2026-05-15 06:02:06 +00:00
class PathFindingStrategy:
2026-05-15 06:16:11 +00:00
def find_path(self, maze, start, exit_cell):
raise NotImplementedError
2026-05-15 06:02:06 +00:00
2026-05-15 06:16:11 +00:00
def _reconstruct_path(self, came_from, start, exit_cell):
2026-05-15 06:02:06 +00:00
path = []
current = exit_cell
while current is not None:
path.append(current)
current = came_from.get(current)
path.reverse()
return path
2026-05-15 06:42:46 +00:00
def get_visited_count(self):
return getattr(self, '_visited_count', 0)
2026-05-15 05:05:17 +00:00
2026-05-15 06:02:06 +00:00
class BFSStrategy(PathFindingStrategy):
2026-05-15 06:16:11 +00:00
def find_path(self, maze, start, exit_cell):
2026-05-15 05:05:17 +00:00
queue = deque()
queue.append(start)
2026-05-15 06:02:06 +00:00
came_from = {start: None}
visited = {start}
2026-05-15 05:05:17 +00:00
while queue:
current = queue.popleft()
2026-05-15 06:02:06 +00:00
if current == exit_cell:
2026-05-15 06:42:46 +00:00
self._visited_count = len(visited)
2026-05-15 06:02:06 +00:00
return self._reconstruct_path(came_from, start, exit_cell)
for neighbor in maze.get_neighbors(current):
if neighbor not in visited:
visited.add(neighbor)
came_from[neighbor] = current
queue.append(neighbor)
2026-05-15 06:42:46 +00:00
self._visited_count = len(visited)
2026-05-15 05:05:17 +00:00
return []
2026-05-15 06:02:06 +00:00
class DFSStrategy(PathFindingStrategy):
2026-05-15 06:16:11 +00:00
def find_path(self, maze, start, exit_cell):
2026-05-15 06:02:06 +00:00
stack = [start]
came_from = {start: None}
visited = {start}
2026-05-15 05:05:17 +00:00
while stack:
current = stack.pop()
2026-05-15 06:02:06 +00:00
if current == exit_cell:
2026-05-15 06:42:46 +00:00
self._visited_count = len(visited)
2026-05-15 06:02:06 +00:00
return self._reconstruct_path(came_from, start, exit_cell)
for neighbor in maze.get_neighbors(current):
if neighbor not in visited:
visited.add(neighbor)
came_from[neighbor] = current
stack.append(neighbor)
2026-05-15 06:42:46 +00:00
self._visited_count = len(visited)
2026-05-15 05:05:17 +00:00
return []
2026-05-15 06:02:06 +00:00
class AStarStrategy(PathFindingStrategy):
2026-05-15 06:16:11 +00:00
def _heuristic(self, cell, exit_cell):
2026-05-15 06:02:06 +00:00
return abs(cell.x - exit_cell.x) + abs(cell.y - exit_cell.y)
2026-05-15 06:16:11 +00:00
def find_path(self, maze, start, exit_cell):
2026-05-15 05:52:56 +00:00
heap = []
counter = 0
2026-05-15 06:02:06 +00:00
start_f = self._heuristic(start, exit_cell)
2026-05-15 05:52:56 +00:00
heapq.heappush(heap, (start_f, counter, start))
2026-05-15 06:02:06 +00:00
counter += 1
2026-05-15 05:52:56 +00:00
came_from = {}
g_score = {start: 0}
f_score = {start: start_f}
2026-05-15 06:42:46 +00:00
visited = set()
2026-05-15 06:02:06 +00:00
2026-05-15 05:52:56 +00:00
while heap:
current_f, _, current = heapq.heappop(heap)
2026-05-15 06:42:46 +00:00
visited.add(current)
2026-05-15 06:02:06 +00:00
if current == exit_cell:
2026-05-15 06:42:46 +00:00
self._visited_count = len(visited)
2026-05-15 05:52:56 +00:00
return self._reconstruct_path(came_from, start, exit_cell)
2026-05-15 06:02:06 +00:00
if current_f > f_score.get(current, float('inf')):
2026-05-15 05:52:56 +00:00
continue
for neighbor in maze.get_neighbors(current):
tentative_g = g_score[current] + 1
if tentative_g < g_score.get(neighbor, float('inf')):
came_from[neighbor] = current
g_score[neighbor] = tentative_g
new_f = tentative_g + self._heuristic(neighbor, exit_cell)
f_score[neighbor] = new_f
heapq.heappush(heap, (new_f, counter, neighbor))
counter += 1
2026-05-15 06:42:46 +00:00
self._visited_count = len(visited)
2026-05-15 05:52:56 +00:00
return []
2026-05-15 06:02:06 +00:00
class SearchStats:
2026-05-15 06:16:11 +00:00
def __init__(self, time_ms, visited_cells, path_length):
2026-05-15 06:02:06 +00:00
self.time_ms = time_ms
self.visited_cells = visited_cells
self.path_length = path_length
2026-05-15 06:16:11 +00:00
class Observer:
def update(self, event_type, data):
raise NotImplementedError
class ConsoleView(Observer):
def __init__(self, player=None):
self._last_path = None
self._player = player
def update(self, event_type, data):
if event_type == "maze_loaded":
self.render_maze(data)
elif event_type == "path_found":
self._last_path = data
self.render_path(data)
elif event_type == "player_moved":
self.render_maze_with_player(data)
def render_maze(self, maze):
os.system('cls' if os.name == 'nt' else 'clear')
print("=" * (maze.width * 2 + 4))
2026-05-15 06:42:46 +00:00
print(" LABIRINT")
2026-05-15 06:16:11 +00:00
print("=" * (maze.width * 2 + 4))
for y in range(maze.height):
print(" ", end='')
for x in range(maze.width):
cell = maze.get_cell(x, y)
if cell == maze.start:
print('S', end=' ')
elif cell == maze.exit:
print('E', end=' ')
elif cell.is_wall:
print('#', end=' ')
else:
print('.', end=' ')
print()
print("=" * (maze.width * 2 + 4))
2026-05-15 06:42:46 +00:00
print(" S - start E - exit # - wall . - path")
2026-05-15 06:16:11 +00:00
def render_maze_with_player(self, maze):
os.system('cls' if os.name == 'nt' else 'clear')
print("=" * (maze.width * 2 + 4))
2026-05-15 06:42:46 +00:00
print(" LABIRINT (P - player)")
2026-05-15 06:16:11 +00:00
print("=" * (maze.width * 2 + 4))
for y in range(maze.height):
print(" ", end='')
for x in range(maze.width):
cell = maze.get_cell(x, y)
if self._player and cell == self._player.current:
print('P', end=' ')
elif cell == maze.start:
print('S', end=' ')
elif cell == maze.exit:
print('E', end=' ')
elif cell.is_wall:
print('#', end=' ')
else:
print('.', end=' ')
print()
print("=" * (maze.width * 2 + 4))
2026-05-15 06:42:46 +00:00
print(f" Player position: ({self._player.current.x}, {self._player.current.y})")
print(" S - start E - exit # - wall . - path P - player")
2026-05-15 06:02:06 +00:00
2026-05-15 06:16:11 +00:00
def render_path(self, path):
if not path:
2026-05-15 06:42:46 +00:00
print("\n Path not found!")
2026-05-15 06:16:11 +00:00
return
2026-05-15 06:42:46 +00:00
print(f"\n Path found! Length: {len(path)}")
2026-05-15 06:16:11 +00:00
def render_player(self, player_cell):
if self._player:
self.render_maze_with_player(self._player._maze)
2026-05-15 06:02:06 +00:00
2026-05-15 06:16:11 +00:00
class Player:
def __init__(self, start_cell, maze):
self._current = start_cell
self._previous = None
self._maze = maze
@property
def current(self):
return self._current
def move_to(self, cell):
if cell and cell.is_passable():
self._previous = self._current
self._current = cell
return True
return False
2026-05-15 06:02:06 +00:00
2026-05-15 06:16:11 +00:00
def undo_move(self):
if self._previous:
self._current, self._previous = self._previous, None
return True
return False
class Command:
def execute(self):
raise NotImplementedError
def undo(self):
raise NotImplementedError
class MoveCommand(Command):
def __init__(self, player, direction, maze):
self._player = player
self._direction = direction
self._maze = maze
self._executed = False
def execute(self):
dx, dy = self._direction
new_x = self._player.current.x + dx
new_y = self._player.current.y + dy
target_cell = self._maze.get_cell(new_x, new_y)
if target_cell and target_cell.is_passable():
self._player.move_to(target_cell)
self._executed = True
return True
return False
def undo(self):
if self._executed:
self._player.undo_move()
self._executed = False
return True
return False
class MazeSolver:
def __init__(self, maze):
2026-05-15 06:02:06 +00:00
self._maze = maze
self._strategy = None
2026-05-15 06:16:11 +00:00
self._observers = []
2026-05-15 06:02:06 +00:00
2026-05-15 06:16:11 +00:00
def attach(self, observer):
self._observers.append(observer)
def notify(self, event_type, data):
for observer in self._observers:
observer.update(event_type, data)
def set_strategy(self, strategy):
2026-05-15 06:02:06 +00:00
self._strategy = strategy
2026-05-15 06:16:11 +00:00
def solve(self):
2026-05-15 06:02:06 +00:00
if self._strategy is None:
return None
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
2026-05-15 06:16:11 +00:00
self.notify("path_found", path)
2026-05-15 06:02:06 +00:00
2026-05-15 06:42:46 +00:00
return SearchStats(time_ms, self._strategy.get_visited_count(), len(path))
def run_experiment(maze_file, strategy, runs=5):
builder = TextFileMazeBuilder()
maze = builder.build_from_file(maze_file)
total_time = 0
total_visited = 0
total_length = 0
for _ in range(runs):
solver = MazeSolver(maze)
solver.set_strategy(strategy)
stats = solver.solve()
if stats:
total_time += stats.time_ms
total_visited += stats.visited_cells
total_length += stats.path_length
return {
'time_ms': total_time / runs,
'visited_cells': total_visited / runs,
'path_length': total_length / runs
}
2026-05-15 06:02:06 +00:00
2026-05-15 05:52:56 +00:00
2026-05-15 05:05:17 +00:00
if __name__ == "__main__":
2026-05-15 06:42:46 +00:00
if len(sys.argv) > 1 and sys.argv[1] == 'experiment':
print("Running experiments...")
sys.exit(0)
2026-05-15 05:05:17 +00:00
builder = TextFileMazeBuilder()
maze = builder.build_from_file("maze1.txt")
2026-05-15 06:02:06 +00:00
2026-05-15 06:16:11 +00:00
player = Player(maze.start, maze)
view = ConsoleView(player)
view.render_maze(maze)
2026-05-15 06:02:06 +00:00
solver = MazeSolver(maze)
2026-05-15 06:16:11 +00:00
solver.attach(view)
2026-05-15 06:42:46 +00:00
print("\n CONTROLS:")
print(" H (left) J (down) K (up) L (right)")
print(" U - undo Q - quit")
print("\n AUTO SEARCH:")
print(" B - BFS D - DFS A - A*")
2026-05-15 06:16:11 +00:00
print("\n" + "=" * 50)
2026-05-15 06:02:06 +00:00
2026-05-15 06:16:11 +00:00
command_stack = []
2026-05-15 06:02:06 +00:00
2026-05-15 06:16:11 +00:00
while True:
2026-05-15 06:42:46 +00:00
key = input("\n Command > ").lower()
2026-05-15 06:16:11 +00:00
if key == 'q':
2026-05-15 06:42:46 +00:00
print("\n Goodbye!")
2026-05-15 06:16:11 +00:00
break
elif key == 'b':
solver.set_strategy(BFSStrategy())
stats = solver.solve()
2026-05-15 06:42:46 +00:00
print(f"\n BFS: time={stats.time_ms:.3f}ms, visited={stats.visited_cells}, length={stats.path_length}")
2026-05-15 06:16:11 +00:00
elif key == 'd':
solver.set_strategy(DFSStrategy())
stats = solver.solve()
2026-05-15 06:42:46 +00:00
print(f"\n DFS: time={stats.time_ms:.3f}ms, visited={stats.visited_cells}, length={stats.path_length}")
2026-05-15 06:16:11 +00:00
elif key == 'a':
solver.set_strategy(AStarStrategy())
stats = solver.solve()
2026-05-15 06:42:46 +00:00
print(f"\n A*: time={stats.time_ms:.3f}ms, visited={stats.visited_cells}, length={stats.path_length}")
2026-05-15 06:16:11 +00:00
elif key in ['h', 'j', 'k', 'l']:
dirs = {'h': (-1, 0), 'l': (1, 0), 'k': (0, -1), 'j': (0, 1)}
cmd = MoveCommand(player, dirs[key], maze)
if cmd.execute():
command_stack.append(cmd)
view.render_maze_with_player(maze)
if player.current == maze.exit:
2026-05-15 06:42:46 +00:00
print("\n CONGRATULATIONS! YOU FOUND THE EXIT!")
print(f" Total moves: {len(command_stack)}")
2026-05-15 06:16:11 +00:00
break
else:
2026-05-15 06:42:46 +00:00
print("\n Cannot go there! It's a wall.")
2026-05-15 06:16:11 +00:00
elif key == 'u':
if command_stack:
cmd = command_stack.pop()
cmd.undo()
view.render_maze_with_player(maze)
2026-05-15 06:42:46 +00:00
print("\n Undo last move")
2026-05-15 06:16:11 +00:00
else:
2026-05-15 06:42:46 +00:00
print("\n Nothing to undo")
2026-05-15 06:16:11 +00:00
else:
2026-05-15 06:42:46 +00:00
print("\n Unknown command. Use h,j,k,l to move, u to undo, q to quit")
2026-05-15 06:02:06 +00:00
2026-05-15 06:42:46 +00:00
print("\n Game over. Thanks for playing!")