Last active
January 23, 2021 20:24
-
-
Save nst/660fadc22857bde4ec2ef6f5db1fcfa8 to your computer and use it in GitHub Desktop.
Game of Life Visualization
This file contains 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
#!/usr/bin/env python | |
# description: Game of Life Visualization | |
# author: Nicolas Seriot | |
# idea: https://twitter.com/JacobJoaquin/status/923681854254825473 | |
# typical outout: http://seriot.ch/visualization/gol.gif | |
from PIL import Image, ImageDraw | |
from images2gif import writeGif | |
import random | |
NB_STEPS = 16 | |
GRID_SIZE = 16 | |
CELL_SIZE = 64 | |
DENSITY = 0.3 | |
def create_grid(N=24): | |
return [[0]*N for i in xrange(N)] | |
def fill_grid_randomly(g, density=0.5): | |
for x,y in [(x,y) for y in range(len(g)) for x in range(len(g[y]))]: | |
g[y][x] = 1 if random.uniform(0.0, 1.0) < density else 0 | |
return g | |
def nb_neighbnours(grid, x, y): | |
size = len(grid) | |
W = (size + x-1) % size | |
E = (size + x+1) % size | |
N = (size + y-1) % size | |
S = (size + y+1) % size | |
return sum([grid[N][W], grid[N][x], grid[N][E], | |
grid[y][W], grid[y][E], | |
grid[S][W], grid[S][x], grid[S][E]]) | |
def next(g): | |
new_grid = create_grid(N=len(g)) | |
for x,y in [(x,y) for y in range(len(g)) for x in range(len(g[y]))]: | |
n = nb_neighbnours(g, x, y) | |
if (g[y][x] == 0 and n == 3) or (g[y][x] == 1 and n in [2,3]): | |
new_grid[y][x] = 1 | |
return new_grid | |
def draw_grid(g, img, i): | |
draw = ImageDraw.Draw(img) | |
for x,y in [(x,y) for y in range(len(g)) for x in range(len(g[y])) if g[y][x] == 1]: | |
x1, x2 = CELL_SIZE + CELL_SIZE*x + 2*i, 2*CELL_SIZE + CELL_SIZE*x - 2*i | |
y1, y2 = CELL_SIZE + CELL_SIZE*y + 2*i, 2*CELL_SIZE + CELL_SIZE*y - 2*i | |
draw.ellipse((x1, y1, x2, y2), fill = "white", outline ='black') | |
def main(): | |
g = create_grid(N=GRID_SIZE) | |
fill_grid_randomly(g, density=DENSITY) | |
images = [] | |
img = Image.new('RGB', (len(g)*CELL_SIZE + 2*CELL_SIZE, len(g)*CELL_SIZE + 2*CELL_SIZE), "white") | |
for num_gen in range(NB_STEPS): | |
draw_grid(g, img, num_gen) | |
images.append(img) | |
g = next(g) | |
img = img.copy() | |
writeGif("gol.gif", images, duration=0.25) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment