Skip to content

Instantly share code, notes, and snippets.

@nakasyou
Created July 23, 2023 00:51
Show Gist options
  • Save nakasyou/cfa49d61efbfd6ad33185748180b91c0 to your computer and use it in GitHub Desktop.
Save nakasyou/cfa49d61efbfd6ad33185748180b91c0 to your computer and use it in GitHub Desktop.
ライフゲームのJavaScript実装、コアのみ
class LifeGame {
constructor (w, h) {
this.w = w;
this.h = h;
this.board = [...Array(w)].map(()=>[...Array(h)].map(()=>Math.random()>0.5)); // Init board
}
step () {
const newBoard = [];
for (const [x,w] of enumerate(this.board)) {
const wArr = [];
newBoard.push(wArr);
for (const [y,h] of enumerate(w)) {
const countedCellsAround = this.countCellsAround(x,y);
if (h) {
// 生きている
if (countedCellsAround === 2 || countedCellsAround === 3) {
wArr.push(true); // 生存
}else if (countedCellsAround <= 1) {
wArr.push(false); // 過疎
}else {
wArr.push(false); // 過密
}
} else {
// 死んでいる
if (countedCellsAround === 3) {
wArr.push(true); // 誕生
} else {
wArr.push(false); // 死んだまま
}
}
}
}
this.board = newBoard;
}
countCellsAround (x, y) {
const area = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
let count = 0;
for (const [biasX, biasY] of area) {
let indexX = x + biasX;
let indexY = y + biasY;
if (indexX >= this.w) {
indexX = 0;
}
if (indexX >= this.y) {
indexY = 0;
}
if (this.board.at(indexX).at(indexY)) {
count += 1;
}
}
return count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment