Gleb Gleb - 6 months ago 7
Java Question

What is the best way to add cell neighbors

I have a grid, grid is and 2-demension array of Cell object.

public class Cell
{
int x;
int y;
ArrayList<Cell> nighbors=new ArrayList<Cell>();

public void addNeighbor(Cell cell)
{
this.neighbors.add(cell);
}
}


Every cell have 8 neighbors:

enter image description here

And also, one more, field is looped, like on the picture below:

enter image description here

So the neighbors for Cell(0,1) are also cells (5,0), (5,1), (5,2).

Now I fill neigbors like that:

public void addNeigbors(int x, int y)
{
Cell curentCell=grid[x][y];
if(x==0)
{
if(y==0)
{
curentCell.addNiegbor(this.cells[this.width-1][this.height-1]);
curentCell.addNiegbor(this.cells[x][this.height-1]);
curentCell.addNiegbor(this.cells[x+1][this.height-1]);
curentCell.addNiegbor(this.cells[x+1][y]);
curentCell.addNiegbor(this.cells[x+1][y+1]);
curentCell.addNiegbor(this.cells[x][y+1]);
curentCell.addNiegbor(this.cells[this.width-1][y+1]);
curentCell.addNiegbor(this.cells[this.width-1][y]);
}
else if(y==this.height-1)
{
// similar code
}
else
{
// and so on
}
}
// and so on
}


This code make my cry but I have no idea to make it better.

What can you advise me?

Answer

Something like this :

public void addNeigbors(int x, int y)
{
  Cell curentCell=grid[x][y];
  int xp1 = (x+1)%width;
  int xm1 = (x-1+width)%width;
  int yp1 = (y+1)%height;
  int ym1 = (y-1+height)%height;
  curentCell.addNiegbor(this.cells[xp1][y]);
  curentCell.addNiegbor(this.cells[xp1][yp1]);
  curentCell.addNiegbor(this.cells[xp1][ym1]);
  curentCell.addNiegbor(this.cells[x][yp1]);
  curentCell.addNiegbor(this.cells[x][ym1]);
  curentCell.addNiegbor(this.cells[xm1][y]);
  curentCell.addNiegbor(this.cells[xm1][yp1]);
  curentCell.addNiegbor(this.cells[xm1][ym1]);
}        
Comments