-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameoflife.html
120 lines (104 loc) · 3.02 KB
/
gameoflife.html
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
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;"></canvas>
<script>
var gridHeight = 400;
var gridWidth = 400;
var theGrid = createArray(gridWidth);
var mirrorGrid = createArray(gridWidth);
fillRandom();
tick();
function tick() {
drawGrid();
updateGrid();
requestAnimationFrame(tick);
}
function createArray(rows) {
var arr = [];
for (var i = 0; i < rows; i++) {
arr[i] = [];
}
return arr;
}
function fillRandom() {
for (var j = 0; j < gridHeight; j++) {
for (var k = 0; k < gridWidth; k++) {
var rawRandom = Math.random();
var improvedNum = (rawRandom * 2);
var randomBinary = Math.floor(improvedNum);
if (randomBinary === 1) {
theGrid[j][k] = 1;
} else {
theGrid[j][k] = 0;
}
}
}
}
function drawGrid() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 400, 400);
for (var j = 1; j < gridHeight; j++) {
for (var k = 1; k < gridWidth; k++) {
if (theGrid[j][k] === 1) {
ctx.fillStyle = "#000000";
ctx.fillRect(j, k, 1, 1);
}
}
}
}
function updateGrid() {
for (var j = 1; j < gridHeight - 1; j++) {
for (var k = 1; k < gridWidth - 1; k++) {
var totalCells = 0;
totalCells += theGrid[j - 1][k - 1];
totalCells += theGrid[j - 1][k];
totalCells += theGrid[j - 1][k + 1];
totalCells += theGrid[j][k - 1];
totalCells += theGrid[j][k + 1];
totalCells += theGrid[j + 1][k - 1];
totalCells += theGrid[j + 1][k];
totalCells += theGrid[j + 1][k + 1];
if (theGrid[j][k] === 0) {
switch (totalCells) {
case 3:
mirrorGrid[j][k] = 1;
break;
default:
mirrorGrid[j][k] = 0;
}
} else if (theGrid[j][k] === 1) {
switch (totalCells) {
case 0:
case 1:
mirrorGrid[j][k] = 0;
break;
case 2:
case 3:
mirrorGrid[j][k] = 1;
break;
case 4:
case 5:
case 6:
case 7:
case 8:
mirrorGrid[j][k] = 0;
break;
default:
mirrorGrid[j][k] = 0;
}
}
}
}
for (var j = 0; j < gridHeight; j++) {
for (var k = 0; k < gridWidth; k++) {
theGrid[j][k] = mirrorGrid[j][k];
}
}
}
</script>
</body>
</html>