Skip to content

Instantly share code, notes, and snippets.

@siwasu17
Created November 23, 2013 14:17
Show Gist options
  • Save siwasu17/7615067 to your computer and use it in GitHub Desktop.
Save siwasu17/7615067 to your computer and use it in GitHub Desktop.
function Sleep( T ){
var d1 = new Date().getTime();
var d2 = new Date().getTime();
while( d2 < d1+1000*T ){ //T秒待つ
d2=new Date().getTime();
}
return;
};
var Cell = function(){
this.currentState;
this.nextState;
};
Cell.ALIVE = 1;
Cell.DEAD= 0;
Cell.prototype = {
isAlive: function(){
if(this.currentState == Cell.ALIVE){
return true;
}else{
return false;
}
},
getState: function(){
return this.currentState;
},
setState: function(state){
this.currentState = state;
},
setNextState: function(state){
this.nextState = state;
},
update: function(){
this.currentState = this.nextState;
}
};
var CellGrid = function(x,y){
this.width = x;
this.height = y;
this.grid = new Array();
for(var i = 0;i < x;i++){
this.grid.push(new Array());
for(var j = 0;j < y;j++){
this.grid[i].push(new Cell());
}
}
};
CellGrid.prototype = {
load: function(stateArray){
//サイズチェック入れたい
for(var i = 0;i < this.width;i++){
for(var j = 0;j < this.height;j++){
this.grid[i][j].setState(stateArray[i][j]);
}
}
console.log(this.toString());
},
toString: function(){
var s = "";
for(var i = 0;i < this.width;i++){
for(var j = 0;j < this.height;j++){
s += (this.grid[i][j].isAlive() ? "*" : " ") + " ";
}
s += "\n";
}
return s;
},
get: function(x,y){
return this.grid[x][y];
},
prepareState: function(x,y,state){
this.grid[x][y].setNextState(state);
},
scanAll: function(){
for(var i = 0;i < this.width;i++){
for(var j = 0;j < this.height;j++){
var aliveAround = 0;
if((i != 0) && (this.grid[i-1][j].isAlive())){
//left
aliveAround++;
}
if((j != 0) && (this.grid[i][j-1].isAlive())){
//top
aliveAround++;
}
if((i != (this.width-1)) && (this.grid[i+1][j].isAlive())){
//Right
aliveAround++;
}
if((j != (this.height-1)) && (this.grid[i][j+1].isAlive())){
//Bottom
aliveAround++;
}
if(this.grid[i][j].isAlive()){
//維持されるかどうか
if((aliveAround != 2) && (aliveAround != 3)){
this.prepareState(i,j,Cell.DEAD);
}
}else{
//生まれるルール
if((aliveAround == 2) || (aliveAround == 3)){
this.prepareState(i,j,Cell.ALIVE);
}
}
}
}
},
updateAll: function(){
for(var i = 0;i < this.width;i++){
for(var j = 0;j < this.height;j++){
this.grid[i][j].update();
}
}
},
process: function(){
this.scanAll();
this.updateAll();
console.log(this.toString());
},
};
function gameStart(){
var g = new CellGrid(10,10);
var state = [
[0,0,1,1,0,0,0,0,1,1],
[1,0,1,1,0,0,0,0,1,1],
[1,0,1,1,1,1,1,0,1,1],
[1,0,1,1,0,0,0,0,1,1],
[1,0,1,1,0,1,1,0,1,1],
[0,1,0,1,0,0,1,1,1,1],
[0,0,0,1,0,0,0,0,1,1],
[0,0,0,1,0,1,1,0,1,1],
[0,0,1,1,0,0,0,0,1,1],
[0,0,1,1,0,0,0,0,1,1]
];
g.load(state);
for(var i = 0;i < 10;i++){
Sleep(1);
g.process();
}
}
//startボタン
$("#start").click(function(){
gameStart();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment