Skip to content

Instantly share code, notes, and snippets.

@bbb651
Created December 31, 2023 02:26
Show Gist options
  • Select an option

  • Save bbb651/ff72dc7bdaa8b92b58a543ed1d4c295a to your computer and use it in GitHub Desktop.

Select an option

Save bbb651/ff72dc7bdaa8b92b58a543ed1d4c295a to your computer and use it in GitHub Desktop.
PuzzleScript Image Importer
from __future__ import annotations
from typing import Iterator
import sys
from itertools import count, product, starmap
import numpy as np
from numpy.typing import NDArray
import imageio
def chunks(a: NDArray, shape: tuple[int, ...]) -> Iterator[NDArray]:
def ceildiv(a, b): return -(-a//b)
for indices in product(*map(range, starmap(ceildiv, zip(a.shape, shape)))):
yield a[*(np.s_[n*i:n*(i+1)] for i, n in zip(indices, shape)), ...]
chars = filter(str.islower, map(chr, count()))
image = imageio.v3.imread(sys.argv[1])
objects = []
level = []
for index, chunk in enumerate(chunks(image, (5, 5))):
colors = []
sprite = ""
for i in range(chunk.shape[0]):
for j in range(chunk.shape[1]):
color = f"#{3*'{:02x}'}".format(*chunk[i, j])
try:
c = str(colors.index(color))
except ValueError:
# TODO: Use https://en.wikipedia.org/wiki/Color_quantization to improve accuracy
if len(colors) >= 10:
print("WARNING: Run out of color values", file=sys.stderr)
c = "9"
else:
colors.append(color)
c = str(len(colors) - 1)
sprite += c
sprite += "\n"
# TODO: Merge exact duplicates to the same tile, potentially across multiple images
legend = next(chars)
obj = f"chunk{index} {legend}\n{' '.join(colors)}\n{sprite}"
objects.append(obj)
level.append(legend)
print("OBJECTS")
print("\n".join(objects))
print("Background\nblack\n")
print("Player\nblack\n")
print("LEGEND")
print("SOUNDS")
print("COLLISIONLAYERS")
print("Background")
print("Player")
print(",".join(f"chunk{i}" for i in range(len(objects))))
print("RULES")
print("WINCONDITIONS")
print("LEVELS")
width = -(-image.shape[1] // 5)
i = 0
while line := level [i:i+width]:
print("".join(line))
i += width
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment