1 Star 1 Fork 0

zhangshenhua/game-of-life

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
evolution.js 1.75 KB
一键复制 编辑 原始数据 按行查看 历史
/**
* Conway's Game of Life
* A "cellular automaton" zero-player mathematical game.
*
* Author: Leo Deng
* URL: https://github.com/myst729/game-of-life
*/
// Evolve the next generation of cells.
var onmessage = function(e) {
var cells = e.data;
var next = [];
var neighbors;
var my_mod = function(x,m) {
return (m+x) % m;
}
for(var i = 0, l = cells.length; i < l; i++) {
next[i] = [];
for(var j = 0, k = cells[i].length; j < k; j++) {
/*
if(i === 0 || j === 0 || i === l-1 || j === k-1) {
next[i][j] = 0; // shim cells
} else
*/
{
// Get the number of live neighbors (8 neighbors in total).
neighbors = cells[my_mod(i-1, l)][my_mod(j-1, k)] +
cells[my_mod(i-1, l)][my_mod(j , k)] +
cells[my_mod(i-1, l)][my_mod(j+1, k)] +
cells[my_mod(i , l)][my_mod(j-1, k)] +
cells[my_mod(i , l)][my_mod(j+1, k)] +
cells[my_mod(i+1, l)][my_mod(j-1, k)] +
cells[my_mod(i+1, l)][my_mod(j , k)] +
cells[my_mod(i+1, l)][my_mod(j+1, k)];
if(cells[i][j] === 0 && neighbors === 3) {
// Any dead cell with exactly 3 live neighbors becomes a live cell, as if by reproduction.
next[i][j] = 1;
} else if(cells[i][j] === 1 && neighbors > 1 && neighbors < 4) {
// Any live cell with 2 or 3 live neighbors lives on to the next generation.
next[i][j] = 1;
} else {
// Live cell dies, caused by under-population (fewer than 2 live neighbors) or overcrowding (more than 3 live neighbors).
// Dead cell remains dead.
next[i][j] = 0;
}
}
}
}
postMessage(next);
};
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/zhangshenhua/game-of-life.git
git@gitee.com:zhangshenhua/game-of-life.git
zhangshenhua
game-of-life
game-of-life
gh-pages

搜索帮助