Last active
February 9, 2022 03:01
-
-
Save discretegames/f6e37a4c5cace0acd7450de25517ad2d to your computer and use it in GitHub Desktop.
All 256 elementary cellular automata
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Generates an image of all 256 1-dimensional cellular automata. | |
from PIL import Image # from `pip install Pillow` | |
def ca1d(rule=90, size=5): | |
w, h = 2**size - 1, 2**(size - 1) | |
ca = [[0] * w for _ in range(h)] | |
ca[0][w//2] = 1 | |
rules = [(rule >> b) % 2 for b in range(8)] | |
for y in range(1, h): | |
for x in range(w): | |
l, c, r = ca[y-1][x-1], ca[y-1][x], ca[y-1][(x+1) % w] | |
ca[y][x] = rules[4*l + 2*c + r] | |
return ca | |
def ca1d_image(rule=90, size=5, fg=(0, 0, 0), bg=(255, 255, 255)): | |
ca = ca1d(rule, size) | |
w, h = len(ca[0]), len(ca) | |
img = Image.new('RGB', (w, h), bg) | |
pix = img.load() | |
for y in range(h): | |
for x in range(w): | |
pix[x, y] = fg if ca[y][x] else bg | |
return img | |
def ca1d_tiled(size=5, fg=(0, 0, 0, 255), bg=(255, 255, 255), space=(32, 128, 255), gap=4, scale=4): | |
imgs = [ca1d_image(rule, size, fg, bg) for rule in range(256)] | |
iw, ih = imgs[0].size | |
w, h = 16 * (iw + gap) + gap, 16 * (ih + gap) + gap | |
tiled = Image.new('RGB', (w, h), bg if space is None else space) | |
i = 0 | |
for y in range(gap, h, ih + gap): | |
for x in range(gap, w, iw + gap): | |
tiled.paste(imgs[i], (x, y)) | |
i += 1 | |
return tiled.resize((w*scale, h*scale), Image.NEAREST) | |
img = ca1d_tiled() | |
img.save('ca.png') | |
img.show() | |
# Learn more: https://mathworld.wolfram.com/ElementaryCellularAutomaton.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment