gpt4 book ai didi

java - 康维斯生命游戏麻烦 [java]

转载 作者:行者123 更新时间:2023-12-01 10:33:59 25 4
gpt4 key购买 nike

public static boolean[][] calculate(boolean cellState[][])//imports cell patern(in the form of a graph)
{
int x = 0, y = 0;
int alive = 0;
boolean newCellState[][] = new boolean[50][50];//what the next generation is stored in

while(x < 50 && y < 50)//calculation loop
{
try//each adjacent cell
{
if(cellState[x-1][y] == true)
alive++; //if the adjacent cell is alive the alive variable gets + 1
}catch(IndexOutOfBoundsException e) {}

try
{
if (cellState[x-1][y-1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }

try
{
if(cellState[x-1][y+1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }

try
{
if (cellState[x][y+1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }

try
{
if (cellState[x][y-1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }

try
{
if(cellState[x+1][y] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }

try
{
if(cellState[x+1][y-1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }

try
{
if(cellState[x+1][y+1] == true)
alive++;
} catch(IndexOutOfBoundsException e) { }

if(cellState[x][y] = true) //determines if the cell should be alive in the next generation
{
if(alive < 2)
newCellState[x][y] = false;
else if(alive > 3)
newCellState[x][y] = false;
else if(alive == 2)
newCellState[x][y] = true;//stores in new cell state for next gen
else
newCellState[x][y] = true;
} else
{
newCellState[x][y] = false;
}

alive = 0; //resets alive

if(x == 49)//counter for graph
{
y++;
x=0;
}else
{
x++;
}
}

return newCellState;
}

这是我用来计算下一代康威生命游戏的方法。每次运行时,无论模式是什么,它都会将除网格边缘之外的每个单元格打印为死单元格。

这是主要方法:

public static void main(String Args[])
{
int x = 0;
int y = 0;
boolean cellState[][] = new boolean[50][50];
String answer;
Scanner input = new Scanner(System.in);

while(true)
{
System.out.print("\n Type anything for next generation, 'new' for new grid, or 'stop' to end>> ");
answer = input.nextLine();
if(answer.equals("new"))
{
cellState = newCells();
}else if(answer.equals("stop"))
{
break;
}else
{
cellState = calculate(cellState);
print(cellState);
}

}


}

我已经测试了打印方法,所以没有问题。我只是不明白它为什么这样做。感谢所有帮助!谢谢!

最佳答案

使用 == 进行测试,而不是 =

= 在 if 条件下不会满足您的目的。

关于java - 康维斯生命游戏麻烦 [java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914343/

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