whoops, swap height/width
[cellular-automaton.git] / 2d.js
1 $(document).ready(function(){
2
3 var cells = 20;
4 var generations = 10;
5
6 var state = {
7 '000' : '0',
8 '001' : '0',
9 '010' : '0',
10 '011' : '1',
11 '100' : '0',
12 '101' : '1',
13 '110' : '1',
14 '111' : '0',
15 }
16
17 var canvas = document.getElementById('canvas')
18 var c = canvas.getContext('2d');
19
20 var cellWidth = Math.floor(canvas.width / cells);
21 var cellHeight = Math.floor(canvas.height / generations);
22 var generation = 0;
23
24 function cell(x, y, h, l) {
25 this.x = x;
26 this.y = y;
27 this.h = h;
28 this.l = l;
29 this.state = 0;
30 this.kill = function() {
31 c.fillStyle = "rgb(200,0,0)";
32 c.fillRect(this.x, this.y, this.h, this.l);
33 this.state = 0;
34 }
35 this.revive = function() {
36 c.fillStyle = "rgb(0,0,0)";
37 c.fillRect(this.x, this.y, this.h, this.l);
38 this.state = 1;
39 }
40 }
41
42 function populate_world() {
43 var world = [];
44 var x = 0;
45 var y = 0;
46 for (var i = 0; i < cells; i++) {
47 world.push(new cell(x, y, cellWidth, cellHeight));
48 x += cellWidth;
49 Math.random() > .5 ? world[i].revive() : world[i].kill();
50 }
51 return world;
52 }
53
54 function generate() {
55 generation += 1;
56 var x = 0;
57 var y = generation * cellHeight;
58 var s = '0' + world.map(function(c) { return c.state }).join('') + '0';
59 world = [];
60 for (var i = 0; i < cells; i++) {
61 world.push(new cell(x, y, cellWidth, cellHeight));
62 x += cellWidth;
63 state[s.substr(i, 3)] == 1 ? world[i].revive() : world[i].kill();
64 }
65 //if (generation == generations) { clearInterval(tick_id) }
66 }
67
68 var world = populate_world();
69 while (generations) { generate(); generations-- }
70 //var tick_id = setInterval(generate, 100);
71
72 });