automaton.js


SUBMITTED BY: Guest

DATE: March 3, 2024, 12:47 p.m.

FORMAT: Text only

SIZE: 2.3 kB

HITS: 318

  1. // Get the canvas element.
  2. const canvas = document.getElementById('canvas');
  3. const ctx = canvas.getContext('2d');
  4. // Set the width and height of the canvas.
  5. canvas.width = 600;
  6. canvas.height = 600;
  7. function Cell(x, y, size, state) {
  8. this.x = x;
  9. this.y = y;
  10. this.size = size;
  11. this.state = state;
  12. }
  13. Cell.prototype.setState = function(state) {
  14. this.state = state;
  15. }
  16. Cell.prototype.draw = function() {
  17. ctx.beginPath();
  18. ctx.rect(this.x, this.y, this.size, this.size);
  19. ctx.fillStyle = this.state === 1 ? 'red' : 'white';
  20. ctx.fill();
  21. ctx.stroke();
  22. }
  23. function Grid(rows, cols, size) {
  24. this.rows = rows;
  25. this.cols = cols;
  26. this.size = size;
  27. this.cells = this.createCells();
  28. }
  29. Grid.prototype.createCells = function() {
  30. const cells = [];
  31. for (let i = 0; i < this.rows; i++) {
  32. cells[i] = [];
  33. for (let j = 0; j < this.cols; j++) {
  34. cells[i][j] = new Cell(j * this.size, i * this.size, this.size, Math.round(Math.random()));
  35. }
  36. }
  37. return cells;
  38. }
  39. Grid.prototype.draw = function() {
  40. this.cells.forEach(row => row.forEach(cell => cell.draw()));
  41. }
  42. Grid.prototype.update = function() {
  43. const next = this.createCells();
  44. for (let i = 0; i < this.rows; i++) {
  45. for (let j = 0; j < this.cols; j++) {
  46. const cell = this.cells[i][j];
  47. const neighbours = this.countNeighbours(i, j);
  48. if (cell.state === 1 && (neighbours < 2 || neighbours > 3)) {
  49. next[i][j].state = 0;
  50. } else if (cell.state === 0 && neighbours === 3) {
  51. next[i][j].state = 1;
  52. } else {
  53. next[i][j].state = cell.state;
  54. }
  55. }
  56. }
  57. this.cells = next;
  58. }
  59. Grid.prototype.countNeighbours = function(x, y) {
  60. let sum = 0;
  61. for (let i = -1; i < 2; i++) {
  62. for (let j = -1; j < 2; j++) {
  63. const row = (x + i + this.rows) % this.rows;
  64. const col = (y + j + this.cols) % this.cols;
  65. sum += this.cells[row][col].state;
  66. }
  67. }
  68. sum -= this.cells[x][y].state;
  69. return sum;
  70. }
  71. const grid = new Grid(50, 50, 10);
  72. grid.draw();
  73. setInterval(() => {
  74. grid.update();
  75. grid.draw();
  76. }, 1000);

comments powered by Disqus