Automat_ES6

Automat_ES6

by mishau

HTML

<body>
  <h1>
    Клеточный автомат
  </h1>
  <canvas height='480' width='640' id='canvas'>Клеточный автомат</canvas>
</body>

JavaScript

function colorToRGBA(color) {
  var cvs, ctx;
  cvs = document.createElement("canvas");
  cvs.height = 1;
  cvs.width = 1;
  ctx = cvs.getContext('2d');
  ctx.fillStyle = color;
  ctx.fillRect(0, 0, 1, 1);
  var data = ctx.getImageData(0, 0, 1, 1).data;
  return data;
}


class Automat {
  constructor(code, generator) {
    this.code = code;
  }

  transmit(index) {
    if (index >= 0 && index < this.code.length)
      return this.code[index];
    else
      return 0;
  }

}



class Matrix {
  constructor(m, n, automat) {
    this.m = m;
    this.n = n;
    this.a = Array(m);
    this.automat = new Automat();
    //this.a.fill(new Array(n));

    for (var i = 0; i < this.m; i++) {
      this.a[i] = Array(n);
    }
  }

  clear() {
    for (var i = 0; i < this.m; i++)
      for (var j = 0; j < this.n; j++) {
        this.a[i][j] = 0;
      }
  }

  run() {
    this.clear();
    this.a[0][this.n / 2 - 1] = 1;

    for (var i = 1; i < this.m; i++) {
      for (var j = 1; j < this.n - 1; j++) {
        this.a[i][j] = this.automat.transmit(this.a[i - 1][j - 1] + this.a[i - 1][j] + this.a[i - 1][j + 1]);
      }
    }
  }

}

class CellularAutomaton {
  constructor(canvas, colors, matrix) {

    this.canvas = canvas;
    this.context = canvas.getContext("2d");
    this.imgData = this.context.createImageData(canvas.width, canvas.height);
    this.colorCount = colors.length;
    this.colors = colors;
    this.rgbaColors = colors.map(colorToRGBA);

    this.matrix = matrix;
    this.code = [0, 2, 0, 1, 1, 3, 1, 5, 0, 5, 0, 1, 0];
  }

  generateImageData() {
    let k = 0;
    for (let i = 0; i < this.matrix.m; i++) {
      for (let j = 0; j < this.matrix.n; j++) {
        let colorNum = this.matrix.a[i][j];
        let data = this.rgbaColors[colorNum];
        for (let l = 0; l < 4; l++)
          this.imgData.data[k + l] = data[l];
        k += 4;
      }
    }
  }

  draw() {
    this.generateImageData(this.imgData, this.matrix, this.rgbaColors);
   ...