Monday, 26 August 2013

Checking a grid, throwing out of bounds exceptions

Checking a grid, throwing out of bounds exceptions

Currently, I'm trying to check a grid cells for data in all cells around
it. Up, left, down, right, and all diagonals. How can I use exception
throwing so I don't have to individually code the sides and corners?
This is currently what I have. isIsAlive() simply checks to see if the
cell is "active". Neighbors for a cell include all active cells around it.
public void calcNeighbors() throws ArrayIndexOutOfBoundsException{
int x =0;
int y =0;
int neighbors = 0;
while(x < 9){
while(y < 9){
if(generation[x+1][y+1].isIsAlive()){
neighbors++;
}
if(generation[x+1][y].isIsAlive()){
neighbors++;
}
if(generation[x+1][y-1].isIsAlive()){
neighbors++;
}
if(generation[x][y-1].isIsAlive()){
neighbors++;
}
if(generation[x-1][y-1].isIsAlive()){
neighbors++;
}
if(generation[x-1][y].isIsAlive()){
neighbors++;
}
if(generation[x-1][y+1].isIsAlive()){
neighbors++;
}
if(generation[x][y+1].isIsAlive()){
neighbors++;
}
y++;
}
x++;
neighbors = 0;
}
}

No comments:

Post a Comment