created populate function to seed from serialize
[cellular-automaton.git] / 1d.js
1 $(document).ready(function(){
2
3 var cells = 100;
4 var generations = 100;
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 = $('#1d-automaton')[0];
18 var c = canvas.getContext('2d');
19
20 var cellWidth = canvas.width / cells;
21 var cellHeight = 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 generation = 0;
47 generations = 100;
48 for (var i = 0; i < cells; i++) {
49 world.push(new cell(x, y, cellWidth, cellHeight));
50 x += cellWidth;
51 Math.random() > .5 ? world[i].revive() : world[i].kill();
52 }
53 return world;
54 }
55
56 function generate() {
57 generation += 1;
58 var x = 0;
59 var y = generation * cellHeight;
60 var s = '0' + world.map(function(c) { return c.state }).join('') + '0';
61 world = [];
62 for (var i = 0; i < cells; i++) {
63 world.push(new cell(x, y, cellWidth, cellHeight));
64 x += cellWidth;
65 state[s.substr(i, 3)] == 1 ? world[i].revive() : world[i].kill();
66 }
67 //if (generation == generations) { clearInterval(tick_id) }
68 }
69
70 var world = populate_world();
71 while (generations - generation) { generate();}
72 //var tick_id = setInterval(generate, 100);
73
74 $('#controls #regenerate-automaton').click(function(e){
75 c.clearRect(0,0,canvas.width,canvas.height);
76 world = populate_world();
77 while (generations - generation) { generate(); }
78 });
79
80 });