Skip to content

Instantly share code, notes, and snippets.

@gongzhitaao
Last active August 29, 2015 14:02
Show Gist options
  • Save gongzhitaao/efb7b234c8366ed8857e to your computer and use it in GitHub Desktop.
Save gongzhitaao/efb7b234c8366ed8857e to your computer and use it in GitHub Desktop.
Game of life
<!DOCTYPE html>
<html>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://gongzhitaao.github.io/lifejs/js/life.js"></script>
<body>
<script>
var width = 960;
var height = 500;
var live = "#222";
var dead = "#eee";
var pat = {
data: "bo12bob$bo12bob$obo10bobo$bo12bob$bo12bob$2bo3b4o3bo2b$6b4o6b$2b4o4b4o2b2$4bo6bo4b$5b2o2b2o!"
};
var param = {
width: 32,
height: 16,
startx: 3,
starty: 3
};
var size = 30;
var offx = (width - param.width * size) / 2;
var offy = (height - param.height * size) / 2;
var canvas = d3.select("body")
.insert("canvas", ":first-child")
.attr("width", width)
.attr("height", height);
var ctx = canvas.node().getContext("2d");
var gol = life.wrapped();
var next = gol.reset(pat, param);
(function init() {
var i, j;
ctx.fillStyle = dead;
for (i = 0; i < param.height; ++i) {
for (j = 0; j < param.width; ++j) {
ctx.fillRect(offx + size * j + 2, offy + size * i + 2,
size - 4, size - 4);
}
}
})();
(function tick() {
var i, xy;
ctx.fillStyle = live;
for (i = 0; i < next.born.length; ++i) {
xy = next.born[i];
ctx.fillRect(offx + size * xy[0] + 2, offy + size * xy[1] + 2,
size - 4, size - 4);
}
ctx.fillStyle = dead;
for (i = 0; i < next.dead.length; ++i) {
xy = next.dead[i];
ctx.fillRect(offx + size * xy[0] + 2, offy + size * xy[1] + 2,
size - 4, size - 4);
}
next = gol.next();
if (next.dead.length > 0 || next.born.length > 0)
setTimeout(tick, 500);
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment