Skip to content

Instantly share code, notes, and snippets.

@webspace-jp
Last active August 29, 2015 14:12
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 webspace-jp/80a5dd10726734bc82cf to your computer and use it in GitHub Desktop.
Save webspace-jp/80a5dd10726734bc82cf to your computer and use it in GitHub Desktop.
jQuery(function($) {
var WIDTH = 80;
var HEIGHT = WIDTH;
var SIZE = 5;
var field;
var canvas;
var Field = function(width, height){
this.width = width;
this.height = height;
this.field;
this.init();
};
Field.prototype = {
init: function(){
this.field = [];
for (var y = 0; y < this.height; y++) {
this.field[y] = [];
for (var x = 0; x < this.width; x++) {
this.set(x, y, null);
}
}
},
randomize: function(){
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
var val = random(1, 10) == 1 ? 1 : 0;
this.set(x, y, val);
}
}
},
next: function(){
this.active = 0;
var tempField = $.extend(true, {}, this.field);
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
var n = this.neighbor(x, y, tempField);
var val = this.fate(tempField[y][x], n);
this.set(x, y, val);
}
}
},
neighbor: function(x, y, field) {
var n = 0;
for (var s = -1; s < 2; s++) {
if (y + s < 0 || y + s > this.height - 1) {
continue;
}
for (var t = -1; t < 2; t++) {
if (s == 0 && t == 0) {
continue;
}
if (x + t < 0 || x + t > this.width - 1) {
continue;
}
if (field[y + s][x + t] == 1) {
n++;
}
}
}
return n;
},
fate: function(mine, neighbor){
// 生存
if (mine == 1 && (neighbor == 2 || neighbor == 3)) {
return 1;
}
// 誕生
if (mine == 0 && neighbor == 3) {
return 1;
}
// 過疎, 過密
return 0;
},
val: function(x, y){
return this.field[y][x];
},
set: function(x, y, v){
this.field[y][x] = v;
}
};
var Canvas = function(ctx, field, size) {
this.ctx = ctx;
this.field = field;
this.size = size;
};
Canvas.prototype = {
clear: function(){
this.ctx.clearRect(0, 0, this.field.width * this.size, this.field.height * this.size);
},
draw: function() {
this.clear();
this.ctx.fillStyle = 'rgb(0, 0, 0)';
for (var y = 0; y < this.field.height; y++) {
for (var x = 0; x < this.field.width; x++) {
if (this.field.val(x, y) == 0) {
continue;
}
this.ctx.fillRect(x * this.size, y * this.size, this.size, this.size);
}
}
}
};
var init = function() {
var $canvas = $("#canvas");
var ctx = $canvas.get(0).getContext('2d');
field = new Field(WIDTH, HEIGHT);
field.randomize();
canvas = new Canvas(ctx, field, SIZE);
};
var draw = function() {
canvas.draw();
};
var lifegame = function() {
field.next();
draw();
}
var random = function(min, max) {
return min + Math.floor(Math.random() * (max + 1));
};
init();
draw();
setInterval(lifegame, 100);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment