Skip to content

Instantly share code, notes, and snippets.

@mekhami
Last active March 23, 2016 22:39
Show Gist options
  • Select an option

  • Save mekhami/61a8691c2e84ebd8243d to your computer and use it in GitHub Desktop.

Select an option

Save mekhami/61a8691c2e84ebd8243d to your computer and use it in GitHub Desktop.
from copy import deepcopy
grid = [[0]*10 for x in range(8)]
grid[4][4] = 1
grid[4][5] = 1
grid[4][6] = 1
def life_check(grid, x, y):
width = len(grid[0])
height = len(grid)
live_neighbours = 0
cell = grid[x][y]
# Enables board wrapping
# For instance, coordinates (7, 4), right would be 'off the grid'.
# To wrap around, do 8 (the right coordinate) modulo 8 (the width of the board)
# which returns 0, the first column wrapped around.
right = (x+1) % height
left = (x-1) % height
up = (y+1) % width
down = (y-1) % width
# add all the values together to find out how many living neighbors it has
live_neighbours += grid[right][y] # right
live_neighbours += grid[left][y] # left
live_neighbours += grid[x][down] # down
live_neighbours += grid[x][up] # up
live_neighbours += grid[left][up] # left up
live_neighbours += grid[right][up] # right up
live_neighbours += grid[left][down] # left down
live_neighbours += grid[right][down] # right down
if cell == 1: # Cell is alive
if live_neighbours == 2 or live_neighbours == 3:
return True
if live_neighbours > 3: # Overpopulation, dead
return False
if live_neighbours < 2: # Underpopulation, dead
return False
if cell == 0 and live_neighbours == 3: # Cell is dead and has three live neighbors, reproduction.
return True
return False
def mutate(grid):
grid_copy = deepcopy(grid) # Have to make a copy of the grid in question
for x in range(len(grid_copy)):
for y in range(len(grid_copy[x])):
grid_copy[x][y] = int(life_check(grid, x, y))
return grid_copy
def as_string(grid):
return '\n'.join(''.join(str(i) for i in row) for row in grid)
def run_mutations(number, grid):
print(as_string(grid))
print('\n')
for x in range(number):
grid = mutate(grid)
print(as_string(grid))
print('\n')
run_mutations(10, grid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment