问题描述
我正在尝试用 javascript 编写康威的生活游戏。
规则是:
我已将这些规则编程到一个二维数组中,但是,有时当有一个死像素被少于三个活像素包围时,它会活跃起来,有时应该消亡的像素会保持活跃。
规则内的镜像对象应该输出相同但镜像的结果,并且与我的代码不一致。这让我相信检查声音的代码存在错误,而不是检查给定像素周围活动像素(计数器)数量的代码。但是,我无法在这里找到错误。也许我太累了,错过了一些非常明显的东西。我确定有更好的方法可以做到这一点,但这段代码应该可以工作,不是吗?
请原谅这种奇怪的格式,我只是想尽可能地让自己清楚,以确保它正确检查自身周围的所有八个像素。
for (var x = 0; x < xPixels; x++) {
for(var y = 0; y < yPixels; y++){
counter = 0;
if(y+1<yPixels){ //not below screen
if(x-1>=0){ if(pixels[x-1][y+1]) {counter++;}} //bottom left
if(pixels[x+0][y+1]) {counter++;} //bottom middle
if(x+1<xPixels){ if(pixels[x+1][y+1]) {counter++;}} //bottom right
} //in-line
if(x-1>=0){ if(pixels[x-1][y+0]) {counter++;}} //left
if(x+1<xPixels){ if(pixels[x+1][y+0]) {counter++;}} //right
if (y-1>=0){ //not above screen
if(x-1>=0){ if(pixels[x-1][y-1]) {counter++;}} //top left
if(pixels[x+0][y-1]) {counter++;} //top middle
if(x+1<xPixels){ if(pixels[x+1][y-1]) {counter++;}} //top right
}
if (pixels[x][y]){ //alive
if(counter<2 || counter>3) {
newPixels[x][y]=false; //dies
} else {
newPixels[x][y]=true; //stays alive
}
} else { //dead
if(counter==3){
newPixels[x][y]=true; //born
} else {
newPixels[x][y]=false; //stays dead
}
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)