您的位置:首页 > 其它

生命游戏

2014-10-05 12:21 190 查看
理论;

生命游戏(game of life)為1970年由英国数学家J. H. Conway所提出,某一细胞的邻居包括上、下、左、右、左上、左下、右上与右下相邻之细胞,游戏规则如下:

孤单死亡:如果细胞的邻居小於一个,则该细胞在下一次状态将死亡。

拥挤死亡:如果细胞的邻居在四个以上,则该细胞在下一次状态将死亡。

稳定:如果细胞的邻居為二个或三个,则下一次状态為稳定存活。

復活:如果某位置原无细胞存活,而该位置的邻居為三个,则该位置将復活一细

解法;

生命游戏的规则可简化為以下,并使用CASE比对即可使用程式实作:

邻居个数為0、1、4、5、6、7、8时,则该细胞下次状态為死亡。

邻居个数為2时,则该细胞下次状态為復活。

邻居个数為3时,则该细胞下次状态為稳定。

package 经典;

public class LifeGame {

private boolean[][] map;
private boolean[][] newMap;

public LifeGame(int row,int col){
map=new boolean[row][col];
newMap=new boolean[row][col];

for(int i=0; i<row; i++)
for(int j=0; j<col; j++)
map[i][j]=true;
}
public void setCell(int x, int y) {
map[x][y] = true;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
LifeGame lifeGame=new LifeGame(10, 25);
int n=0;
while(n<1000)
{
lifeGame.next();
lifeGame.outputMap();
n++;
}
}

public void next(){

for(int row=0; row<map.length; row++)
{
for(int col=0; col<map[row].length; col++)
{
switch(neighbor(row,col))
{
case 0:
case 1:
case 4:
case 5:
case 6:
case 7:
case 8:
newMap[row][col]=false;
break;
case 2:
newMap[row][col]=map[row][col];
break;
case 3:
newMap[row][col]=true;
break;
}
}
}
colyMap();
}

private int neighbor(int row, int col) {
// TODO Auto-generated method stub
int count=0;
for(int i=row-1; i<=row+1; i++)
{
for(int j=col-1; j<=col+1; j++)
{
if( i<0 || i>=map.length || j<0 || j>=map[i].length-1)
continue;
if(map[i][j]==true)
count++;
}
}
if(map[row][col]==true)
count--;
return count;
}

private void colyMap() {
// TODO Auto-generated method stub
for(int row=0; row<map.length; row++)
{
for(int col=0; col<map[row].length; col++)
{
map[row][col]=newMap[row][col];
}
}
}

public void outputMap() {
System.out.println("\n\nGame of life cell status");
for(int row = 0; row < map.length; row++) {
System.out.print("\n ");
for(int col = 0; col < map[0].length; col++)
if(map[row][col] == true)
System.out.print('#');
else
System.out.print('-');
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: