gpt4 book ai didi

java - 调用/调用 void 方法(Java 作业 - 生命游戏示例)

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:19 26 4
gpt4 key购买 nike

我在操作此生命游戏示例代码中的数组时遇到问题。

情况:
“生命游戏”是约翰·康威发明的一种细胞自动化技术。它由一个细胞网格组成,这些细胞可以根据数学规则生存/死亡/繁殖。该网格中的活细胞和死细胞通过 next() 方法进行操作,nPals 是网格的初始状态。

问题:
我的问题 - 我知道这是相当基本的 - 是如何使用 nPals 上的 next() 方法来进入下一阶段?

尝试:
到目前为止,我的尝试大致如下 - 回顾起来,这两者似乎非常相似。

  • nPals.next();
  • int newNPALS[][] = nPals.next();//然后打印数组 newNPALS

任何想法将不胜感激!

代码:

public class GameOfLife {
static int nPals[][] = {
{0,0,0,0,0,0,0},
{0,1,2,3,2,1,0},
{0,2,102,104,102,2,0},
{0,3,104,8,104,3,0},
{0,2,102,104,102,2,0},
{0,1,2,3,2,1,0},
{0,0,0,0,0,0,0}
};
public static void main(String[] args) {
//Initial Stage
System.out.println(" >>First Stage<<");
printMatrix(nPals);
//Second Stage
System.out.println("\n >>Second Stage<<");
printMatrix(nPals);
}//end main

static Stack<Integer>stk=new Stack<Integer>();
static final int LIVE=100;
static final int MAXGRIDSIZE=1024;
public static void next(){
for (int i=0;i<nPals.length;i++){
for(int j=0;j<nPals[i].length;j++){
switch(nPals[i][j]){
case LIVE+0:case LIVE+1:case LIVE+4:
case LIVE+5:case LIVE+6:case LIVE+7:
stk.push(-(i*MAXGRIDSIZE+j)); //death
nPals[i][j]-=LIVE;
break;
case 3:
stk.push(i*MAXGRIDSIZE+j); //life
nPals[i][j]+=LIVE;
break;
}//end switch
}//end for j
}//end for i
while(!stk.isEmpty()){
int k=stk.pop();
if(k>0)inc(k/MAXGRIDSIZE,k%MAXGRIDSIZE);
else{
k=-k;
dec(k/MAXGRIDSIZE,k%MAXGRIDSIZE);
}//end if
}//end while
}//end next

private static void inc(int i, int j) {

}

private static void dec(int i, int j){
if(i!=0){
//3 squares on top
if(j!=0) minus(i-1,j-1);
minus(i-1,j);
if(j!=nPals[i].length-1)minus(i-1,j+1);
}
//2 on either side
if(j!=0)minus(i,j-1);
if(j!=nPals[i].length-1)minus(i,j+1);
if(i!=nPals.length-1){
//3 squares on bottom
if(j!=0)minus(i+1,j-1);
minus(i+1,j);
if(j!=nPals[i].length-1)minus(i+1,j+1);
}
}

private static void minus(int i, int j){
if(nPals[i][j]>0)nPals[i][j]--;
}
private static void plus(int i, int j){
if(nPals[i][j]<=0)nPals[i][j]++;
}

//This is just for explaining printMatrix above, otherwise immaterial
public static <E> void printMatrix(int[][] m){
for(int[] rows:m){
System.out.println(Arrays.toString(rows));
}
}//end printMatrix
}//end GameOfLife

输出:

   >>First Stage<<
[0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 2, 1, 0]
[0, 2, 102, 104, 102, 2, 0]
[0, 3, 104, 8, 104, 3, 0]
[0, 2, 102, 104, 102, 2, 0]
[0, 1, 2, 3, 2, 1, 0]
[0, 0, 0, 0, 0, 0, 0]

>>Second Stage<< /* currently unchanged */
[0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 2, 1, 0]
[0, 2, 102, 104, 102, 2, 0]
[0, 3, 104, 8, 104, 3, 0]
[0, 2, 102, 104, 102, 2, 0]
[0, 1, 2, 3, 2, 1, 0]
[0, 0, 0, 0, 0, 0, 0]

最佳答案

您需要一个方法来执行以下操作:

public void doTurn(int [][]m) {

//manipulate matrix

}

并为每个阶段调用它。

关于java - 调用/调用 void 方法(Java 作业 - 生命游戏示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20203218/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com