Daily Creative Coding

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

シェルピンスキーのカーペット

/**
* Sierpinski Carpet
*
* @author aa_debdeb
* @date 2015/10/05
*/


int MAX_DEPTH = 5;
int MAX_SIZE = 500;

void setup(){
  size(500, 500);
  smooth();
  noStroke();
  
  Square root = new Square();
  root.draw();
}

class Square{
  PVector topLeft;
  float size;
  int depth;
  ArrayList<Square> children;
  
  Square(){
    this.topLeft = new PVector(0, 0);
    this.size = MAX_SIZE;
    this.depth = 0;
    this.children = new ArrayList<Square>();
    if(this.depth != MAX_DEPTH){
      makeChildren();
    }
  }
  
  Square(float x, float y, float size, int depth){
    this.topLeft = new PVector(x, y);
    this.size = size;
    this.depth = depth;
    this.children = new ArrayList<Square>();
    if(this.depth != MAX_DEPTH){
      makeChildren();
    }
  }
  
  void makeChildren(){
    float childSize = this.size / 3.0;
    for(int x = 0; x < 3; x++){
      for(int y = 0; y < 3; y++){
        if(!(x == 1 && y == 1)){
          children.add(new Square(this.topLeft.x + childSize * x, this.topLeft.y + childSize * y, childSize, this.depth + 1));
        }
      }
    }
  }
  
  void draw(){
    fill(0);
    rect(topLeft.x, topLeft.y, size, size);
    fill(255);
    float childSize = size / 3.0;
    rect(topLeft.x + childSize, topLeft.y + childSize, childSize, childSize);
    if(children.size() != 0){
      for(Square child: children){
        child.draw();
      }
    }
  }
  
}