Search code examples
javapositioncoordinatesneighbours

Java: Finding neighbours of a start coordinate (0,0)


I've been having an issue figuring out how I can search arround a coordinate to find its neighbours. It will make more sense when you see the picture.

I have 7 hexagons and they all have respective coordinates where the center one is (0,0). I wish to create a method in which I can add all neighbour hexagons to an arraylist, but I'm having a difficult time figuring out how I can determine that the added hexagon is in fact an neighbour.

Picture here: enter image description here

Example: (Reference to picture)

I wish to know which neighbours the hexagon on position (0,-1) has. By looking at the picture I can see it has (1,0) , (0,0) and (-1,-1). But how would I loop through this and find its neighbours in java code?


Solution

  • I'm going to make some assumptions and try to present an answer. Please comment if something changes or doesn't sit right.

    From the looks of it your grid is square. What I mean by that, both the X and the Y coordinate are specified in the same range. Consider the following class:

    public class HexagonalGrid {
      // Helper class Cell
      public static class Cell {
        public int x;
        public int y;
    
        public Cell(int x, int y) {
          this.x = x;
          this.y = y;
        }
      }
    
    
      // ranges are
      // x -> [-width, width]
      // y -> [-height, height]
      private int width;
      private int height;
    
      public HexagonalGrid(int width, int height) {
        this.width = width;
        this.height = height;
      }
    
      public ArrayList<Cell> getNeighbours(Cell target)  {
        ArrayList<Cell> neighbours = new ArrayList<>();
    
        // These coordinates are predictable, so let's generate them
        // Each immediate 
        for (int x_offset = -1; x_offset <= 1; x_offset++) {
          for (int y_offset = -1; y_offset <= 1; y_offset++) {
            // No offset puts us back at target cell so skip
            if (x_offset == 0 && y_offset == 0) { 
              continue;
            }
    
            // Generate the cell with the offset
            int x = target.x + x_offset;
            int y = target.y + y_offset;
    
            // Check validity against bounds
            if (isValidCoordinate(x, y)) {
              // Add valid neighbour
              Cell neighbour = new Cell(x, y);
              neighbours.add(neighbour);
            }
          }
        }
    
        return neighbours;
      }
    
    
      private boolean isValidCoordinate(int x, int y) {
        // Enforcing the ranges specified above
        return -width <= x && x <= width
            && -height <= y && y <= height;
      }
    }