-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_grid.py
More file actions
241 lines (191 loc) · 7.14 KB
/
simple_grid.py
File metadata and controls
241 lines (191 loc) · 7.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/env python3
"""
Simple Grid Example for Circle-WFC
기본적인 그리드에서 경로 탐색 테스트
"""
import sys
import os
# src 폴더를 path에 추가
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
from grid import Grid, TileState
from pathfinder import CircleWFC
from circle_layer import CircleLayer
def visualize_grid(grid: Grid, path: list = None, start: tuple = None, end: tuple = None) -> str:
"""그리드를 시각화
기호:
S, E: 시작/끝점
*: 경로
#: 붕괴된 ROAD
B: 붕괴된 BUILDING
.: 붕괴된 EMPTY
X: 제약 있는 타일 (ROAD 불가능)
?: 미붕괴 타일
"""
path_set = set(path) if path else set()
lines = []
for y in range(grid.height):
line = ""
for x in range(grid.width):
if (x, y) == start:
line += "S"
elif (x, y) == end:
line += "E"
elif (x, y) in path_set:
line += "*"
else:
tile = grid.get(x, y)
if tile.is_collapsed:
if tile.collapsed_state == TileState.ROAD:
line += "#"
elif tile.collapsed_state == TileState.BUILDING:
line += "B"
elif tile.collapsed_state == TileState.EMPTY:
line += "."
else:
line += "~"
else:
# 미붕괴 상태: ROAD가 불가능하면 제약 표시
if TileState.ROAD not in tile.possible_states:
line += "X"
else:
line += "?"
lines.append(line)
return "\n".join(lines)
def visualize_circles(circle_layer: CircleLayer, width: int, height: int) -> str:
"""원주 레이어 시각화"""
# 간단한 ASCII 시각화
grid = [['.' for _ in range(width)] for _ in range(height)]
# 원 중심 표시
for i, circle in enumerate(circle_layer.circles):
cx, cy = int(circle.center.x), int(circle.center.y)
if 0 <= cx < width and 0 <= cy < height:
grid[cy][cx] = str(i % 10)
# 교점 표시
for points in circle_layer.intersection_points:
for point in points:
px, py = point.to_grid()
if 0 <= px < width and 0 <= py < height:
grid[py][px] = 'X'
# 시작점, 끝점
sx, sy = circle_layer.get_start_grid()
ex, ey = circle_layer.get_end_grid()
if 0 <= sx < width and 0 <= sy < height:
grid[sy][sx] = 'S'
if 0 <= ex < width and 0 <= ey < height:
grid[ey][ex] = 'E'
return "\n".join("".join(row) for row in grid)
def example_basic():
"""기본 예제: 빈 그리드에서 경로 탐색"""
print("=" * 50)
print("Example 1: Basic Path Finding")
print("=" * 50)
# 15x15 그리드
grid = Grid(15, 15)
start = (1, 1)
end = (13, 13)
# Circle-WFC 실행
pathfinder = CircleWFC(grid, num_layers=3)
path = pathfinder.find(start, end)
print(f"\nStart: {start}, End: {end}")
print(f"Path found: {len(path) > 0}")
print(f"Path length: {len(path)}")
print(f"\nGrid visualization:")
print(visualize_grid(grid, path, start, end))
print(f"\nStats: {pathfinder.get_stats()}")
def example_with_obstacles():
"""장애물이 있는 예제 (WFC 방식)"""
print("\n" + "=" * 50)
print("Example 2: Path Finding with Obstacles (WFC Style)")
print("=" * 50)
# 20x20 그리드
grid = Grid(20, 20)
# 장애물 영역 설정 (WFC 제약 방식)
# 이 영역에서는 ROAD가 불가능 (possible_states에서 ROAD 제거)
print("Setting obstacle area constraints (5-15, 8-12)...")
grid.set_area_constraint(
x_range=(5, 15),
y_range=(8, 12),
forbidden_states={TileState.ROAD}
)
start = (2, 2)
end = (17, 17)
# Circle-WFC 실행
pathfinder = CircleWFC(grid, num_layers=5)
path = pathfinder.find(start, end)
print(f"\nStart: {start}, End: {end}")
print(f"Path found: {len(path) > 0}")
print(f"Path length: {len(path)}")
print(f"\nGrid visualization:")
print(visualize_grid(grid, path, start, end))
print(f"\nStats: {pathfinder.get_stats()}")
def example_circle_visualization():
"""원주 레이어 시각화"""
print("\n" + "=" * 50)
print("Example 3: Circle Layer Visualization")
print("=" * 50)
start = (2, 10)
end = (27, 10)
# 원주 레이어 생성
circle_layer = CircleLayer(start, end, num_layers=5)
print(f"\nStart: {start}, End: {end}")
print(f"Total distance: {circle_layer.total_distance:.2f}")
print(f"Number of circles: {len(circle_layer.circles)}")
print(f"\nCircle centers:")
for i, circle in enumerate(circle_layer.circles):
print(f" Circle {i}: center={circle.center}, radius={circle.radius:.2f}")
print(f"\nIntersection points:")
for i, points in enumerate(circle_layer.intersection_points):
print(f" Between circle {i} and {i+1}: {points}")
print(f"\nLayer order from middle: {circle_layer.get_layer_order_from_middle()}")
print(f"Intersection order from middle: {circle_layer.get_intersection_order_from_middle()}")
print(f"\nVisualization (30x20):")
print(visualize_circles(circle_layer, 30, 20))
def example_wfc_propagation():
"""WFC 전파를 명확히 보여주는 예제"""
print("\n" + "=" * 50)
print("Example 4: WFC Propagation Visualization")
print("=" * 50)
# 작은 그리드로 전파 과정 확인
grid = Grid(20, 15)
# 중앙에 장애물 블록 만들기 (우회 필요)
print("Creating central obstacle block...")
grid.set_area_constraint(
x_range=(8, 12),
y_range=(4, 11),
forbidden_states={TileState.ROAD}
)
start = (2, 7)
end = (17, 7)
pathfinder = CircleWFC(grid, num_layers=5)
path = pathfinder.find(start, end)
print(f"\nStart: {start}, End: {end}")
print(f"Path found: {len(path) > 0}")
print(f"Path length: {len(path)}")
print(f"\nGrid visualization:")
print("(X = constraint/obstacle, * = path, ? = uncollapsed)")
print(visualize_grid(grid, path, start, end))
print(f"\nStats: {pathfinder.get_stats()}")
print("\nNotice: Path automatically routes around the obstacle!")
print("This is WFC propagation in action - no A* heuristic needed.")
def example_different_layers():
"""레이어 수에 따른 비교"""
print("\n" + "=" * 50)
print("Example 5: Comparing Different Layer Counts")
print("=" * 50)
start = (1, 1)
end = (18, 18)
for num_layers in [1, 3, 5, 7]:
# 새 그리드 생성
grid = Grid(20, 20)
pathfinder = CircleWFC(grid, num_layers=num_layers)
path = pathfinder.find(start, end)
stats = pathfinder.get_stats()
print(f"\nLayers: {num_layers}")
print(f" Path length: {stats['path_length']}")
print(f" Road tiles: {stats['road_tiles']}")
if __name__ == "__main__":
example_basic()
example_with_obstacles()
example_circle_visualization()
example_wfc_propagation()
example_different_layers()