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

Daily Creative Coding

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

拡大するキューブ群

3D
/**
* enlarging crowd of cubes
*
* @author aa_debdeb
* @date 2016/09/13
*/

int BOX_NUM = 50;
float BOX_SIZE = 10;
int[][][] states;
int[][][] neighbors;
int[][] moves = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {-1, 0, 0}, {0, -1, 0}, {0, 0, -1}};
ArrayList<Block> blocks;
ArrayList<Block> pBlocks;

void setup(){
  size(500, 500, P3D);
  stroke(255, 38, 0);
  strokeWeight(2);
  fill(255, 147, 128);
  neighbors = new int[BOX_NUM][BOX_NUM][BOX_NUM];
  states = new int[BOX_NUM][BOX_NUM][BOX_NUM];
  blocks = new ArrayList<Block>();
  pBlocks = new ArrayList<Block>();
  addBlock(int(BOX_NUM / 2), int(BOX_NUM / 2), 0);
}

void addBlock(int x, int y, int z){
  Block block = new Block(x, y, z);
  blocks.add(block);
  states[x][y][z] = 1;
  for(int[] move: moves){
    int nx = x + move[0];
    int ny = y + move[1];
    int nz = z + move[2];
    if(0 <= nx && nx < BOX_NUM && 0 <= ny && ny < BOX_NUM && 0 <= nz && nz < BOX_NUM){
      neighbors[nx][ny][nz]++;
      if(neighbors[nx][ny][nz] == 6){
        states[nx][ny][nz] = 2;
      }
      if(states[nx][ny][nz] == 0){
        states[nx][ny][nz] = 1;
        pBlocks.add(new Block(nx, ny, nz));
      }
    }
  }
}

void draw(){
  background(200);
  translate(width / 2, height * 3.0 / 5);
  rotateX(PI / 3);
  rotateZ(PI / 4);
  rotateZ(map(mouseX, 0, width, -PI / 2, PI / 2));
  translate(-width / 2, -height / 2);
  for(Block block: blocks){
    block.display();
  }
  
  Block pBlock = pBlocks.remove(int(random(pBlocks.size())));
  addBlock(pBlock.x, pBlock.y, pBlock.z);
}

class Block{

  int x, y, z;
  
  Block(int _x, int _y, int _z){
    x = _x;
    y = _y;
    z = _z;
  }
  
  void display(){
    if(states[x][y][z] != 2){
      pushMatrix();
      translate(x * BOX_SIZE + BOX_SIZE / 2, y * BOX_SIZE + BOX_SIZE / 2, z * BOX_SIZE + BOX_SIZE / 2);
      box(BOX_SIZE);
      popMatrix();
    }
  }
  
}
f:id:aa_debdeb:20160910124010j:plain