|
| 1 | +import Cell from './Cell.js'; |
| 2 | + |
| 3 | +export default class Grid { |
| 4 | + rows = []; |
| 5 | + |
| 6 | + constructor(numRows, numColumns, cellSize) { |
| 7 | + this.numRows = numRows; |
| 8 | + this.numColumns = numColumns; |
| 9 | + |
| 10 | + Cell.size = cellSize; |
| 11 | + |
| 12 | + // Create the grid as a two-dimensional array (i.e. an array of arrays) |
| 13 | + for (let y = 0; y < numRows; y++) { |
| 14 | + const row = []; |
| 15 | + for (let x = 0; x < numColumns; x++) { |
| 16 | + const cell = new Cell(x, y); |
| 17 | + row.push(cell); |
| 18 | + } |
| 19 | + this.rows.push(row); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + isAlive(x, y) { |
| 24 | + // Out-of-border cells are presumed dead |
| 25 | + if (x < 0 || x >= this.numColumns || y < 0 || y >= this.numRows) { |
| 26 | + return 0; |
| 27 | + } |
| 28 | + |
| 29 | + const cell = this.rows[y][x]; |
| 30 | + return cell.alive ? 1 : 0; |
| 31 | + } |
| 32 | + |
| 33 | + countLivingNeighbors(cell) { |
| 34 | + const { x, y } = cell; |
| 35 | + return ( |
| 36 | + this.isAlive(x - 1, y - 1) + |
| 37 | + this.isAlive(x, y - 1) + |
| 38 | + this.isAlive(x + 1, y - 1) + |
| 39 | + this.isAlive(x - 1, y) + |
| 40 | + this.isAlive(x + 1, y) + |
| 41 | + this.isAlive(x - 1, y + 1) + |
| 42 | + this.isAlive(x, y + 1) + |
| 43 | + this.isAlive(x + 1, y + 1) |
| 44 | + ); |
| 45 | + } |
| 46 | + |
| 47 | + forEachCell(callback) { |
| 48 | + this.rows.forEach((row) => { |
| 49 | + row.forEach((cell) => callback(cell)); |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + update() { |
| 54 | + this.forEachCell((cell) => { |
| 55 | + const aliveNeighbors = this.countLivingNeighbors(cell); |
| 56 | + cell.liveAndLetDie(aliveNeighbors); |
| 57 | + }); |
| 58 | + |
| 59 | + this.forEachCell((cell) => cell.update()); |
| 60 | + } |
| 61 | + |
| 62 | + render(context) { |
| 63 | + this.forEachCell((cell) => cell.draw(context)); |
| 64 | + } |
| 65 | +} |
0 commit comments