You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.4 KiB

import json
import tkinter as tk
from collections import deque
import threading
class MazeSolver:
def __init__(self, maze_file):
with open(maze_file, 'r') as file:
self.maze = json.load(file)
self.height = len(self.maze)
self.width = len(self.maze[0])
self.start = (1, 1)
self.end = (self.width - 2, self.height - 2)
self.path = []
self.window = tk.Tk()
self.window.title("Maze Solver")
self.canvas = tk.Canvas(self.window, width=self.width*10, height=self.height*10)
self.canvas.pack()
self.queue = deque([[self.start]])
self.visited = set([self.start])
self.position = (0, 0)
def solve_maze(self):
if not len(self.queue):
return
path = self.queue.popleft()
x, y = path[-1]
self.position = path[-1]
if (x, y) == self.end:
self.path = path
return
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < self.width and 0 <= ny < self.height and not self.maze[ny][nx] and (nx, ny) not in self.visited:
self.queue.append(path + [(nx, ny)])
self.visited.add((nx, ny))
threading.Thread(target=self.solve_maze).start()
def draw_maze(self):
self.canvas.delete("all")
for y in range(self.height):
for x in range(self.width):
color = "black" if self.maze[y][x] else "white"
if (x, y) == self.position:
color = "blue" # Color the current position blue
elif (x, y) in self.visited:
color = "gray" # Color the current position blue
self.canvas.create_rectangle(x*10, y*10, (x+1)*10, (y+1)*10, fill=color)
def draw_path(self):
for x, y in self.path:
self.canvas.create_rectangle(x*10, y*10, (x+1)*10, (y+1)*10, fill="green")
def update_maze(self):
if self.queue and not self.path: # Continue updating only if there are cells left to visit
self.solve_maze()
self.draw_maze()
self.window.after(10, self.update_maze)
else:
self.draw_path()
def run(self):
self.update_maze()
self.window.mainloop()
# Create and run the maze solver
#Breadth-First Search, BFS
solver = MazeSolver('maze.json')
solver.run()