9460aa71d5bb3c8df99fdc4478d3e65f1cc161b9
1 $(document
).ready(function(){
3 var canvas
= document
.getElementById('2d-automaton')
4 var c
= canvas
.getContext('2d');
9 var cellWidth
= canvas
.width
/ rows
;
10 var cellHeight
= canvas
.height
/ columns
;
12 function cell(x
, y
, h
, l
) {
18 this.kill = function() {
19 c
.fillStyle
= "rgb(255,255,255)";
20 c
.fillRect(this.x
, this.y
, this.h
, this.l
);
23 this.revive = function() {
24 c
.fillStyle
= "rgb(0,0,0)";
25 c
.fillRect(this.x
, this.y
, this.h
, this.l
);
34 for (var i
= 0; i
< rows
; i
++) {
37 var y
= i
* cellHeight
;
38 for (var ii
= 0; ii
< columns
; ii
++) {
39 world
.push(new cell(x
, y
, cellWidth
, cellHeight
));
41 Math
.random() > .5 ? world
[ii
].revive() : world
[ii
].kill();
43 this.population
.push(world
);
46 this.highlight = function() {
47 for (var i
= 0; i
< rows
; i
++) {
48 for (var ii
= 0; ii
< columns
; ii
++) {
49 if (this.population
[i
][ii
].state
== 1) {
50 this.population
[i
][ii
].highlight();
56 this.redraw = function() {
57 for (var i
= 0; i
< rows
; i
++) {
58 for (var ii
= 0; ii
< columns
; ii
++) {
59 if (this.population
[i
][ii
].state
== 1) {
60 this.population
[i
][ii
].redraw();
67 function tick(automaton
) {
68 automaton
.generation
+= 1;
69 var universe
= automaton
.population
;
71 for (var i
= 0; i
< universe
.length
; i
++) {
73 for (var ii
= 0; ii
< universe
[i
].length
; ii
++) {
74 var neighbors
= (universe
[i
][ii
+1] ? universe
[i
][ii
+1].state
: 0) +
75 (universe
[i
][ii
-1] ? universe
[i
][ii
-1].state
: 0) +
77 (universe
[i
+1][ii
] ? universe
[i
+1][ii
].state
: 0) +
78 (universe
[i
+1][ii
+1] ? universe
[i
+1][ii
+1].state
: 0) +
79 (universe
[i
+1][ii
-1] ? universe
[i
+1][ii
-1].state
: 0)
82 (universe
[i
-1][ii
] ? universe
[i
-1][ii
].state
: 0) +
83 (universe
[i
-1][ii
-1] ? universe
[i
-1][ii
-1].state
: 0) +
84 (universe
[i
-1][ii
+1] ? universe
[i
-1][ii
+1].state
: 0)
86 universe
[i
][ii
].neighbors
= neighbors
;
87 if (universe
[i
][ii
].state
== 1) {
88 if (neighbors
< 2 || neighbors
> 3) {
89 newUniverse
[i
][ii
] = 0;
91 newUniverse
[i
][ii
] = 1;
94 newUniverse
[i
][ii
] = (neighbors
== 3 ? 1 : 0);
98 for (var i
in newUniverse
) {
99 for (var ii
in newUniverse
[i
]) {
100 newUniverse
[i
][ii
] ? universe
[i
][ii
].revive() : universe
[i
][ii
].kill();
103 $('#generation')[0].innerHTML
= automaton
.generation
;
106 var automaton
= new universe
;
109 $('#controls #start-automaton').click(function(e
){
110 tickID
= setInterval(function(){tick(automaton
)}, 100);
111 $('#controls #start-automaton').hide();
112 $('#controls #stop-automaton').show();
115 $('#controls #stop-automaton').click(function(e
){
116 clearInterval(tickID
);
117 $('#controls #stop-automaton').hide();
118 $('#controls #start-automaton').show();