-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_finder.py
102 lines (80 loc) · 2.75 KB
/
path_finder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import curses
from curses import wrapper
import queue
import time
maze = [
["#", "O", "#", "#", "#", "#", "#", "#", "#"],
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
["#", " ", "#", "#", " ", "#", "#", " ", "#"],
["#", " ", "#", " ", " ", " ", "#", " ", "#"],
["#", " ", "#", " ", "#", " ", "#", " ", "#"],
["#", " ", "#", " ", "#", " ", "#", " ", "#"],
["#", " ", "#", " ", "#", " ", "#", "#", "#"],
["#", " ", " ", " ", " ", " ", " ", " ", "#"],
["#", "#", "#", "#", "#", "#", "#", "X", "#"]
]
def print_maze(maze, stdscr, path=[]):
BLUE = curses.color_pair(1)
RED = curses.color_pair(2)
for i, row in enumerate(maze):
for j, value in enumerate(row):
stdscr.addstr(i, j*2, value, BLUE)
for (i, j) in path:
stdscr.addstr(i, j*2, "X", RED)
def find_start(maze, start):
for i, row in enumerate(maze):
for j, value in enumerate(row):
if value == start:
return i, j
return None
def find_path(maze, stdscr):
start = "O"
end = "X"
start_pos = find_start(maze, start)
q = queue.Queue()
q.put((start_pos, [start_pos]))
visited = set()
while not q.empty():
current_pos, path = q.get()
row, col = current_pos
stdscr.clear()
print_maze(maze, stdscr, path)
time.sleep(0.2)
stdscr.refresh()
if maze[row][col] == end:
return path
neighbors = find_neighbors(maze, row, col)
for neighbor in neighbors:
if neighbor in visited:
continue
r, c = neighbor
if maze[r][c] == "#":
continue
new_path = path + [neighbor]
q.put((neighbor, new_path))
visited.add(neighbor)
def find_neighbors(maze, row, col):
neighbors = []
if row > 0:
neighbors.append((row - 1, col))
if row + 1 < len(maze):
neighbors.append((row + 1, col))
if col > 0:
neighbors.append((row, col - 1))
if col + 1 < len(maze[0]):
neighbors.append((row, col + 1))
if row > 0 and col > 0:
neighbors.append((row - 1, col - 1))
if row > 0 and col + 1 < len(maze[0]):
neighbors.append((row - 1, col + 1))
if row + 1 < len(maze) and col > 0:
neighbors.append((row + 1, col - 1))
if row + 1 < len(maze) and col + 1 < len(maze[0]):
neighbors.append((row + 1, col + 1))
return neighbors
def main(stdscr):
curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
find_path(maze, stdscr)
stdscr.getch()
wrapper(main)