-
Notifications
You must be signed in to change notification settings - Fork 0
/
gameoflife.html
80 lines (73 loc) · 2.67 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
<!DOCTYPE html>
<html>
<head>
<title>Conway's Game of Life</title>
</head>
<body> <div align="center">
<canvas id = "canvas" style = "border:2px solid black"></canvas></div>
<script>
var xCell = 130;
var yCell = 130;
var canvas = document.getElementById("canvas")
canvas.width = xCell*4
canvas.height = yCell*4
var context = canvas.getContext("2d")
var grids = new Array(yCell)
for (var i = 0; i < yCell; i++)
grids[i] = new Array(xCell)
var random = 1200;
var m,n;
for (var j = 0; j < random; j++) {
m = parseInt(Math.random()*yCell);
n = parseInt(Math.random()*xCell);
grids[m][n] = 1;
}
draw();
setInterval("game()", 100);
function game(){
var neighbourCount = 0
for (i = 0; i < yCell; i++){
for(j = 0; j<xCell; j++) {
neighbourCount = count(i,j)
if (neighbourCount < 2) grids[i][j] = 0
if (neighbourCount > 3) grids[i][j] = 0
if (neighbourCount === 3) grids[i][j] = 1
}
} draw();
}
function count(i, j) {
var count = 0;
if (grids[i] != undefined) {
if (grids[i][j-1] == 1) count++;
if (grids[i][j+1] == 1) count++;
}
if (grids[i-1] != undefined) {
if (grids[i-1][j] == 1) count++;
if (grids[i-1][j-1] == 1) count++;
if (grids[i-1][j+1] == 1) count++;
}
if (grids[i+1] != undefined) {
if (grids[i+1][j] == 1) count++;
if (grids[i+1][j-1] == 1) count++;
if (grids[i+1][j+1] == 1) count++;
}
return count;
}
function draw(){
for (i = 0; i < yCell; i++) {
for (j = 0; j < xCell; j++)
{
if (grids[i][j] == 1) {
context.fillStyle = 'red';
}
else {
context.fillStyle = 'grey';
}
context.beginPath();
context.rect(j*4, i*4, 4,4);
context.closePath();
context.fill();
}}}
</script>
</body>
</html>