-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolve.py
More file actions
73 lines (59 loc) · 2.1 KB
/
Solve.py
File metadata and controls
73 lines (59 loc) · 2.1 KB
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
from settings import *
import pygame as pg
from util import Node
class Solve:
def __init__(self, frontier, elem_maze, draw):
self.frontier = frontier
self.draw = draw
self.cur_x = 1
self.cur_y = 1
self.elem_list = elem_maze
self.maze_width = MAZE_WIDTH * 2 + 1
self.maze_height = MAZE_HEIGHT * 2 + 1
self.solve_path = []
self.is_solve = False
self.goal_x = self.maze_width - 2
self.goal_y = self.maze_height - 2
self.direction = 0
self.start = (self.cur_x, self.cur_y)
self.goal = (self.goal_x, self.goal_y)
def solve(self):
self.num_explored = 0
start = Node(state=self.start, parent=None, action=None)
frontier = self.frontier
frontier.add(start)
self.explored = set()
while True:
if frontier.empty():
raise Exception("No solution")
node = frontier.remove()
self.num_explored += 1
if node.state == self.goal:
return
self.explored.add(node.state)
x, y = node.state
self.elem_list[x][y] = 5
# pg.time.delay(50)
self.draw()
for action, state in self.get_neighbors(node.state):
if not frontier.contains_state(state) and state not in self.explored:
child = Node(state=state, parent=node, action=action)
frontier.add(child)
def get_neighbors(self, state):
row, col = state
candidates = [
("up", (row - 1, col)),
("down", (row + 1, col)),
("left", (row, col - 1)),
("right", (row, col + 1)),
]
result = []
for action, (r, c) in candidates:
# if 0 <= r < self.maze_height and 0 <= c < self.maze_width and not self.walls[r][c]:
if (
0 <= r < self.maze_height
and 0 <= c < self.maze_width
and self.elem_list[r][c] != 1
):
result.append((action, (r, c)))
return result