規則
每個格子的生死遵循下面的原則:
如果一個細胞周圍有3個細胞為生(一個細胞周圍共有8個細胞),則該細胞為生(即該細胞若原先為死,則轉為生,若原先為生,則保持不變) 。
如果一個細胞周圍有2個細胞為生,則該細胞的生死狀態保持不變;
在其它情況下,該細胞為死(即該細胞若原先為生,則轉為死,若原先為死,則保持不變)
代碼
/**
* @desc 求周圍的存活的細胞個數
* @param map 當前細胞地圖
* @param x y 當前細胞位置
*/
round: (map,x,y) =>{
let count = 0
map.forEach((row,i) =>{
row.forEach((col,j) =>{
if((Math.abs(i-x) == 1 || Math.abs(j-y) == 1)
&& Math.abs(i-x) < 2 && Math.abs(j-y) < 2)
count += map[i][j] ? map[i][j] : 0
})
})
return count
}
/**
* @desc 返回一個細胞下一時間的狀態
* @param status 細胞當前狀態 0:死 1:活
* @param count 細胞當前周圍的存活細胞數量
*/
nextCellStatus: (status,count) =>{
if(count == 3) return 1
if(count == 2) return status
return 0
}
/**
* @desc 生成下一時刻的地圖
* @param 當前時刻的map
* @return 下一時刻的map
*/
nextMap: (map) =>{
let newmap = map.map(row => row.map(col => 0))
map.map((row,i) =>{
row.map((col,j) =>{
const count = round(map,i,j)
newmap[i][j] = nextCellStatus(map[i][j],count)
})
})
return newmap
}
其他
我已經把這個代碼封裝成一個npm包。通過 npm install lifegame
即可安裝。
有時間我會寫一篇關于如何寫一個npm包,然后在github上集成travis-ci進行自動化測試以及codecov進行代碼覆蓋率測試。