Skip to content

Instantly share code, notes, and snippets.

@ranuzz
Created June 9, 2021 02:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranuzz/0ff833b4efff9ab7e145636dfeb18085 to your computer and use it in GitHub Desktop.
Save ranuzz/0ff833b4efff9ab7e145636dfeb18085 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Processing with Python
"""
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
conway's game of life
"""
from random import randint
def gameOfLife(grid):
state = {}
rows = len(grid)
if rows == 0:
return
cols = len(grid[0])
for i in range(rows):
for j in range(cols):
an = 0
cs = grid[i][j]
if i-1 >=0 and j-1 >= 0 and grid[i-1][j-1] == 1:
an += 1
if i-1 >= 0 and grid[i-1][j] == 1:
an += 1
if i-1 >= 0 and j+1 < cols and grid[i-1][j+1] == 1:
an += 1
if i+1 < rows and j-1 >= 0 and grid[i+1][j-1] == 1:
an += 1
if i+1 < rows and grid[i+1][j] == 1:
an += 1
if i+1 < rows and j+1 < cols and grid[i+1][j+1] == 1:
an += 1
if j-1 >= 0 and grid[i][j-1] == 1:
an += 1
if j+1 < cols and grid[i][j+1] == 1:
an += 1
if an < 2 and cs == 1:
state[(i, j)] = 0
elif an > 3 and cs == 1:
state[(i, j)] = 0
elif an == 3 and cs == 0:
state[(i, j)] = 1
for k, v in state.items():
grid[k[0]][k[1]] = v
def randomState(rows, cols, alive):
state = {}
tots = 0
while tots < alive:
r = randint(0, rows-1)
c = randint(0, cols-1)
if (r, c) in state:
continue
state[(r, c)] = 1
tots += 1
return state
def initBoard(rows, cols, state):
global grid
grid = [[0 for _ in range(cols)] for _ in range(rows)]
for k, v in state.items():
grid[k[0]][k[1]] = v
def setup():
size(1080/2, 1920/2)
frameRate(2)
grid = []
initBoard(53, 95, randomState(53, 95, 1000))
def draw():
background(255)
fill(0)
global grid
rows = len(grid)
if rows == 0:
return
cols = len(grid[0])
for i in range(rows):
for j in range(cols):
if grid[i][j]:
rect(5+i*10, 5+j*10, 8, 8)
gameOfLife(grid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment