-
Notifications
You must be signed in to change notification settings - Fork 0
/
Generations.js
54 lines (43 loc) · 1.4 KB
/
Generations.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Generations.js
import { Grid } from './Grid.js';
import { GridDrawer } from './GridDrawer.js';
import { Rules } from './Rules.js';
export class Generations {
constructor(rows, columns, cellSize, numGenerations) {
this.rows = rows;
this.columns = columns;
this.cellSize = cellSize;
this.numGenerations = numGenerations;
this.gridGenerator = new Grid(rows, columns);
this.currentGrid = this.gridGenerator.grid;
this.gridDrawer = new GridDrawer(rows, columns, cellSize, document.getElementById('myCanvas'));
}
async runGenerations() {
while (true) {
let generation = 0;
while (generation < this.numGenerations) {
this.gridDrawer.drawGrid(this.currentGrid);
this.currentGrid = Rules.applyRules(this.currentGrid);
await this.sleep(100);
if (this.isGridEmpty(this.currentGrid)) {
console.log('All cells are dead. Stopping simulation.');
return;
}
generation++;
}
if (this.isEveryoneAlive(this.currentGrid)) {
console.log(`Valid generation found: ${this.numGenerations}`);
this.numGenerations++;
}
}
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
isGridEmpty(grid) {
return grid.every(row => row.every(cell => cell === 0));
}
isEveryoneAlive(grid) {
return grid.every(row => row.every(cell => cell === 1));
}
}