読者です 読者をやめる 読者になる 読者になる

Daily Creative Coding

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

単純なセルオートマトンによるBZ反応

/**
* BZ reaction by simple cellular automata
*
* @author aa_debdeb
* @date 2016/07/08
*/

int cellNum = 100;
float cellSize = 5;
int[][] cells;
int[][] dir = {{0, 1, 0, -1},
               {-1, 0, 1, 0}}; // up, right, down, left

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

void mousePressed(){
  initialize();
}

void initialize(){
  cells = new int[cellNum][cellNum];
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      cells[x][y] = 0;
    }
  }
}

void draw(){
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      if(cells[x][y] == 0){
        fill(139, 0, 139);
      } else if(cells[x][y] == 1){
        fill(0, 140, 70);
      } else {
        fill(140, 140, 0);
      }
      rect(x * cellSize, y * cellSize, cellSize, cellSize);
    }
  }
  int[][] nextCells = new int[cellNum][cellNum];
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      if(cells[x][y] == 1){
        nextCells[x][y] = 2;
      } else if(cells[x][y] == 2){
        nextCells[x][y] = 0;
      } else {
        nextCells[x][y] = 0;
        for(int i = 0; i < 4; i++){
          int dx = x + dir[0][i];
          int dy = y + dir[1][i];
          if(0 <= dx && dx < cellNum && 0 <= dy && dy < cellNum &&
             cells[dx][dy] == 1){
            nextCells[x][y] = 1;
          }
        }
      }
    }
  }
  cells = nextCells;
  cells[int(random(cellNum))][int(random(cellNum))] = 1;
}