Skip to content

Instantly share code, notes, and snippets.

@yashbonde
Last active March 28, 2020 21:11
Show Gist options
  • Save yashbonde/13d70b067e98bdc89d3250a6c0c7596a to your computer and use it in GitHub Desktop.
Save yashbonde/13d70b067e98bdc89d3250a6c0c7596a to your computer and use it in GitHub Desktop.
"""making conway's game of life. It has the following instructions:
1. Any live cell with fewer than two live neighbors dies, as if by underpopulation.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by overpopulation.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction."""
import time
import os
import numpy as np
import argparse
# helper functions
def render_board(array):
val = {1: "*", 0: "-"}
t = ''
for row in board:
t += ' '.join([val[x] for x in row]) + '\n'
# t += ' '.join([val[x] for x in row]) + '\n'
return t
def update_board(array):
live_locations = array == True
new_board = np.zeros(shape = (args.s, args.s))
for ridx, row in enumerate(live_locations):
for cidx, item in enumerate(row):
if item:
# this cell is alive; get count of nearby cells
nearby_cell_count = np.sum(array[
max(0, ridx-1): min(args.s, ridx+1) + 1,
max(0, cidx-1): min(args.s, cidx+1) + 1]
) - 1 # for itself
# print("nearby_cell_count", nearby_cell_count)
# if nearby_cell_count < 2:
# # dies of underpopulation
if int(nearby_cell_count) in [2, 3]:
# lives
new_board[ridx, cidx] = 1
# elif nearby_cell_count > 3:
# # dies of over population
else:
nearby_cell_count = np.sum(array[
max(0, ridx-1): min(args.s, ridx+1) + 1,
max(0, cidx-1): min(args.s, cidx+1) + 1]
)
# print("nearby_cell_count", nearby_cell_count)
if int(nearby_cell_count) == 3:
# grows by reproduction
new_board[ridx, cidx] = 1
return new_board
if __name__ == '__main__':
args = argparse.ArgumentParser(description = "simple conway's game of life setup")
args.add_argument("-s", type = int, default = 32, help = "size of board")
args.add_argument("-n", type = int, default = 20, help = "number of generations")
args.add_argument("-t", type = float, default = 0.5, help = "time to sleep (s)")
args = args.parse_args()
# main
os.system("clear")
board = np.random.choice([1, 0], args.s * args.s, p=[0.3, 0.7]).reshape(args.s, args.s)
board = np.reshape(board, (args.s, args.s))
print(render_board(board))
time.sleep(args.t)
for gen in range(args.n):
os.system("clear")
board = update_board(board)
print(render_board(board))
time.sleep(args.t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment