Pastie now auto-senses if line-wrap is a bad or good idea. Feedback?
## mark a section (Learn more)
## Conway's Game of Life - Teaching 2D Arrays ## # python version # see: http://www.16kb.com/portfolio/display/automata/ import random from processing.core import PApplet # make these self.scale? use global? just leave them out of scope? scale = 10 # factor to magnify grid cols, rows = 100, 100 # number of cols in world world = [] # world = [[0]*cols]*rows DO NOT DO THIS!! for n in range(rows): world.append([0]*cols) # initialize 2D array that will house the game aliveFill = 128 backgroundFill = 0 # draw a cell def drawCell(x, y, alive): if alive == 1: p.fill(aliveFill) else: p.fill(backgroundFill) p.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 class Processor(PApplet): def __init__(self): global p p = self def setup(self): p.size(1000,1000) p.frameRate(60) p.background(0) p.translate(5,5) # shifts everything to the right and down 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(self): # p.background(0) p.translate(5,5) # check each cell 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 import pawt pawt.test(Processor())
This paste will be private.
From the Design Piracy series on my blog: