つよくなりたいなあ

地に足をつけず世界を生きぬくブログです

セル・オートマトン

f:id:heyassy:20180127221642j:plain

ここはこうなって、こう書くとこうなるんだなあという感じで少しずつコードがどう動いてるのかわかりつつある。

/*
 * 2018/01/27
 * cell automaton
 */

Cell[][] _cellArray;
int _cellSize  = 10;
int _numX, _numY;

void setup() {
  size(500, 500);
  _numX = floor(width/_cellSize);
  _numY = floor(height/_cellSize);
  restart();
}

void restart() {
  _cellArray = new Cell[_numX][_numY];
  for (int x = 0; x < _numX; x++) {
    for (int y = 0; y < _numY; y++) {
      Cell newCell = new Cell(x, y);
      _cellArray[x][y] = newCell;
    }
  }
  for (int x = 0; x < _numX; x++) {
    for (int y = 0; y < _numY; y++) {
      int above = y-1;
      int below = y+1;
      int left = x-1;
      int right = x+1;

      if (above < 0) {
        above = _numY - 1;
      }
      if (below == _numY) {
        below = 0;
      }
      if (left < 0) {
        left = _numY - 1;
      }
      if (right == _numX) {
        right = 0;
      }
      _cellArray[x][y].addNeighbour(_cellArray[left][above]);
      _cellArray[x][y].addNeighbour(_cellArray[left][y]);
      _cellArray[x][y].addNeighbour(_cellArray[left][below]);
      _cellArray[x][y].addNeighbour(_cellArray[x][below]);
      _cellArray[x][y].addNeighbour(_cellArray[right][below]);
      _cellArray[x][y].addNeighbour(_cellArray[right][y]);
      _cellArray[x][y].addNeighbour(_cellArray[right][above]);
      _cellArray[x][y].addNeighbour(_cellArray[x][above]);
    }
  }
}

void draw() {
  background(255);

  for (int x = 0; x < _numX; x++) {
    for (int y = 0; y < _numY; y++) {
      _cellArray[x][y].calcNextState();
    }
  }

  translate(_cellSize/2, _cellSize/2);

  for (int x = 0; x < _numX; x++) {
    for (int y = 0; y < _numY; y++) {
      _cellArray[x][y].drawMe();
    }
  }
}

void mousePressed() {
  restart();
  saveFrame("CA-####.jpg");
}

//==================== object
class Cell {
  float x, y;
  boolean state;
  boolean nextState;
  Cell[] neighbours;

  Cell(float ex, float why) {
    x = ex * _cellSize;
    y = why * _cellSize;
    if (random(2)>1) {
      nextState = true;
    } else {
      nextState = false;
    }
    state = nextState;
    neighbours = new Cell[0];
  }

  void addNeighbour(Cell cell) {
    neighbours = (Cell[])append(neighbours, cell);
  }

  void calcNextState() {
    int liveCount = 0;
    for (int i = 0; i < neighbours.length; i++) {
      if (neighbours[i].state == true) {
        liveCount++;
      }
    }

    if (state == true) {
      if ((liveCount == 2)||(liveCount == 3)) {
        nextState = true;
      } else {
        nextState = false;
      }
    } else {
      if (liveCount == 3) {
        nextState = true;
      } else {
        nextState = false;
      }
    }
  }

  void drawMe() {
    state = nextState;
    noStroke();

    if (state == true) {
      fill(10);
    } else {
      fill(250);
    }
    ellipse(x,y,_cellSize,_cellSize);
  }
}