Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

セルオートマトンによるチューリングパターン

/**
* turing pattern by CA
*
* @author aa_debdeb
* @date 2016/07/10
*/

int cellNum = 250;
float cellSize = 2;
int[][] cells;

int innerNeighbor = 2;
int outerNeighbor = 4;
float w;
color bg, fc;

void setup(){
  size(500, 500);
  frameRate(10);
  noStroke();
  initialize();
}

void initialize(){
  w = random(0.25, 0.7);
  cells = new int[cellNum][cellNum];
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      if(random(1) < 0.1){
        cells[x][y] = 1;
      } else {
        cells[x][y] = 0;      
      }
    }
  }
//  cells[int(cellNum / 2)][int(cellNum / 2)] = 1;
  bg = color(random(255), random(255), random(255));
  fc = color(random(255), random(255), random(255));
}

void mousePressed(){
  initialize();
}

void draw(){
  background(bg);
  fill(fc);
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      if(cells[x][y] == 1){
        rect(x * cellSize, y * cellSize, cellSize, cellSize);
      }
    }
  }
  fill(255);
  text("w = " + float(int(w * 1000)) / 1000, 15, 15);
  
  int[][] nextCells = new int[cellNum][cellNum];
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      int innerSum = 0;
      int outerSum = 0;
      for(int dx = - outerNeighbor; dx <= outerNeighbor; dx++){
        for(int dy = - outerNeighbor; dy <= outerNeighbor; dy++){
          int distance = abs(dx) + abs(dy);
          if(distance > outerNeighbor || distance == 0){
            continue;
          }
          int nx = x + dx;
          int ny = y + dy;
          if(nx < 0 || cellNum <= nx || ny < 0 || cellNum <= ny){
            continue;
          }
          if(distance <= innerNeighbor){
            innerSum += cells[nx][ny];
          }
          if(distance <= outerNeighbor){
            outerSum += cells[nx][ny];
          }
        }        
      }
      if(innerSum > w * outerSum){
        nextCells[x][y] = 1;
      } else if(innerSum < w * outerSum){
        nextCells[x][y] = 0;      
      } else {
        nextCells[x][y] = cells[x][y];      
      }
    }
  }
  cells = nextCells;
}