Skip to content

Instantly share code, notes, and snippets.

@rommix0
Forked from EllieTheYeen/actuallyfunctioningpath.gif
Created January 22, 2025 02:11
Show Gist options
  • Select an option

  • Save rommix0/dcb0b244fcdd1ec086103f5485d9eebb to your computer and use it in GitHub Desktop.

Select an option

Save rommix0/dcb0b244fcdd1ec086103f5485d9eebb to your computer and use it in GitHub Desktop.
A test where I implemented a pathfinding algorithm without actually looking up how to write one for the challenge and it works most of the time
from PIL import Image, ImageDraw
from IPython.display import Image as Im
import random
import io
def chebychev(c1, c2):
return max(abs(c1[0] - c2[0]), abs(c1[1] - c2[1]))
w, h = 100, 100
res = 400, 400
pw = res[0] / w
ph = res[1] / h
moves = set()
grid = dict()
EMPTY = 1
TAKEN = 2
BLOCKED = 3
POSSIBLE = 4
g = (EMPTY,) * 7 + (BLOCKED,)
for hi in range(h):
for wi in range(w):
grid[wi, hi] = random.choice(g)
imgs = []
start = 0, 0
target = w - 1, h - 1
s = start
for it in range(10000):
grid[s[0], s[1]] = TAKEN
up = s[0], s[1] - 1
right = s[0] + 1, s[1]
down = s[0], s[1] + 1
left = s[0] - 1, s[1]
if up[1] >= 0 and grid[up] not in (BLOCKED, TAKEN, POSSIBLE):
grid[up] = POSSIBLE
moves.add(up)
if down[1] < h and grid[down] not in (BLOCKED, TAKEN, POSSIBLE):
grid[down] = POSSIBLE
moves.add(down)
if right[0] < w and grid[right] not in (BLOCKED, TAKEN, POSSIBLE):
grid[right] = POSSIBLE
moves.add(right)
if left[0] >= 0 and grid[left] not in (BLOCKED, TAKEN, POSSIBLE):
grid[left] = POSSIBLE
moves.add(left)
doend = False
if s == target:
doend = True
#if it % 10 == 0 or doend:
im = Image.new('RGBA', res, (0, 0, 0))
d = ImageDraw.Draw(im)
for (a, b), slot in grid.items():
col = "grey"
if slot == BLOCKED:
col = "blue"
elif slot == TAKEN:
col = "orange"
elif slot == POSSIBLE:
col = "brown"
d.rectangle((a * pw, b * ph, a * pw + pw, b * ph + ph), fill=col)
imgs.append(im)
if not moves or doend:
break
closest = sorted(moves, key=lambda c: chebychev(target, c))
if not closest:
break
s = closest[0]
moves.remove(s)
ii = io.BytesIO()
imgs[0].save(ii, 'gif', loop=0, save_all=True, append_images=imgs[1:])
Im(ii.getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment