-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.js
141 lines (110 loc) · 2.42 KB
/
code.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
let n = 40; //number of columns
let m = 40; //number of rows
let tbody;
let board = [];
let data = [];
let running;
let generations;
let toroidalWorld;
// color cells
function setBoard(force) {
let i;
let j;
if (running || force) {
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
board[i][j].style.background = (data[i][j] ? "black" : "white");
}
}
}
}
// delete cells
function clearBoard() {
let i;
let j;
if (!running) {
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
data[i][j] = false;
}
}
setBoard(true);
generations.value = 0;
}
}
function init() {
let i;
let j;
let row;
let xcenter = Math.floor(n/2);
let ycenter = Math.floor(m/2);
generations = document.getElementById("generations");
tbody = document.getElementById("board");
for (i = 0; i < m; i++) {
row = tbody.appendChild(document.createElement("tr"));
board[i] = [];
data[i] = [];
for (j = 0; j < n; j++) {
board[i][j] = row.appendChild(document.createElement("td"))
board[i][j].addEventListener('click', callbackGenerator(i,j));
}
}
data[ycenter-1][xcenter] = true;
data[ycenter][xcenter+1] = true;
data[ycenter+1][xcenter-1] = true;
data[ycenter+1][xcenter] = true;
data[ycenter+1][xcenter+1] = true;
setBoard(true);
setInterval( function () {
update();
setBoard();
}, 300)
}
function check() {
running = document.getElementById("running").checked;
generations.value = 0;
}
function toggle() {
toroidalWorld = document.getElementById("toroidalWorld").checked;
}
function update() {
let i;
let j;
let k;
let l;
let neighbors;
if (running) {
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
neighbors = 0;
for (k = i-1; k <= i+1; k++) {
for (l = j-1; l <= j+1; l++) {
if (k != i || l != j) {
if (!toroidalWorld && board[k] && board[k][l] &&
board[k][l].style.background.indexOf("black") != -1) {
neighbors++;
}
else if (toroidalWorld && board[(m+k)%m][(n+l)%n].style.background.indexOf("black") != -1) {
neighbors++;
}
}
}
}
if (neighbors == 3) {
data[i][j] = true;
} else if (neighbors != 2) {
data[i][j] = false;
}
}
}
generations.value++;
}
}
function callbackGenerator(i,j) {
return function () {
if (!running) {
data[i][j] = (board[i][j].style.background.indexOf("black") == -1 );
setBoard(true);
}
}
}