4
4
5
5
from __future__ import annotations
6
6
7
+ from typing import Optional
8
+
9
+ Path = list [tuple [int , int ]]
10
+
7
11
grid = [
8
12
[0 , 0 , 0 , 0 , 0 , 0 , 0 ],
9
13
[0 , 1 , 0 , 0 , 0 , 0 , 0 ], # 0 are free path whereas 1's are obstacles
@@ -33,7 +37,15 @@ class Node:
33
37
True
34
38
"""
35
39
36
- def __init__ (self , pos_x , pos_y , goal_x , goal_y , g_cost , parent ):
40
+ def __init__ (
41
+ self ,
42
+ pos_x : int ,
43
+ pos_y : int ,
44
+ goal_x : int ,
45
+ goal_y : int ,
46
+ g_cost : float ,
47
+ parent : Optional [Node ],
48
+ ):
37
49
self .pos_x = pos_x
38
50
self .pos_y = pos_y
39
51
self .pos = (pos_y , pos_x )
@@ -72,16 +84,16 @@ class GreedyBestFirst:
72
84
(6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]
73
85
"""
74
86
75
- def __init__ (self , start , goal ):
87
+ def __init__ (self , start : tuple [ int , int ], goal : tuple [ int , int ] ):
76
88
self .start = Node (start [1 ], start [0 ], goal [1 ], goal [0 ], 0 , None )
77
89
self .target = Node (goal [1 ], goal [0 ], goal [1 ], goal [0 ], 99999 , None )
78
90
79
91
self .open_nodes = [self .start ]
80
- self .closed_nodes = []
92
+ self .closed_nodes : list [ Node ] = []
81
93
82
94
self .reached = False
83
95
84
- def search (self ) -> list [ tuple [ int ] ]:
96
+ def search (self ) -> Optional [ Path ]:
85
97
"""
86
98
Search for the path,
87
99
if a path is not found, only the starting position is returned
@@ -113,8 +125,9 @@ def search(self) -> list[tuple[int]]:
113
125
else :
114
126
self .open_nodes .append (better_node )
115
127
116
- if not ( self .reached ) :
128
+ if not self .reached :
117
129
return [self .start .pos ]
130
+ return None
118
131
119
132
def get_successors (self , parent : Node ) -> list [Node ]:
120
133
"""
@@ -143,7 +156,7 @@ def get_successors(self, parent: Node) -> list[Node]:
143
156
)
144
157
return successors
145
158
146
- def retrace_path (self , node : Node ) -> list [ tuple [ int ]] :
159
+ def retrace_path (self , node : Optional [ Node ] ) -> Path :
147
160
"""
148
161
Retrace the path from parents to parents until start node
149
162
"""
@@ -166,9 +179,9 @@ def retrace_path(self, node: Node) -> list[tuple[int]]:
166
179
167
180
greedy_bf = GreedyBestFirst (init , goal )
168
181
path = greedy_bf .search ()
182
+ if path :
183
+ for pos_x , pos_y in path :
184
+ grid [pos_x ][pos_y ] = 2
169
185
170
- for elem in path :
171
- grid [elem [0 ]][elem [1 ]] = 2
172
-
173
- for elem in grid :
174
- print (elem )
186
+ for elem in grid :
187
+ print (elem )
0 commit comments