## Conway's Game of Life - Teaching 2D Arrays
##
# python version
# see: http://www.16kb.com/portfolio/display/automata/
from pyprocessing import *

import random

# make these self.scale? use global? just leave them out of scope?
scale = 10 # factor to magnify grid
cols, rows = 50, 40 # number of cols in world
world = []
# world = [[0]*cols]*rows DO NOT DO THIS!!
for n in range(cols):
world.append([0]*rows) # initialize 2D array that will house the game

aliveFill = 128
backgroundFill = 0

# draw a cell
def drawCell(x, y, alive):
if alive == 1:
fill(aliveFill)
else:
fill(backgroundFill)
ellipse(x*scale, y*scale, 8, 8)


def checkNeighbours(x, y):
# check how neighbours a position has
neighbours = 0

for dx in [-1,0,1]:
for dy in [-1,0,1]:
if dy==0 and dx==0: # skip checking ourselves
continue
if (x+dx >= 0 and x+dx < cols) and (y+dy >= 0 and y+dy < rows) and (world[x+dx][y+dy] == 1 or world[x+dx][y+dy] == -1):
neighbours = neighbours + 1
return neighbours



def setup():
size(500,400)
frameRate(5)
background(0)

for x in range(cols): # loop through every column
for y in range(rows): # loop through every row
world[x][y] = random.randint(0,1) # place a 0 or 1 into the world
# note we have y first!
if world[x][y] == 1:
drawCell(x, y, 1) # if world holds a 1 then draw a circle

def draw():
# check each cell
print "test"
for x in range(cols): # loop through every column
for y in range(rows): # loop through every row
num = checkNeighbours(x,y)

if world[x][y] == 0 and num == 3: # bring cell to life
world[x][y] = 8 # 0 = dead, 8 dead, but alive next
drawCell(x, y, 1)


elif world[x][y] == 1 and (num < 2 or num > 3): # kill cell
world[x][y] = -1 # 1 = alive, -1 = alive, but dead next round
drawCell(x, y, 0)

# set all changing state codes (ie. -1 and 8)
for x in range(cols): # loop through every column
for y in range(rows): # loop through every row

if world[x][y] == 8:
world[x][y] = 1
elif world[x][y] == -1:
world[x][y] = 0


run()