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

30 min. Processing

毎日30分、Processingで何かを作る

環状の1次元セルオートマトン

セルオートマトン
/**
* ringed 1d cellular automata
* 
* @author aa_debdeb
* @date 2016/05/03
*/

int ruleNo = 110; // 30, 110, 90...
int[] rule;
ArrayList<ArrayList<Integer>> gens;

int genSize = 100;
int stateSize = 100;

void setup(){
  size(500, 500);
  noStroke();
  
  rule = new int[8];
  String binaryRule = binary(ruleNo);
  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
  }
  gens = new ArrayList<ArrayList<Integer>>();
  for(int i = 0; i < genSize; i++){
    ArrayList states = new ArrayList<Boolean>();
    for(int j = 0; j < stateSize; j++){
      if(i == genSize - 1){
        states.add(random(1) < 0.5 ? 0: 1);
      } else {
        states.add(0);
      }
    }
    gens.add(states);
  }
}

void draw(){
  background(255);
  float rStep = TWO_PI / stateSize;
  for(int i = 0; i < genSize; i++){ 
    ArrayList<Integer> states = gens.get(i);
    for(int j = 0; j < stateSize; j++){
      float d = map(i, 0, genSize, width, 0);
      if(states.get(j) == 0){fill(255);}
      else{fill(0);}
      arc(width / 2, height / 2, d, d, rStep * j, rStep * (j + 1));
    }
  }
  
  ArrayList<Integer> states = gens.get(genSize - 1);
  ArrayList<Integer> nextStates = new ArrayList<Integer>();
  for(int i = 0; i < stateSize; i++){
    int left = i != 0 ? states.get(i  - 1): states.get(stateSize - 1);
    int center = states.get(i);
    int right = i != stateSize - 1 ? states.get(i + 1): states.get(0);
    int s = left * 4 + center * 2 + right;
    nextStates.add(rule[s]);
  }
  gens.remove(0);
  gens.add(nextStates);
 
}