Skip to content

Instantly share code, notes, and snippets.

@KylePiira
Created November 25, 2018 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KylePiira/86b4c04cf768854d9fac3da81a1b4f37 to your computer and use it in GitHub Desktop.
Save KylePiira/86b4c04cf768854d9fac3da81a1b4f37 to your computer and use it in GitHub Desktop.
Game of Life in Python
"""
Kyle's Game of Life Implementation
1) live cells die if they have 0, 1, or 4+ neighbors
2) empty cells have a birth if they have exactly three neighbors
"""
import numpy as np
# Create a blank board
board = np.zeros((5, 5))
def iterate(board):
"""
This function takes the current board state and returns the next state.
"""
conv_board = np.zeros((7, 7))
conv_board[1:6, 1:6] = board
conv = np.lib.stride_tricks.as_strided(
conv_board,
(5, 5, 3, 3), # view shape
(56, 8, 56, 8) # strides
)
# The new board
b = np.zeros((5, 5))
for i in range(5):
for j in range(5):
# Count the number of neighbor live cells
if conv[i, j, 1, 1] == 1:
# Subtract itself from total count
b[i, j] = conv[i, j].sum() - 1
else:
b[i, j] = conv[i, j].sum()
# Cells with 0, 1, or 4+ die
b[np.any([b <= 1, b >= 4], axis=0)] = 0
# Living cells with 2 neighbors get to keep living
b[np.all([b == 2, board == 1], axis=0)] = 1
# Dead cells with 2 neighbors stay dead
b[np.all([b == 2, board == 0], axis=0)] = 0
# All cells with 3 neighbors live
b[b == 3] = 1
# Return the new board state
return b
if __name__ == '__main__':
while input('Continue? [y/n] ') == 'y':
print(board)
board = iterate(board)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment