Skip to content

Instantly share code, notes, and snippets.

@limitpointinf0
Last active July 27, 2018 11:30
Show Gist options
  • Save limitpointinf0/09eaaf5166b9f410153d59959df4cf81 to your computer and use it in GitHub Desktop.
Save limitpointinf0/09eaaf5166b9f410153d59959df4cf81 to your computer and use it in GitHub Desktop.
Run John Conway's Game of Life in the console!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import numpy as np
import itertools
import time
import argparse
#from termcolor import colored
def display_gen(mat):
board = ''
for i,x in enumerate(mat):
line = '\n'
for j,y in enumerate(x):
if mat[i][j] == 1:
line += ' o '
else:
line += ' '
board += line
print board
def seed_mat(dimx, dimy):
return np.random.randint(2, size=(dimx, dimy))
def get_next(arr):
mat = arr.copy()
new_values = []
x_coords = list(range(arr.shape[0]))
y_coords = list(range(arr.shape[1]))
coords = list(itertools.product(x_coords, y_coords))
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
adj = 0
if (i-1,j-1) in coords:
adj += arr[i-1][j-1]
if (i-1,j) in coords:
adj += arr[i-1][j]
if (i-1,j+1) in coords:
adj += arr[i-1][j+1]
if (i,j-1) in coords:
adj += arr[i][j-1]
if (i,j+1) in coords:
adj += arr[i][j+1]
if (i+1,j-1) in coords:
adj += arr[i+1][j-1]
if (i+1,j) in coords:
adj += arr[i+1][j]
if (i+1,j+1) in coords:
adj += arr[i+1][j+1]
#adjust statuses
if arr[i,j] == 1: #alive
if adj < 2: #underpopulation and dies
mat[i][j] = 0
elif (adj >= 2) and (adj < 4): #lives on
mat[i][j] = 1
else: #overpopulation and dies
mat[i][j] = 0
else: #dead
if adj == 3: #reproduction
mat[i][j] = 1
else: #stays dead
mat[i][j] = 0
return mat
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='run the Game of Life simulation')
parser.add_argument('-d', '--dim', help='set dimension of board')
parser.add_argument('-n', '--iters', help='set number of iterations', default='100')
parser.add_argument('-s', '--sec', help='seconds before refresh')
args = parser.parse_args()
gen = seed_mat(int(args.dim),int(args.dim))
for i in range(int(args.iters)):
gen = get_next(gen)
os.system('clear')
display_gen(gen)
time.sleep(float(args.sec))
numpy==1.15.0
pkg-resources==0.0.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment