-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautomata.js
More file actions
69 lines (62 loc) · 1.88 KB
/
Copy pathautomata.js
File metadata and controls
69 lines (62 loc) · 1.88 KB
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
const canvas = document.getElementById('automataCanvas');
const ctx = canvas.getContext('2d');
const ancho = 150;
const alto = 150;
canvas.width = ancho;
canvas.height = alto;
let celdas = [];
function inicializarCeldas() {
for (let y = 0; y < alto; y++) {
celdas[y] = [];
for (let x = 0; x < ancho; x++) {
celdas[y][x] = Math.round(Math.random());
}
}
}
function obtenerEstado(x, y) {
if (x < 0 || x >= ancho || y < 0 || y >= alto) {
return 0;
}
return celdas[y][x];
}
function aplicarReglas(vecindad) {
const sumaVecinos = vecindad.flat().reduce((a, b) => a + b, 0);
if (vecindad[1][1]) {
return (sumaVecinos === 3 || sumaVecinos === 4) ? 1 : 0;
} else {
return (sumaVecinos === 3) ? 1 : 0;
}
}
function generarSiguienteGeneracion() {
const nuevaGeneracion = [];
for (let y = 0; y < alto; y++) {
nuevaGeneracion[y] = [];
for (let x = 0; x < ancho; x++) {
const vecindad = [
[obtenerEstado(x - 1, y - 1), obtenerEstado(x, y - 1), obtenerEstado(x + 1, y - 1)],
[obtenerEstado(x - 1, y), obtenerEstado(x, y), obtenerEstado(x + 1, y)],
[obtenerEstado(x - 1, y + 1), obtenerEstado(x, y + 1), obtenerEstado(x + 1, y + 1)]
];
nuevaGeneracion[y][x] = aplicarReglas(vecindad);
}
}
celdas = nuevaGeneracion;
}
function dibujarCeldas() {
ctx.clearRect(0, 0, ancho, alto);
for (let y = 0; y < alto; y++) {
for (let x = 0; x < ancho; x++) {
if (celdas[y][x]) {
ctx.fillStyle = 'black';
ctx.fillRect(x, y, 1, 1);
}
}
}
}
function animar() {
generarSiguienteGeneracion();
dibujarCeldas();
requestAnimationFrame(animar);
}
inicializarCeldas();
animar();