-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
101 lines (77 loc) · 1.93 KB
/
sketch.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
}
let grid;
let COLS = 100;
let ROWS = 100;
function setup() {
grid = make2DArray(COLS, ROWS);
// fill in the grid with random values (1 || 2)
for (let i = 0; i < COLS; i++) {
for (let j = 0; j < ROWS; j++) {
grid[i][j] = floor(random(2));
}
}
console.table(grid);
createCanvas(750, 750);
frameRate(20);
}
function draw() {
background(0);
for (let i = 0; i < COLS; i++) {
for (let j = 0; j < ROWS; j++) {
let cellWidth = width / COLS;
let cellHeight = height / ROWS;
let x = i * cellWidth;
let y = j * cellHeight;
if (grid[i][j] == 1) {
fill(255);
rect(x, y, cellWidth, cellHeight);
}
}
}
// Initialize a new array for the next frame
let nextGen = make2DArray(COLS, ROWS);
// Compute the next grid
for (let i = 0; i < COLS; i++) {
for (let j = 0; j < ROWS; j++) {
// // Edge cases
// if (i == 0 || i == COLS - 1 || j == 0 || j == ROWS - 1) {
// nextGen[i][j] = grid[i][j] // TODO: REMOVE PLACEHOLDER
// }
// else {
// Count the neighbors
let sum = 0;
let neighbors = countNeighbors(grid, i, j);
let curState = grid[i][j];
// Apply the rules
if (curState == 0 && neighbors == 3) {
nextGen[i][j] = 1;
}
else if (curState == 1 && (neighbors < 2 || neighbors > 3)) {
nextGen[i][j] = 0;
}
else {
nextGen[i][j] = grid[i][j];
}
// }
}
}
grid = nextGen;
}
function countNeighbors(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
// Toroidal grid implementation
gridX = (x + i + COLS) % COLS;
gridY = (y + j + ROWS) % ROWS;
sum += grid[gridX][gridY];
}
}
return sum - grid[x][y];
}