-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
99 lines (87 loc) · 2.48 KB
/
app.js
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var ROWS = 40;
var COLS = 60;
$(document).ready(function() {
var life = new Life(ROWS, COLS);
var running = false;
var interval;
start = function() {
running = true;
interval = setInterval(tick, 400);
$("#start").hide();
$("#stop").show();
};
stop = function() {
running = false;
clearInterval(interval);
$("#stop").hide();
$("#start").show();
};
tick = function() {
life.tick();
updateBoard();
};
toggleCell = function(row, col, element) {
if (!running) {
life.board[row][col] = !life.board[row][col];
updateCell(element, life.board[row][col]);
}
};
reset = function(board) {
stop();
if (board) {
life = new Life(ROWS, COLS, eval(board));
}
else {
life = new Life(ROWS, COLS);
}
updateBoard();
};
initBoard = function() {
var board = "<table>";
for (var row = 0; row < life.rows; row++) {
board += "<tr>";
for (var col = 0; col < life.cols; col++) {
board += "<td></td>";
}
board += "</tr>"
}
board += "</table>"
$("#board").html(board);
};
initPatterns = function() {
var options = "<option value=\"\">Empty</option>";
for (group in Life.patternGroups) {
options += "<optgroup label=\"" + group + "\">";
for (pattern in Life.patternGroups[group]) {
options += "<option value=\"" + Life.patternGroups[group][pattern] + "\">" + pattern + "</option>";
}
options += "</optgroup>";
}
$("#pattern").html(options)
};
updateBoard = function() {
$("#board table tr").each(function(row) {
$("td", this).each(function(col) {
updateCell(this, life.board[row][col]);
});
});
};
updateCell = function(cell, alive) {
$(cell).attr("class", alive ? "alive" : "dead")
};
initBoard();
initPatterns();
updateBoard(life);
$("#start").click(start);
$("#stop").click(stop);
$("#reset").click(function() {
reset($("#pattern").val());
});
$("#board table tr").each(function(row) {
$("td", this).each(function(col) {
$(this).click(function() {
toggleCell(row, col, this);
});
});
});
});