游戏规则
可以把计算机中的宇宙想象成是一堆方格子构成的封闭空间,尺寸为N的空间就有NxN个格子。而每一个格子都可以看成是一个生命体,每个生命都有生和死两种状态,如果该格子生就显示黑色,死则显示白色。每一个格子旁边都有邻居格子存在,如果我们把3*3的9个格子构成的正方形看成一个基本单位的话,那么这个正方形中心的格子的邻居就是它旁边的8个格子。
每个格子的生死遵循下面的原则:
1. 如果一个细胞周围有3个细胞为生(一个细胞周围共有8个细胞),则该细胞为生(即该细胞若原先为死,则转为生,若原先为生,则保持不变) 。
2. 如果一个细胞周围有2个细胞为生,则该细胞的生死状态保持不变;
3. 在其它情况下,该细胞为死(即该细胞若原先为生,则转为死,若原先为死,则保持不变)
代码实现:
Cell.java
public class Cell {
private int maxLength;
private int maxWidth;
private int nowGeneration;
private int[][] grid; //一个数据代表一个细胞,0代表死,1代表活
public Cell(int maxLength, int maxWidth) {
this.maxLength = maxLength;
this.maxWidth = maxWidth;
nowGeneration = 0;
grid = new int[maxLength + 2][maxWidth + 2];
for (int i = 0; i <= maxLength + 1; i++) {
for (int j = 0; j <= maxWidth + 1; j++)
grid[i][j] = 0;
}
}
public void setGrid(int[][] grid) {
this.grid = grid;
}
public int[][] getGrid() {
return grid;
}
public void setNowGeneration(int nowGeneration){
this.nowGeneration = nowGeneration;
}
public int getNowGeneration(){
return nowGeneration;
}
//随机初始化细胞
public void randomCell(){
for (int i = 1; i <= maxLength; i++)
for (int j = 1; j <= maxWidth; j++)
grid[i][j] = Math.random()>0.5?1:0;
}
//细胞清零
public void deleteAllCell(){
for (int i = 1; i <= maxLength; i++)
for (int j = 1; j <= maxWidth; j++)
grid[i][j] = 0;
}
//繁衍
public void update() {
int[][] newGrid = new int[maxLength + 2][maxWidth + 2];
for (int i = 1; i <= maxLength; i++)
for (int j = 1; j <= maxWidth; j++)
switch (getNeighborCount(i, j)) {
case 2:
newGrid[i][j] = grid[i][j]; //细胞状态保持不变
break;
case 3:
newGrid[i][j] = 1; // Cell is alive.
break;
default:
newGrid[i][j] = 0; // Cell is dead.
}
for (int i = 1; i <= maxLength; i++)
for (int j = 1; j <= maxWidth; j++)