android原生实现生命游戏,沙堆模型
生命游戏 效果截图
绘制一条线迭代为谢尔宾斯基三角形
核心代码
/**
* 计算下一代
*/
public int[][] calculationNextCell(){
//创建下一代细胞
int[][] nextCells=new int[cells.length][cells[0].length];
//根据上一代细胞计算下一代细胞的权重
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
if (cells[i][j]==3){
checkedNextCell(i, j, nextCells);
}
if (i>=10&&j>=10){
if (nextCells[i-10][j-10]==3){
// 权重为3为出生
nextCells[i-10][j-10]=3;
}else if (nextCells[i-10][j-10]==2){
// 权重为2 和上一代一样保持不变
nextCells[i-10][j-10]= cells[i-10][j-10];
}else {
// 其他权重 重置为0
nextCells[i-10][j-10]=0;
}
}
}
}
// 减少循环次数
for (int i = nextCells.length-10; i < nextCells.length; i++) {
for (int j = nextCells[i].length-10; j < nextCells[i].length; j++) {
if (nextCells[i][j]==3){
nextCells[i][j]=3;
}else if (nextCells[i][j]==2){
nextCells[i][j]= cells[i][j];
}else {
nextCells[i][j]=0;
}
}
}
cells =nextCells;
// allHabit.push(habit);
return cells;
}
/**
* * 对坐标(+i,+j)点细胞 周围的每个点权重+1
* @param i
* @param j
*/
private void checkedNextCell(int i, int j, int cells[][]) {
if (i+1<cells.length){
// 边界判断是否超出右边界
++cells[i+1][j];
}
if (i-1>=0){
// 边界判断是否超出左边界
++cells[i-1][j];
}
if (j-1>=0){
// 边界判断是否超出上边界
++cells[i][j-1];
}
if (j+1<cells[i].length){
// 边界判断是否超出下边界
++cells[i][j+1];
}
if (i+1<cells.length&&j-1>=0){
// 边界判断是否超出右上边界
++cells[i+1][j-1];
}
if (i+1<cells.length&&j+1<cells[i].length){
// 边界判断是否超出右下边界
++cells[i+1][j+1];
}
if (i-1>=0&&j+1<cells[i].length){
// 边界判断是否超出左下边界
++cells[i-1][j+1];
}
if (i-1>=0&&j-1>=0){
// 边界判断是否超出左下边界
++cells[i-1][j-1];
}
}
沙堆模型游戏 效果截图
核心代码
下面展示一些 内联代码片
。
/**
* 计算下一代(模拟在点(sendDune.length/2,sendDune.length/2)处不停滴落沙子)
* @return
*/
public int[][] nextSandDune() {
sendDune[ sendDune.length/2][ sendDune[0].length/2]++;
if (sendDune[ sendDune.length/2][ sendDune[0].length/2]==maxCount){
sendDune[ sendDune.length/2][ sendDune.length/2]=0;
sendAway( sendDune.length/2, sendDune.length/2,sendDune);
}
return sendDune;
}
/**
* 这里采用递归模拟沙堆分散
* @param i
* @param j
* @param sendDune
*/
private void sendAway(int i,int j,int[][] sendDune) {
if (i+1<sendDune.length){
// 边界判断是否超出右边界
if (++sendDune[i+1][j]==maxCount){
sendDune[i+1][j]=0;
sendAway(i+1,j,sendDune);
}
}
if (i-1>=0){
// 边界判断是否超出左边界
if (++sendDune[i-1][j]==maxCount){
sendDune[i-1][j]=0;
sendAway(i-1,j,sendDune);
}
}
if (j-1>=0){
// 边界判断是否超出上边界
if (++sendDune[i][j-1]==maxCount){
sendDune[i][j-1]=0;
sendAway(i,j-1,sendDune);
}
}
if (j+1<sendDune[i].length){
// 边界判断是否超出下边界
if (++sendDune[i][j+1]==maxCount){
sendDune[i][j+1]=0;
sendAway(i,j+1,sendDune);
}
}
}