-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid.py
More file actions
50 lines (42 loc) · 1.62 KB
/
grid.py
File metadata and controls
50 lines (42 loc) · 1.62 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
import random
FREE = 0
OBSTACLE = 1
START = 2
GOAL = 3
class Grid:
def __init__(self, rows=10, cols=10, obstacle_ratio=0.2,
start=(0, 0), goal=(9, 9), seed=None):
self.rows = rows
self.cols = cols
self.start = start
self.goal = goal
self.cells = [[FREE] * cols for _ in range(rows)]
self._place_endpoints()
self._generate_obstacles(obstacle_ratio, seed)
def _place_endpoints(self):
r0, c0 = self.start
r1, c1 = self.goal
self.cells[r0][c0] = START
self.cells[r1][c1] = GOAL
def _generate_obstacles(self, ratio, seed):
if seed is not None:
random.seed(seed)
count = int(self.rows * self.cols * ratio)
placed = 0
blocked = {self.start, self.goal}
while placed < count:
r = random.randint(0, self.rows - 1)
c = random.randint(0, self.cols - 1)
if (r, c) not in blocked and self.cells[r][c] == FREE:
self.cells[r][c] = OBSTACLE
placed += 1
# ── helpers ──────────────────────────────────────────────
def in_bounds(self, r, c):
return 0 <= r < self.rows and 0 <= c < self.cols
def is_obstacle(self, r, c):
return self.cells[r][c] == OBSTACLE
def get_neighbors(self, r, c):
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nr, nc = r + dr, c + dc
if self.in_bounds(nr, nc) and not self.is_obstacle(nr, nc):
yield (nr, nc)