-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathexample-game-of-life.html
100 lines (90 loc) · 4.2 KB
/
example-game-of-life.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
<html>
<head>
<title>Discrete-Event Simulator: Game of Life</title>
<script src="https://rawgit.com/chen0040/js-simulator/master/src/jssim.js" type="text/javascript"></script>
</head>
<body>
<h2>Discrete-Event Simulator: Conway's Game of Life <input type="text" id="simTime" value="" /></h2>
<p>Game of life will restart randomly every 40 seconds :)</p>
<canvas id="myCanvas" width="640" height="640" style="border:1px solid #000000;">
</canvas>
<script>
(function(){
var CellularAgent = function(world) {
jssim.SimEvent.call(this);
this.world = world;
};
CellularAgent.prototype = Object.create(jssim.SimEvent.prototype);
CellularAgent.prototype.update = function (deltaTime) {
var width = this.world.width;
var height = this.world.height;
var past_grid = this.world.makeCopy();
for(var i=0; i < width; ++i) {
for(var j = 0; j < height; ++j) {
var count = 0;
for(var dx = -1; dx < 2; ++dx) {
var x = i + dx;
if (x >= width) {
x = 0;
}
if (x < 0) {
x = width - 1;
}
for(var dy = -1; dy < 2; ++dy) {
var y = j + dy;
if(y >= height) {
y = 0;
}
if(y < 0) {
y = height - 1;
}
count += past_grid.getCell(x, y);
}
}
if (count <= 2 || count >= 5) {
this.world.setCell(i, j, 0); // dead
}
if (count == 3) {
this.world.setCell(i, j, 1); // live
}
}
}
};
var scheduler = new jssim.Scheduler();
var grid = new jssim.Grid(128, 128);
function init() {
scheduler.reset();
grid.reset();
grid.cellWidth = 5;
grid.cellHeight = 5;
grid.showTrails = true;
grid.trailColor = '#55ff55';
for(var i = 0; i < 32; ++i){
for(var j=0; j < 32; ++j) {
var x = Math.floor(Math.random() * 32 + 64);
var y = Math.floor(Math.random() * 32 + 64);
grid.setCell(x, y, 1);
}
}
grid.setCell(1, 0, 1);
grid.setCell(2, 0, 1);
grid.setCell(0, 1, 1);
grid.setCell(1, 1, 1);
grid.setCell(1, 2, 1);
grid.setCell(2, 2, 1);
grid.setCell(2, 3, 1);
scheduler.scheduleRepeatingIn(new CellularAgent(grid), 1);
}
init();
var canvas = document.getElementById("myCanvas");
setInterval(function(){
scheduler.update();
grid.render(canvas);
console.log('current simulation time: ' + scheduler.current_time);
document.getElementById("simTime").value = "Generation: " + scheduler.current_time;
}, 50);
setInterval(init, 40000);
})();
</script>
</body>
</html>