-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
82 lines (63 loc) · 1.89 KB
/
app.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
function nextGeneration(rule) {
function getNext(generation) {
let next = [];
let ruleArr = rule.split("").map((c) => parseInt(c));
for (let i = 0; i < generation.length; i++) {
const curr = generation[i];
const left = generation[i - 1];
const right = generation[i + 1];
if (left !== undefined && right !== undefined) {
let rulePos = parseInt(`${left}${curr}${right}`, 2);
next.push(ruleArr[rulePos]);
} else {
next.push(0);
}
}
return next;
}
return getNext;
}
function randomByte() {
const { floor, random } = Math;
return Array.from({ length: 8 }, () => floor(random() * 2)).join("");
}
function createCanvas(width, height) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
return canvas;
}
function displayInfo(firstGeneration, rule) {
const genStr = `${firstGeneration.join("")}`;
const ruleStr = `Rule ${parseInt(rule, 2)} (${rule})`;
document.getElementById("first-gen").setAttribute("title", genStr);
document.getElementById("rule").textContent = ruleStr;
}
function init(width, height) {
const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");
function show(generation, count) {
for (let pos in generation) {
ctx.fillStyle = generation[pos] === 1 ? "#000" : "#fff";
ctx.fillRect(pos, count, 1, 1);
}
}
let rule = randomByte();
let generation = Array.from({ length: width }, () =>
Math.floor(Math.random() * 2)
);
displayInfo(generation, rule);
let genCount = 0;
const next = nextGeneration(rule);
show(generation, genCount);
let animation = setInterval(() => {
genCount++;
generation = next(generation);
show(generation, genCount);
}, 1000 / 60);
if (genCount === height) {
clearInterval(animation);
}
}
init(800, 600);