-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
67 lines (62 loc) · 1.59 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
let world;
let rows;
let cols;
let res = 4
function createWorld(cols, rows) {
let world = Array(cols)
for(let i = 0; i < cols; i++) {
world[i] = new Array(rows)
}
return world;
}
function setup() {
createCanvas(windowWidth, windowHeight);
cols = Math.round(width / res);
rows = Math.round(height / res);
world = createWorld(cols, rows)
for(let i = 0; i < cols; i++) {
for(let j = 0; j < rows; j++) {
world[i][j] = floor(random(2))
}
}
}
function draw() {
background(0);
for(let i = 0; i < cols; i++) {
for(let j = 0; j < rows; j++) {
let x = i * res;
let y = j * res;
if(world[i][j] == 1) {
fill(255);
rect(x, y, res - 1, res - 1);
}
}
}
let nextWorld = createWorld(cols, rows)
for(let i = 0; i < cols; i++) {
for(let j = 0; j < rows; j++) {
let state = world[i][j]
let sum = neighborCount(world, i, j)
if(state == 0 && sum == 3) {
nextWorld[i][j] = 1
} else if(state == 1 && (sum < 2 || sum > 3)) {
nextWorld[i][j] = 0
} else {
nextWorld[i][j] = state
}
}
}
world = nextWorld;
}
function neighborCount(world, x, y) {
let sum = 0;
for(let i = -1; i < 2; i++) {
for(let j = -1; j < 2; j++) {
let col = (x + i + cols) % cols
let row = (y + j + rows) % rows
sum += world[col][row]
}
}
sum -= world[x][y]
return sum
}