Skip to content

Instantly share code, notes, and snippets.

@st98
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st98/9087945 to your computer and use it in GitHub Desktop.
Save st98/9087945 to your computer and use it in GitHub Desktop.
JavaScriptで書いたライフゲーム。
<!doctype html>
<head>
<meta charset="utf-8">
<title>Conway&apos;s Game of Life</title>
</head>
<body>
<script src="life.js"></script>
</body>
(function () {
var Life = function Life(options) {
if (!(this instanceof Life)) {
return new Life(options);
}
options = options || {};
this.width = options.width || 100;
this.height = options.height || 100;
this.context = options.context;
this.fps = options.fps || 15;
};
Life.prototype.neighbor = function (x, y) {
var cells = this.cells;
var w, i, j;
var lives = 0;
w = this.width;
for (i = -1; i <= 1; i++) {
for (j = -1; j <= 1; j++) {
lives += cells[(x + i) + (y + j) * w];
}
}
lives -= cells[x + y * w];
return lives;
};
Life.prototype.update = function () {
var cells, newCells;
var x, y, w, h;
var lives;
cells = this.cells;
newCells = [];
w = this.width;
h = this.height;
for (x = 0; x < w; x++) {
for (y = 0; y < h; y++) {
lives = this.neighbor(x, y);
if (cells[x + y * w] ? (lives === 2 || lives === 3) : lives === 3) {
newCells[x + y * w] = 1;
} else {
newCells[x + y * w] = 0;
}
}
}
this.cells = newCells;
};
Life.prototype.draw = function () {
var cells, ctx;
var image, imageData;
var x, y, w, h, i;
cells = this.cells;
ctx = this.context;
w = this.width;
h = this.height;
image = ctx.createImageData(w, h);
imageData = image.data;
for (x = 0; x < w; x++) {
for (y = 0; y < h; y++) {
i = (x + y * w) * 4;
imageData[i] = imageData[i + 1] = imageData[i + 2] = cells[x + y * w] ? 0 : 255;
imageData[i + 3] = 255;
}
}
ctx.putImageData(image, 0, 0);
};
Life.prototype.randomize = function () {
var cells;
var x, y, w, h;
cells = this.cells = [];
w = this.width;
h = this.height;
for (x = 0; x < w; x++) {
for (y = 0; y < h; y++) {
cells[x + y * w] = Math.random() * 2 | 0;
}
}
};
Life.prototype.start = function () {
var interval = 1000 / this.fps;
if (this.running) {
this.stop();
}
this.timer = setInterval(function () {
this.update();
this.draw();
}.bind(this), interval);
this.running = true;
};
Life.prototype.stop = function () {
clearInterval(this.timer);
this.running = false;
};
var cv = document.createElement('canvas');
cv.width = cv.height = 100;
cv.style.border = '1px solid #000';
var ctx = cv.getContext('2d');
var game = new Life({
context: ctx
});
game.randomize();
game.start();
cv.addEventListener('click', function () {
game.stop();
game.randomize();
game.start();
});
document.body.appendChild(cv);
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment