-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid.py
More file actions
60 lines (49 loc) · 2.14 KB
/
grid.py
File metadata and controls
60 lines (49 loc) · 2.14 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
class Grid:
def __init__(self, rows: int, cols: int, cell_size: int):
self.rows = rows
self.cols = cols
self.cell_size = cell_size
self.obstacles: set[tuple[int, int]] = set()
self.start: tuple[int, int] | None = None
self.end: tuple[int, int] | None = None
def pixel_to_cell(self, px: int, py: int) -> tuple[int, int]:
col = px // self.cell_size
row = py // self.cell_size
return (row, col)
def cell_to_pixel_center(self, row: int, col: int) -> tuple[float, float]:
x = col * self.cell_size + self.cell_size / 2
y = row * self.cell_size + self.cell_size / 2
return (x, y)
def cell_to_pixel_topleft(self, row: int, col: int) -> tuple[int, int]:
return (col * self.cell_size, row * self.cell_size)
def in_bounds(self, row: int, col: int) -> bool:
return 0 <= row < self.rows and 0 <= col < self.cols
def is_blocked(self, row: int, col: int) -> bool:
return (row, col) in self.obstacles
def set_obstacle(self, row: int, col: int) -> None:
if self.in_bounds(row, col):
self.obstacles.add((row, col))
def remove_obstacle(self, row: int, col: int) -> None:
self.obstacles.discard((row, col))
def toggle_obstacle(self, row: int, col: int) -> None:
if (row, col) in self.obstacles:
self.obstacles.discard((row, col))
else:
self.obstacles.add((row, col))
def clear(self) -> None:
self.obstacles.clear()
self.start = None
self.end = None
def get_neighbors(self, row: int, col: int) -> list[tuple[int, int]]:
neighbors = []
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nr, nc = row + dr, col + dc
if self.in_bounds(nr, nc) and not self.is_blocked(nr, nc):
neighbors.append((nr, nc))
return neighbors
def get_obstacle_rects_px(self) -> list[tuple[int, int, int, int]]:
rects = []
for (r, c) in self.obstacles:
x, y = self.cell_to_pixel_topleft(r, c)
rects.append((x, y, self.cell_size, self.cell_size))
return rects