-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid.py
More file actions
42 lines (35 loc) · 1.44 KB
/
grid.py
File metadata and controls
42 lines (35 loc) · 1.44 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
import numpy as np
import random
class Grid:
"""
2D occupancy grid map for rover navigation.
Cells are represented as integers:
0 = free
1 = obstacle
"""
def __init__(self, width: int = 20, height: int = 20, obstacle_ratio: float = 0.25):
"""
Args:
width: Number of columns.
height: Number of rows.
obstacle_ratio: Fraction of cells randomly set as obstacles (0.0-1.0).
"""
self.width = width
self.height = height
self.grid = np.zeros((height, width), dtype=int)
self._place_obstacles(obstacle_ratio)
def _place_obstacles(self, ratio: float):
"""Randomly populate obstacles, ensuring start (0,0) and goal are always free."""
for y in range(self.height):
for x in range(self.width):
if random.random() < ratio:
self.grid[y][x] = 1
self.grid[0][0] = 0
self.grid[self.height - 1][self.width - 1] = 0
def is_free(self, x: int, y: int) -> bool:
"""Return True if (x, y) is within bounds and not an obstacle."""
return 0 <= x < self.width and 0 <= y < self.height and self.grid[y][x] == 0
def get_neighbors(self, x: int, y: int) -> list:
"""Return free 4-connected neighbors of (x, y)."""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
return [(x+dx, y+dy) for dx, dy in directions if self.is_free(x+dx, y+dy)]