This repository was archived by the owner on May 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconway.js
More file actions
83 lines (70 loc) · 1.71 KB
/
conway.js
File metadata and controls
83 lines (70 loc) · 1.71 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var Canvas = require('canvas');
var Image = Canvas.Image;
var canvas = new Canvas(128, 16);
var panel = require('./index');
var ctx = canvas.getContext("2d");
var mypanel = new panel.Panel(ctx, 'ledpanel.lan', 1021);
var width = 128;
var height = 16;
var oldMap = new Array(width * height);
var newMap = new Array(width * height);
function init() {
for(var i = 0; i < oldMap.length; i++) {
oldMap[i] = Math.round(Math.random());
}
}
function getAlive(x, y) {
x = (x + width) % width;
y = (y + height) % height;
return oldMap[x + y * width];
}
function updateAlive(x, y) {
var isAlive = getAlive(x, y);
var neighbour = 0;
for(var x_ = x-1; x_ <= x+1; x_++) {
for(var y_ = y-1; y_ <= y+1; y_++) {
if(x_ == x && y_ == y)
continue;
if(getAlive(x_, y_))
neighbour++;
}
}
if(!isAlive) {
newMap[x + y * width] = neighbour == 3;
}
else if(neighbour < 2)
newMap[x + y * width] = false;
else if(neighbour > 3)
newMap[x + y * width] = false;
else
newMap[x + y * width] = true;
return newMap[x + y * width];
}
function swapMap() {
var tmp = newMap;
newMap = oldMap;
oldMap = tmp;
}
function setPixel(imageData, x, y, r, g, b, a) {
index = (x + y * imageData.width) * 4;
imageData.data[index+0] = r;
imageData.data[index+1] = g;
imageData.data[index+2] = b;
imageData.data[index+3] = a;
}
function loop() {
var imageData = ctx.createImageData(width, height);
for(var x = 0; x < width; x++) {
for(var y = 0; y < height; y++) {
var wasAlive = getAlive(x, y);
var alive = updateAlive(x, y);
setPixel(imageData, x, y, wasAlive * 255, alive * 255, 0, 255);
}
}
ctx.putImageData(imageData, 0, 0);
mypanel.draw();
swapMap();
}
setInterval(init, 10000);
init();
setInterval(loop, 100);