Computational Art by Hossein Askari

game of life

·

The idea of having a living organism in a cyber space was always fascinating for me, playing videogames when I was child always amazed me, to see people “living” in a nonexistent world, and to be able to interact with them.

in the recent years, my Instagram account helped me a lot, from meeting new friends to connecting to more professional people and artists, and i was always grateful for this little community of mine.

this time i tried to recreate this community in a simple game of life simulation, the emotional stuff can be found on my account, where it belongs. but i wanted to share my code as well, so, here we go!

import numpy as np
import matplotlib.pyplot as plt 
import matplotlib.animation as animation
import random

# Function to add 'num_alive' alive cells in random locations
def add_cells(num_alive, grid):
    for _ in range(num_alive):
        x, y = random.randint(0, grid.shape[0]-1), random.randint(0, grid.shape[1]-1)
        grid[x][y] = 1

# Count the number of neighbours
def count_neighbours(grid):
    num_neighbours = np.zeros((grid.shape[0], grid.shape[1]))
    for dx in [-1, 0, 1]:
        for dy in [-1, 0, 1]:
            if dx != 0 or dy != 0:
                num_neighbours += np.roll(np.roll(grid, dy, axis=0), dx, axis=1)
    return num_neighbours

# Update the grid of cells according to the rules
def step(grid):
    num_neighbours = count_neighbours(grid)
    new_grid = np.where(grid==1, (num_neighbours == 2) | (num_neighbours == 3), num_neighbours == 3)
    return new_grid

# Visualization
def animate(steps, num_alive):
    fig, ax = plt.subplots()
    grid = np.zeros((75, 75))
    add_cells(num_alive, grid)
    img = ax.imshow(grid, cmap='binary')
    ani = animation.FuncAnimation(fig, update, fargs=(img, grid, steps), frames=steps, repeat=False)
    ani.save('game_of_life.gif', writer='pillow', fps=30)

# Function to handle animation frames
def update(frameNum, img, grid, steps):
    new_grid = step(grid)
    img.set_array(new_grid)
    grid[:] = new_grid[:]
    return img,

# Run the game
animate(3000, 2446) # 3000 steps, 2446 initial living cells

you can also read more about the game of life here : Conway’s Game of Life – Wikipedia

¶¶¶¶¶

¶¶¶¶¶

¶¶¶¶¶

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept the Privacy Policy