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

Daily Creative Coding

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

1次元セルオートマトン

/**
* 1D Cellular Automaton
*
* @author aa_debdeb
* @date 2016/02/13
*/

int RULE_NO = 110;
int[] rule;
int[] states;

void setup(){
  size(500, 500);
  frameRate(45);
  background(255);
  
  rule = new int[8];
  String binaryRule = binary(RULE_NO);
  for(int i = 0; i < 8; i++){
//    rule[i] = Character.getNumericValue(binaryRule.charAt(binaryRule.length() - i - 1)); // java
    rule[i] = binaryRule.charAt(binaryRule.length() - i - 1).toString() == "0" ||
              binaryRule.charAt(binaryRule.length() - i - 1).toString() == "" ? 0: 1; // javascript
  }
  initializeState();
}

void initializeState(){
  states = new int[width];
  for(int w = 0; w < width; w++){
    states[w] = 0;
  }
  states[width - 1] = 1;
}


void draw(){
  loadPixels();
  int h = frameCount % height;
  for(int w = 0; w < width; w++){
    color c = states[w] == 0 ? color(255): color(0);
    pixels[h * width + w] = c;
  }
  updatePixels();
  
  update();
}

void update(){
  int[] nextStates = new int[width];
  for(int w = 0; w < width; w++){
    int pwl = w != 0 ? states[w - 1]: 0;
    int pwc = states[w];
    int pwr = w != width - 1 ? states[w + 1]: 0;
    int stateIdx = pwl * 4 + pwc * 2 + pwr;
    nextStates[w] = rule[stateIdx];
  }
  states = nextStates;
}