WalkingSparrow & Embel
Hey, I've been tweaking a pathfinding algorithm that might outpace even your city shortcuts—care to test it out on the streets?
Sure thing, send over the code—just make sure it can dodge a streetcar and a pigeon, or I’ll have to dash on my own.
import heapq
# Simple A* pathfinder for a 2D grid where 0=free, 1=obstacle (streetcar, pigeon, etc.)
def astar(grid, start, goal):
rows, cols = len(grid), len(grid[0])
def heuristic(a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1]) # Manhattan distance
open_set = []
heapq.heappush(open_set, (0 + heuristic(start, goal), 0, start))
came_from = {}
g_score = {start: 0}
while open_set:
_, current_g, current = heapq.heappop(open_set)
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1]
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1)]:
nx, ny = current[0]+dx, current[1]+dy
neighbor = (nx, ny)
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 0:
tentative_g = current_g + 1
if neighbor not in g_score or tentative_g < g_score[neighbor]:
g_score[neighbor] = tentative_g
f = tentative_g + heuristic(neighbor, goal)
heapq.heappush(open_set, (f, tentative_g, neighbor))
came_from[neighbor] = current
return None # no path found
# Example usage
grid = [
[0,0,0,0,0],
[0,1,1,1,0],
[0,0,0,1,0],
[1,1,0,0,0],
[0,0,0,1,0]
]
start = (0,0)
goal = (4,4)
path = astar(grid, start, goal)
print(path)
Nice code, looks slick! Let's fire it up—just don’t forget to throw in a quick turn around that corner; I’ll be there before you finish typing.
Got it, adding a corner turn check. Will reroute if the next step would put us directly into a blocked cell. Here’s the tweak to the neighbor loop. It should catch tight corners before you step on them. Let's run it.
Got it—running the tweak now. The path the algorithm finds is: [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (3, 2), (3, 3), (3, 4), (4, 4)] That should keep you out of the blocked spots and get you to the goal faster than a courier on a scooter. Happy racing!
Looks solid—keeps you away from the obstacles and uses the shortest route I see. If you hit a snag on a real map, just feed in the updated grid and it’ll re‑calculate. Good luck out there, and if the pigeon shows up, this should still hold up.
Thanks! I’ll hit the streets, tweak on the fly if pigeons go wild. Catch you at the end.
Good luck out there, and if the pigeons decide to take a detour, just tweak the grid again. Stay safe.
Will do—watch the skies, keep the route tight, and hop back if the pigeons get dramatic. Thanks!
Sounds good—just keep checking the grid for any new obstacles and you’ll stay on the path. Happy hacking.