Skip to content

Instantly share code, notes, and snippets.

@shetharp
Created February 6, 2020 01:02
Show Gist options
  • Save shetharp/d9dd7facd48ffb241a6ea3c37ce3e9f9 to your computer and use it in GitHub Desktop.
Save shetharp/d9dd7facd48ffb241a6ea3c37ce3e9f9 to your computer and use it in GitHub Desktop.
Conway's Game of Life
exampleGrid = [
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
]
def getNeighborIdx(i, j, size):
"""Returns a list of indexes to visit that are not out of bounds given the grid size"""
neighbors = []
for x in [-1, 0, 1]:
for y in [-1, 0, 1]:
coord = [i+x, j+y]
if not (coord[0] < 0 or
coord[0] >= size or
coord[1] < 0 or
coord[1] >= size) and not (coord[0] == i and coord[1] == j):
neighbors.append(coord)
return neighbors
def countAliveNeighbors(grid, neighbors):
count = 0
for neighbor in neighbors:
i, j = neighbor
isAlive = grid[i][j]
if isAlive:
count += 1
return count
def gameOfLife(grid):
size = len(grid)
updatedGrid = [[0]*size for i in range(size)]
for i, row in enumerate(grid):
for j, isAlive in enumerate(grid[i]):
neighbors = getNeighborIdx(i, j, size)
numLiveNeighbors = countAliveNeighbors(grid, neighbors)
if isAlive and numLiveNeighbors < 2:
updatedGrid[i][j] = 0
elif isAlive and numLiveNeighbors > 3:
updatedGrid[i][j] = 0
elif (not isAlive) and numLiveNeighbors == 3:
updatedGrid[i][j] = 1
else:
updatedGrid[i][j] = isAlive
return updatedGrid
def printGrid(grid):
for i, row in enumerate(grid):
for j, isAlive in enumerate(grid[i]):
print(isAlive)
print('---')
# Run
updatedGrid = gameOfLife(exampleGrid)
printGrid(updatedGrid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment