【讨论1】关于Field.getNeighbour()
为什么Field.getNeighbour()不直接看Cell.isAlive()来返回一个数字,而是要返回一个数组让外面来数数?
代码更改:
改之前的Field 和 CellMechine
public Cell[] getNeighbour(int row, int col) {
ArrayList<Cell> list = new ArrayList<Cell>();//储存细胞
int sum=0;
//遍历周围方框
for ( int i=-1; i<2; i++ ) {
for ( int j=-1; j<2; j++ ) {
int r = row+i;
int c = col+j;//r,c为方位
if ( r >-1 && r<height && c>-1 && c<width && !(r== row && c == col) )
{//最上边 最下边 最左边 最右边 不计算当前位置存活
list.add(field[r][c]);
}
}
}
return list.toArray(new Cell[list.size()]);//返回获取到的细胞数组
}
Cell[] neighbour = field.getNeighbour(row, col);
//统计周围细胞的存活情况
int numOfLive=0;
for ( Cell c : neighbour ) {
if ( c.isAlive() ) {
numOfLive++;
}
}
改之后的代码:
public int getNeighbour(int row, int col) {
ArrayList<Cell> list = new ArrayList<Cell>();//储存细胞
int sum=0;
//遍历周围方框
for ( int i=-1; i<2; i++ ) {
for ( int j=-1; j<2; j++ ) {
int r = row+i;
int c = col+j;//r,c为方位
if ( r >-1 && r<height && c>-1 && c<width && !(r== row && c == col) )
{//最上边 最下边 最左边 最右边 不计算当前位置存活
list.add(field[r][c]);
}
}
}
Cell[] cells=list.toArray(new Cell[list.size()]);
for(int c=0;c<cells.length;c++)
{
if(cells[c].isAlive()) {
sum++;
}
}
return sum;
}
// Cell[] neighbour = field.getNeighbour(row, col);
//统计周围细胞的存活情况
// int numOfLive=0;
int numOfLive = field.getNeighbour(row, col);
// for ( Cell c : neighbour ) {
// if ( c.isAlive() ) {
// numOfLive++;
// }
// }
改之前Filed只是Cell的容器,只储存Cell的对象就可以啦,修改之后,Filed需要创建额外的Cell变量去接管数组,并且要调用Cell的isAlive()函数,他们之间的耦合更紧了。