[file under: experimental scripts]
http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
Just as an expirement i decided to create Conway's Game of Life in CS2. It is not real practical, and painfully slow, but it works.
To use the script first open a small RGB image (i developed the script with images no larger than 15x15 pixels, the bigger the image the slower the script). Run the script. Go get a snack as it will be a few minutes. When you come back you will have a new document with each layer an iteration of the cellular automaton.
Code: Select allfunction gameOfLife(){
var steps = 1;//number of steps before rendering a layer
var layers = 10;//number of layers to render
function selectBounds(b) {
newDoc.selection.select([[ b[0], b[1] ],
[ b[2], b[1] ],
[ b[2], b[3] ],
[ b[0], b[3] ]]);
}
function getCellVal(x,y){
selectBounds([x, y, x+1, y+1]);
var returnVal = (newDoc.histogram[255]==1)?1:0;
newDoc.selection.deselect();
return returnVal;
}
function renderArray(outArry){
var newLayer = newDoc.artLayers.add();
newDoc.activeLayer = newLayer;
for (x=0;x<outArry.length;x++){
for (y=0;y<outArry[x].length;y++){
selectBounds([x, y, x+1, y+1]);
var fillColor = (outArry[x][y]==1)?app.foregroundColor:app.backgroundColor;
newDoc.selection.fill(fillColor);
newDoc.selection.deselect();
}
}
}
function iterateCA(theArry){
var newArry = new Array(theArry.length);
for (x=0;x<theArry.length;x++){
newArry[x] = new Array(theArry[x].length);
for (y=0;y<theArry[x].length;y++){
var sum8 = (x-1>=0&&y-1>=0)?theArry[x-1][y-1]:0;
sum8 += (x-1>=0)?theArry[x-1][y]:0;
sum8 += (x-1>=0&&y+1<theArry[x].length)?theArry[x-1][y+1]:0;
sum8 += (y-1>=0)?theArry[x][y-1]:0;
sum8 += (y+1<theArry[x].length)?theArry[x][y+1]:0;
sum8 += (x+1<theArry.length&&y-1>=0)?theArry[x+1][y-1]:0;
sum8 += (x+1<theArry.length)?theArry[x+1][y]:0;
sum8 += (x+1<theArry.length&&y+1<theArry[x].length)?theArry[x+1][y+1]:0;
if(theArry[x][y] == 1){
newArry[x][y] = (sum8==2||sum8==3)?1:0;
}else{
newArry[x][y] = (sum8==3)?1:0;
}
}
}
return newArry;
}
var currDoc = app.activeDocument;
var newDoc = currDoc.duplicate();
newDoc.flatten();
newDoc.activeLayer.threshold(128);
var pixelArry = new Array(newDoc.width);
for (x=0;x<newDoc.width;x++){
pixelArry[x] = new Array(newDoc.height);
for (y=0;y<newDoc.height;y++){
pixelArry[x][y] = getCellVal(x,y);
}
}
var calcArry = pixelArry.slice();
for (iL=0;iL<layers;iL++){
for (it=0;it<steps;it++){
calcArry = iterateCA(calcArry);
}
renderArray(iterateCA(calcArry));
}
}
enjoy,
-wade
p.s. thanks to xbytor for some code style tips bb/viewtopic.php?p=1623