我无法在我的代码中实现边缘检查算法。我写了代码的内容。在不检查错误的情况下,它总是会抛出一个ArrayIndexOutOfBounds错误。
public class CreateLife {
private int dimension;
private boolean[][] world;
private long generation;
Life(int dimension){
this.dimension = dimension;
createBoard();
this.generation = 0;
}
// Randomly decides which cells are alive or dead in starting generation.
private void createBoard(){
boolean[][] board = new boolean[dimension][dimension];
for(int row = 0; row < board.length; row++ ){
for(int col = 0; col < board[row].length; col++ ){
board[row][col] = (Math.random() < 0.3);
}
}
world = board;
}
// Makes the intial gameboard array.
public void makeWorld(){
System.out.println(" ");
System.out.println("Generation:" + generation);
for(int row = 0; row < world.length; row++ ){
for(int col = 0; col < world[row].length; col++ ){
System.out.print(world[row][col] ? '*' : ' ');
System.out.print(' ');
}
System.out.println();
}
}
// Second array/ gameboard to store next generation
public void nextGeneration(int genCheck){
boolean[][] newWorld = new boolean[dimension][dimension];
for(int row = 0; row < newWorld.length; row++ ){
for(int col = 0; col < newWorld[row].length; col++ ){
newWorld[row][col] = isAlive(row, col);
}
}
world = newWorld;
generation++;
//Exits program if user input generation is met
if (generation == genCheck + 1)
{
System.out.println("Thank you for playing the Game Of Life");
System.exit(0);
}
}
// THIS IS WHERE I AM HAVING ISSUES
private boolean isAlive(int r, int c){
int count = 0;
boolean checkEdge;
boolean cellCurrentlyAlive = world[r][c];
if (world [r - 1][ c -1] = true) {
count++;
}
if (world [r - 1][ c ] = true) {
count++;
}
if (world [r - 1][ c + 1] = true) {
count++;
}
if (world [r][ c - 1] = true) {
count++;
}
if (world [r ][ c + 1] = true) {
count++;
}
if (world [r + 1][ c - 1] = true) {
count++;
}
if (world [r + 1][ c] = true) {
count++;
}
if (world [r + 1][ c + 1] = true) {
count++;
}
if(cellCurrentlyAlive){
count--;
}
// The game of life rules coded
if(count == 2 && cellCurrentlyAlive){
return true;
} else if(count == 3){
return true;
} else {
return false;
}
}
我确实知道如何使用这些if语句查找边缘
public class LifeUtils
{
public static boolean isEdge(char[][] w, int r, int c)
{
//it it in an edge ?
if((r == 0) || (r == w.length-1) || (c == 0) || (c == w.length-1))
return true;
else
return false;
}
public static boolean isTopEdge(int r, int c)
{
if(r == 0)
return true;
else
return false;
}
public static boolean isBottomEdge(int r, char[][] w)
{
if(r == w.length-1)
return true;
else
return false;
}
public static boolean isLeftEdge(int c)
{
if(c == 0)
return true;
else
return false;
}
public static boolean isRightEdge(int c, char[][] w)
{
if(c == w.length-1)
return true;
else
return false;
}
}
有人可以帮我开始使用算法吗?这将不胜感激。