Skip to content

Instantly share code, notes, and snippets.

@Legend-of-iPhoenix
Last active February 8, 2019 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Legend-of-iPhoenix/a33306aea25665652bf4552a6d76804c to your computer and use it in GitHub Desktop.
Save Legend-of-iPhoenix/a33306aea25665652bf4552a6d76804c to your computer and use it in GitHub Desktop.
from random import randint, seed
from math import floor
from PIL import Image
##################
# Algorithm for generating a single tile
# note that the algorithm I use to generate several tiles at once is the same in principle but steps like normalizing are done globally, as opposed to per-tile
# 1) With each pixel, generate a number based on the
# 1a) calculate the euclidean squared distance
# 1b) turn each distance into a percentage (in the inclusive range [0, 1]) of the total
# 1c) multiply each percentage by the respective weight
# 2) normalize each pixel so that the darkest pixel is always 0 and the lightest is always 255
# 3) return tile array
#
# Inputs:
# a, b, c, d: weights used, 0-255
# width: horizontal resolution of tile
# height: verticle resolution of tile
# colors: number of possible outputs used- I use this to get a "stepped" greyscale
#
# Output:
# Array of arrays containing values in the inclusive range [0, 255] representing the value of each pixel
def genTile(a, b, c, d, width, height, colors):
def genPixel(row, col):
def sq(n): # simple helper function for squaring
return n * n
# euclidean distance from wach corner,
# minus square roots
# If you modify this to include square roots, it's less interesting in my opinion.
# coefficient is the wrong term, using it because I couldn't think of anything better
coeffs = [
sq(col) + sq(row), # (0, 0)
sq(width - col) + sq(row), # (width, 0)
sq(col) + sq(height - row), # (0, height)
sq(width - col) + sq(height - row) # (width, height)
]
coeffs = [coeff / sum(coeffs) for coeff in coeffs] # map may be better here but whatever
coeffs[0] *= a
coeffs[1] *= b
coeffs[2] *= c
coeffs[3] *= d
return floor(sum(coeffs))
tile = [[0 for j in range(width)] for i in range(height)]
for row in range(height):
for col in range(width):
tile[row][col] = genPixel(row, col)
min = 256
max = 0
for row in tile:
for point in row:
if point < min:
min = point
if point > max:
max = point
normalizer = (colors + 1) / (max - min)
for row in range(height):
for col in range(width):
tile[row][col] = round(((colors + 1) - floor((tile[row][col] - min) * normalizer)) * 255 / colors)
return tile
tile = genTile(90, 70, 190, 60, 64, 64, 8)
image = Image.new('RGB', (64, 64))
data = []
for row in tile:
for col in row:
data.append((col, col, col))
image.putdata(data)
image.save("tile.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment