-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutonomous Robot Navigation.py
More file actions
70 lines (55 loc) · 1.85 KB
/
Copy pathAutonomous Robot Navigation.py
File metadata and controls
70 lines (55 loc) · 1.85 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
from simpleai.search import SearchProblem, astar
from simpleai.search.viewers import BaseViewer
# The grid environment (0 means free without obstruction, number 1 signifies an obstacle)
Grid = [
[1, 0, 1, 0, 1],
[0, 1, 1, 1, 0],
[0, 0, 0, 1, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
]
# Directions: up, down, left, right
Directions = [
('up', (1, 0)),
('down', (-1, 0)),
('left', (0, -1)),
('right', (0, 1)),
]
class NavigationProblem(SearchProblem):
def __init__(self, original_state=None):
super().__init__(original_state)
self.goal = None
def actions(self, state):
actions = []
x, y = state
for action, (dx, dy) in Directions:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < len(Grid) and 0 <= new_y < len(Grid[0]):
if Grid[new_x][new_y] == 0:
actions.append(action)
return actions
def result(self, state, action):
dx, dy = dict(Directions)[action]
return (state[0] + dx, state[1] + dy)
def is_goal(self, state):
return state == self.goal
def cost(self, state1, action, state2):
return 1 # Uniform cost for all moves
def heuristic(self, state):
x1, y1 = state
x2, y2 = self.goal
return abs(x1 - x2) + abs(y1 - y2)
# Define the initial and goal states
initial_state = (0, 0) # Bottom-left corner
goal_state = (4, 4) # Top-right corner
# Instantiate the problem
problem = NavigationProblem(original_state=initial_state)
problem.goal = goal_state
# Use A* search
viewer = BaseViewer()
result = astar(problem, viewer=viewer)
# Conclusive results
print("Path to goal:")
for action, state in result.path():
print(f"Action: {action}, State: {state}")
print(f"\nTotal cost: {result.cost}")