This is a python program that I wrote based off of Conway's game of life. The Game of Life is a cellular automaton that consists of a collection of cells which, based on a few mathematical rules, can live, die or multiply. Depending on the initial conditions, the cells form various patterns throughout the course of the game.
Any live cell with fewer than two live neighbors dies, as if by underpopulation.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by overpopulation.
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
These rules, which compare the behavior of the automaton to real life, can be condensed into the following:
Any live cell with two or three live neighbors survives.
Any dead cell with three live neighbors becomes a live cell.
All other live cells die in the next generation. Similarly, all other dead cells stay dead.
# Conway's game of life
import random
import time
import copy
width = 60
height = 20
# list of cells
nextCells = []
for x in range(width):
column = [] # create a new column
for y in range(height):
if random.randint(0, 1) == 0:
column.append('#') # adds a living cell
else:
column.append(' ') # adds a dead cell
nextCells.append(column) # list of column lists
# main loop
while True:
print('\n\n\n\n\n')
currentCells = copy.deepcopy(nextCells)
# print currentcells
for y in range(height):
for x in range(width):
print(currentCells[x][y], end='')
print()
# determine the next step based on current steps
for x in range(width):
for y in range(height):
# get neighbor coordinates
# %width-leftcoor always between 0 & width -1
leftCoord = (x - 1) % width
rightCoord = (x + 1) % width
aboveCoord = (y - 1) % height
belowCoord = (y + 1) % height
# count living neighbors
num = 0
if currentCells[leftCoord][aboveCoord] == '#':
num += 1 # top left is alive
if currentCells[x][aboveCoord] == '#':
num += 1 # top is alive
if currentCells[rightCoord][aboveCoord] == '#':
num += 1 # top right is alive
if currentCells[leftCoord][y] == '#':
num += 1 # left is alive
if currentCells[rightCoord][y] == '#':
num += 1 # right is alive
if currentCells[leftCoord][belowCoord] == '#':
num += 1 # bottom left is alive
if currentCells[rightCoord][belowCoord] == '#':
num += 1 # bottom right is alive
if currentCells[x][belowCoord] == '#':
num += 1 # bottom is alive
# set cell base on game of life rules
if currentCells[x][y] == '#' and (num == 2 or num == 3):
# living cells with 2 or 3 neighbor stay alive
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and num == 3:
# dead cell w/ 3 neighbors become alive
nextCells[x][y] = '#'
else:
# everything dies or stays dead
nextCells[x][y] = ' '
time.sleep(.5) # adds 1 sec pause to stop flickering