topical media & game development

talk show tell print

graphic-processing-algorithm-Ch07-p169-p169.pde / pde



  PImage MyImage; //define an image
  int [][] memory; //use it as a copy of the image’s data
  void setup(){
  size(400,400);
  MyImage = createImage(width, height, RGB);
  for(int x=0; x<width; x++)
  for(int y=0; y<height; y++){
  if(random(1)>0.5) //create a random bitmap
  set(x,y,color(0,0,0));
  else
  set(x,y,color(255,255,255));
  }
  memory = new int[width][height];
  }
  void draw(){
  image(MyImage,0,0); //just draw the image in its new state
  }
  int gen = 0; //marks the number of generations
  void keyPressed(){
  for(int x=5; x<width-5; x++) //go through all pixels
  for(int y=5; y<height-5; y++){
  int k=0;
  for(int i=-1; i<=1; i++) //go through all 8-neighbors
  for(int j=-1; j<=1; j++){
  if(i==0 && j==0)continue; //skip if the same one
  color c = get(x+i,y+j); //if the neighbor is black
  if(red(c)==0.)k++; //add it to the counter
  }
  if(k==3) //if all black neighbors are exactly 3
  memory[x][y]=0; //become black
  else if(k>=5) //if all black neighbors are greater or equal to
  memory[x][y]=255; //become white
  }
  for(int x=0; x<width; x++)
  for(int y=0; y<height; y++)
  set(x,y,color(memory[x][y])); //copy memory[] to image
  println(gen++);
  }
  


(C) Æliens 04/09/2009

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.